PackageManagerService.java revision 74f0a3450cd598f52b2c68c43531b1a27fb4e1ce
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.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.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.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
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.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.BackgroundDexOptJobService;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.Installer.InstallerException;
275import com.android.server.pm.PermissionsState.PermissionState;
276import com.android.server.pm.Settings.DatabaseVersion;
277import com.android.server.pm.Settings.VersionInfo;
278import com.android.server.pm.dex.DexManager;
279import com.android.server.storage.DeviceStorageMonitorInternal;
280
281import dalvik.system.CloseGuard;
282import dalvik.system.DexFile;
283import dalvik.system.VMRuntime;
284
285import libcore.io.IoUtils;
286import libcore.util.EmptyArray;
287
288import org.xmlpull.v1.XmlPullParser;
289import org.xmlpull.v1.XmlPullParserException;
290import org.xmlpull.v1.XmlSerializer;
291
292import java.io.BufferedOutputStream;
293import java.io.BufferedReader;
294import java.io.ByteArrayInputStream;
295import java.io.ByteArrayOutputStream;
296import java.io.File;
297import java.io.FileDescriptor;
298import java.io.FileInputStream;
299import java.io.FileNotFoundException;
300import java.io.FileOutputStream;
301import java.io.FileReader;
302import java.io.FilenameFilter;
303import java.io.IOException;
304import java.io.PrintWriter;
305import java.nio.charset.StandardCharsets;
306import java.security.DigestInputStream;
307import java.security.MessageDigest;
308import java.security.NoSuchAlgorithmException;
309import java.security.PublicKey;
310import java.security.SecureRandom;
311import java.security.cert.Certificate;
312import java.security.cert.CertificateEncodingException;
313import java.security.cert.CertificateException;
314import java.text.SimpleDateFormat;
315import java.util.ArrayList;
316import java.util.Arrays;
317import java.util.Collection;
318import java.util.Collections;
319import java.util.Comparator;
320import java.util.Date;
321import java.util.HashMap;
322import java.util.HashSet;
323import java.util.Iterator;
324import java.util.List;
325import java.util.Map;
326import java.util.Objects;
327import java.util.Set;
328import java.util.concurrent.CountDownLatch;
329import java.util.concurrent.Future;
330import java.util.concurrent.TimeUnit;
331import java.util.concurrent.atomic.AtomicBoolean;
332import java.util.concurrent.atomic.AtomicInteger;
333
334/**
335 * Keep track of all those APKs everywhere.
336 * <p>
337 * Internally there are two important locks:
338 * <ul>
339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
340 * and other related state. It is a fine-grained lock that should only be held
341 * momentarily, as it's one of the most contended locks in the system.
342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
343 * operations typically involve heavy lifting of application data on disk. Since
344 * {@code installd} is single-threaded, and it's operations can often be slow,
345 * this lock should never be acquired while already holding {@link #mPackages}.
346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
347 * holding {@link #mInstallLock}.
348 * </ul>
349 * Many internal methods rely on the caller to hold the appropriate locks, and
350 * this contract is expressed through method name suffixes:
351 * <ul>
352 * <li>fooLI(): the caller must hold {@link #mInstallLock}
353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
354 * being modified must be frozen
355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
357 * </ul>
358 * <p>
359 * Because this class is very central to the platform's security; please run all
360 * CTS and unit tests whenever making modifications:
361 *
362 * <pre>
363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
365 * </pre>
366 */
367public class PackageManagerService extends IPackageManager.Stub {
368    static final String TAG = "PackageManager";
369    static final boolean DEBUG_SETTINGS = false;
370    static final boolean DEBUG_PREFERRED = false;
371    static final boolean DEBUG_UPGRADE = false;
372    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
373    private static final boolean DEBUG_BACKUP = false;
374    private static final boolean DEBUG_INSTALL = false;
375    private static final boolean DEBUG_REMOVE = false;
376    private static final boolean DEBUG_BROADCASTS = false;
377    private static final boolean DEBUG_SHOW_INFO = false;
378    private static final boolean DEBUG_PACKAGE_INFO = false;
379    private static final boolean DEBUG_INTENT_MATCHING = false;
380    private static final boolean DEBUG_PACKAGE_SCANNING = false;
381    private static final boolean DEBUG_VERIFY = false;
382    private static final boolean DEBUG_FILTERS = false;
383
384    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
385    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
386    // user, but by default initialize to this.
387    public static final boolean DEBUG_DEXOPT = false;
388
389    private static final boolean DEBUG_ABI_SELECTION = false;
390    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
391    private static final boolean DEBUG_TRIAGED_MISSING = false;
392    private static final boolean DEBUG_APP_DATA = false;
393
394    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
395    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
396
397    private static final boolean DISABLE_EPHEMERAL_APPS = false;
398    private static final boolean HIDE_EPHEMERAL_APIS = false;
399
400    private static final boolean ENABLE_FREE_CACHE_V2 =
401            SystemProperties.getBoolean("fw.free_cache_v2", false);
402
403    private static final int RADIO_UID = Process.PHONE_UID;
404    private static final int LOG_UID = Process.LOG_UID;
405    private static final int NFC_UID = Process.NFC_UID;
406    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
407    private static final int SHELL_UID = Process.SHELL_UID;
408
409    // Cap the size of permission trees that 3rd party apps can define
410    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
411
412    // Suffix used during package installation when copying/moving
413    // package apks to install directory.
414    private static final String INSTALL_PACKAGE_SUFFIX = "-";
415
416    static final int SCAN_NO_DEX = 1<<1;
417    static final int SCAN_FORCE_DEX = 1<<2;
418    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
419    static final int SCAN_NEW_INSTALL = 1<<4;
420    static final int SCAN_UPDATE_TIME = 1<<5;
421    static final int SCAN_BOOTING = 1<<6;
422    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
423    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
424    static final int SCAN_REPLACING = 1<<9;
425    static final int SCAN_REQUIRE_KNOWN = 1<<10;
426    static final int SCAN_MOVE = 1<<11;
427    static final int SCAN_INITIAL = 1<<12;
428    static final int SCAN_CHECK_ONLY = 1<<13;
429    static final int SCAN_DONT_KILL_APP = 1<<14;
430    static final int SCAN_IGNORE_FROZEN = 1<<15;
431    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
432    static final int SCAN_AS_INSTANT_APP = 1<<17;
433    static final int SCAN_AS_FULL_APP = 1<<18;
434    /** Should not be with the scan flags */
435    static final int FLAGS_REMOVE_CHATTY = 1<<31;
436
437    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
438
439    private static final int[] EMPTY_INT_ARRAY = new int[0];
440
441    /**
442     * Timeout (in milliseconds) after which the watchdog should declare that
443     * our handler thread is wedged.  The usual default for such things is one
444     * minute but we sometimes do very lengthy I/O operations on this thread,
445     * such as installing multi-gigabyte applications, so ours needs to be longer.
446     */
447    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
448
449    /**
450     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
451     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
452     * settings entry if available, otherwise we use the hardcoded default.  If it's been
453     * more than this long since the last fstrim, we force one during the boot sequence.
454     *
455     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
456     * one gets run at the next available charging+idle time.  This final mandatory
457     * no-fstrim check kicks in only of the other scheduling criteria is never met.
458     */
459    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
460
461    /**
462     * Whether verification is enabled by default.
463     */
464    private static final boolean DEFAULT_VERIFY_ENABLE = true;
465
466    /**
467     * The default maximum time to wait for the verification agent to return in
468     * milliseconds.
469     */
470    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
471
472    /**
473     * The default response for package verification timeout.
474     *
475     * This can be either PackageManager.VERIFICATION_ALLOW or
476     * PackageManager.VERIFICATION_REJECT.
477     */
478    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
479
480    static final String PLATFORM_PACKAGE_NAME = "android";
481
482    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
483
484    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
485            DEFAULT_CONTAINER_PACKAGE,
486            "com.android.defcontainer.DefaultContainerService");
487
488    private static final String KILL_APP_REASON_GIDS_CHANGED =
489            "permission grant or revoke changed gids";
490
491    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
492            "permissions revoked";
493
494    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
495
496    private static final String PACKAGE_SCHEME = "package";
497
498    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
499    /**
500     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
501     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
502     * VENDOR_OVERLAY_DIR.
503     */
504    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
505    /**
506     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
507     * is in VENDOR_OVERLAY_THEME_PROPERTY.
508     */
509    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
510            = "persist.vendor.overlay.theme";
511
512    /** Permission grant: not grant the permission. */
513    private static final int GRANT_DENIED = 1;
514
515    /** Permission grant: grant the permission as an install permission. */
516    private static final int GRANT_INSTALL = 2;
517
518    /** Permission grant: grant the permission as a runtime one. */
519    private static final int GRANT_RUNTIME = 3;
520
521    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
522    private static final int GRANT_UPGRADE = 4;
523
524    /** Canonical intent used to identify what counts as a "web browser" app */
525    private static final Intent sBrowserIntent;
526    static {
527        sBrowserIntent = new Intent();
528        sBrowserIntent.setAction(Intent.ACTION_VIEW);
529        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
530        sBrowserIntent.setData(Uri.parse("http:"));
531    }
532
533    /**
534     * The set of all protected actions [i.e. those actions for which a high priority
535     * intent filter is disallowed].
536     */
537    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
538    static {
539        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
540        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
541        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
542        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
543    }
544
545    // Compilation reasons.
546    public static final int REASON_FIRST_BOOT = 0;
547    public static final int REASON_BOOT = 1;
548    public static final int REASON_INSTALL = 2;
549    public static final int REASON_BACKGROUND_DEXOPT = 3;
550    public static final int REASON_AB_OTA = 4;
551    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
552    public static final int REASON_SHARED_APK = 6;
553    public static final int REASON_FORCED_DEXOPT = 7;
554    public static final int REASON_CORE_APP = 8;
555
556    public static final int REASON_LAST = REASON_CORE_APP;
557
558    /** All dangerous permission names in the same order as the events in MetricsEvent */
559    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
560            Manifest.permission.READ_CALENDAR,
561            Manifest.permission.WRITE_CALENDAR,
562            Manifest.permission.CAMERA,
563            Manifest.permission.READ_CONTACTS,
564            Manifest.permission.WRITE_CONTACTS,
565            Manifest.permission.GET_ACCOUNTS,
566            Manifest.permission.ACCESS_FINE_LOCATION,
567            Manifest.permission.ACCESS_COARSE_LOCATION,
568            Manifest.permission.RECORD_AUDIO,
569            Manifest.permission.READ_PHONE_STATE,
570            Manifest.permission.CALL_PHONE,
571            Manifest.permission.READ_CALL_LOG,
572            Manifest.permission.WRITE_CALL_LOG,
573            Manifest.permission.ADD_VOICEMAIL,
574            Manifest.permission.USE_SIP,
575            Manifest.permission.PROCESS_OUTGOING_CALLS,
576            Manifest.permission.READ_CELL_BROADCASTS,
577            Manifest.permission.BODY_SENSORS,
578            Manifest.permission.SEND_SMS,
579            Manifest.permission.RECEIVE_SMS,
580            Manifest.permission.READ_SMS,
581            Manifest.permission.RECEIVE_WAP_PUSH,
582            Manifest.permission.RECEIVE_MMS,
583            Manifest.permission.READ_EXTERNAL_STORAGE,
584            Manifest.permission.WRITE_EXTERNAL_STORAGE,
585            Manifest.permission.READ_PHONE_NUMBER,
586            Manifest.permission.ANSWER_PHONE_CALLS);
587
588
589    /**
590     * Version number for the package parser cache. Increment this whenever the format or
591     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
592     */
593    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
594
595    /**
596     * Whether the package parser cache is enabled.
597     */
598    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
599
600    final ServiceThread mHandlerThread;
601
602    final PackageHandler mHandler;
603
604    private final ProcessLoggingHandler mProcessLoggingHandler;
605
606    /**
607     * Messages for {@link #mHandler} that need to wait for system ready before
608     * being dispatched.
609     */
610    private ArrayList<Message> mPostSystemReadyMessages;
611
612    final int mSdkVersion = Build.VERSION.SDK_INT;
613
614    final Context mContext;
615    final boolean mFactoryTest;
616    final boolean mOnlyCore;
617    final DisplayMetrics mMetrics;
618    final int mDefParseFlags;
619    final String[] mSeparateProcesses;
620    final boolean mIsUpgrade;
621    final boolean mIsPreNUpgrade;
622    final boolean mIsPreNMR1Upgrade;
623
624    @GuardedBy("mPackages")
625    private boolean mDexOptDialogShown;
626
627    /** The location for ASEC container files on internal storage. */
628    final String mAsecInternalPath;
629
630    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
631    // LOCK HELD.  Can be called with mInstallLock held.
632    @GuardedBy("mInstallLock")
633    final Installer mInstaller;
634
635    /** Directory where installed third-party apps stored */
636    final File mAppInstallDir;
637
638    /**
639     * Directory to which applications installed internally have their
640     * 32 bit native libraries copied.
641     */
642    private File mAppLib32InstallDir;
643
644    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
645    // apps.
646    final File mDrmAppPrivateInstallDir;
647
648    // ----------------------------------------------------------------
649
650    // Lock for state used when installing and doing other long running
651    // operations.  Methods that must be called with this lock held have
652    // the suffix "LI".
653    final Object mInstallLock = new Object();
654
655    // ----------------------------------------------------------------
656
657    // Keys are String (package name), values are Package.  This also serves
658    // as the lock for the global state.  Methods that must be called with
659    // this lock held have the prefix "LP".
660    @GuardedBy("mPackages")
661    final ArrayMap<String, PackageParser.Package> mPackages =
662            new ArrayMap<String, PackageParser.Package>();
663
664    final ArrayMap<String, Set<String>> mKnownCodebase =
665            new ArrayMap<String, Set<String>>();
666
667    // List of APK paths to load for each user and package. This data is never
668    // persisted by the package manager. Instead, the overlay manager will
669    // ensure the data is up-to-date in runtime.
670    @GuardedBy("mPackages")
671    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
672        new SparseArray<ArrayMap<String, ArrayList<String>>>();
673
674    /**
675     * Tracks new system packages [received in an OTA] that we expect to
676     * find updated user-installed versions. Keys are package name, values
677     * are package location.
678     */
679    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
680    /**
681     * Tracks high priority intent filters for protected actions. During boot, certain
682     * filter actions are protected and should never be allowed to have a high priority
683     * intent filter for them. However, there is one, and only one exception -- the
684     * setup wizard. It must be able to define a high priority intent filter for these
685     * actions to ensure there are no escapes from the wizard. We need to delay processing
686     * of these during boot as we need to look at all of the system packages in order
687     * to know which component is the setup wizard.
688     */
689    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
690    /**
691     * Whether or not processing protected filters should be deferred.
692     */
693    private boolean mDeferProtectedFilters = true;
694
695    /**
696     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
697     */
698    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
699    /**
700     * Whether or not system app permissions should be promoted from install to runtime.
701     */
702    boolean mPromoteSystemApps;
703
704    @GuardedBy("mPackages")
705    final Settings mSettings;
706
707    /**
708     * Set of package names that are currently "frozen", which means active
709     * surgery is being done on the code/data for that package. The platform
710     * will refuse to launch frozen packages to avoid race conditions.
711     *
712     * @see PackageFreezer
713     */
714    @GuardedBy("mPackages")
715    final ArraySet<String> mFrozenPackages = new ArraySet<>();
716
717    final ProtectedPackages mProtectedPackages;
718
719    boolean mFirstBoot;
720
721    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
722
723    // System configuration read by SystemConfig.
724    final int[] mGlobalGids;
725    final SparseArray<ArraySet<String>> mSystemPermissions;
726    @GuardedBy("mAvailableFeatures")
727    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
728
729    // If mac_permissions.xml was found for seinfo labeling.
730    boolean mFoundPolicyFile;
731
732    private final InstantAppRegistry mInstantAppRegistry;
733
734    @GuardedBy("mPackages")
735    int mChangedPackagesSequenceNumber;
736    /**
737     * List of changed [installed, removed or updated] packages.
738     * mapping from user id -> sequence number -> package name
739     */
740    @GuardedBy("mPackages")
741    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
742    /**
743     * The sequence number of the last change to a package.
744     * mapping from user id -> package name -> sequence number
745     */
746    @GuardedBy("mPackages")
747    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
748
749    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
750        @Override public boolean hasFeature(String feature) {
751            return PackageManagerService.this.hasSystemFeature(feature, 0);
752        }
753    };
754
755    public static final class SharedLibraryEntry {
756        public final String path;
757        public final String apk;
758        public final SharedLibraryInfo info;
759
760        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
761                String declaringPackageName, int declaringPackageVersionCode) {
762            path = _path;
763            apk = _apk;
764            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
765                    declaringPackageName, declaringPackageVersionCode), null);
766        }
767    }
768
769    // Currently known shared libraries.
770    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
771    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
772            new ArrayMap<>();
773
774    // All available activities, for your resolving pleasure.
775    final ActivityIntentResolver mActivities =
776            new ActivityIntentResolver();
777
778    // All available receivers, for your resolving pleasure.
779    final ActivityIntentResolver mReceivers =
780            new ActivityIntentResolver();
781
782    // All available services, for your resolving pleasure.
783    final ServiceIntentResolver mServices = new ServiceIntentResolver();
784
785    // All available providers, for your resolving pleasure.
786    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
787
788    // Mapping from provider base names (first directory in content URI codePath)
789    // to the provider information.
790    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
791            new ArrayMap<String, PackageParser.Provider>();
792
793    // Mapping from instrumentation class names to info about them.
794    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
795            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
796
797    // Mapping from permission names to info about them.
798    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
799            new ArrayMap<String, PackageParser.PermissionGroup>();
800
801    // Packages whose data we have transfered into another package, thus
802    // should no longer exist.
803    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
804
805    // Broadcast actions that are only available to the system.
806    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
807
808    /** List of packages waiting for verification. */
809    final SparseArray<PackageVerificationState> mPendingVerification
810            = new SparseArray<PackageVerificationState>();
811
812    /** Set of packages associated with each app op permission. */
813    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
814
815    final PackageInstallerService mInstallerService;
816
817    private final PackageDexOptimizer mPackageDexOptimizer;
818    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
819    // is used by other apps).
820    private final DexManager mDexManager;
821
822    private AtomicInteger mNextMoveId = new AtomicInteger();
823    private final MoveCallbacks mMoveCallbacks;
824
825    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
826
827    // Cache of users who need badging.
828    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
829
830    /** Token for keys in mPendingVerification. */
831    private int mPendingVerificationToken = 0;
832
833    volatile boolean mSystemReady;
834    volatile boolean mSafeMode;
835    volatile boolean mHasSystemUidErrors;
836
837    ApplicationInfo mAndroidApplication;
838    final ActivityInfo mResolveActivity = new ActivityInfo();
839    final ResolveInfo mResolveInfo = new ResolveInfo();
840    ComponentName mResolveComponentName;
841    PackageParser.Package mPlatformPackage;
842    ComponentName mCustomResolverComponentName;
843
844    boolean mResolverReplaced = false;
845
846    private final @Nullable ComponentName mIntentFilterVerifierComponent;
847    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
848
849    private int mIntentFilterVerificationToken = 0;
850
851    /** The service connection to the ephemeral resolver */
852    final EphemeralResolverConnection mInstantAppResolverConnection;
853
854    /** Component used to install ephemeral applications */
855    ComponentName mInstantAppInstallerComponent;
856    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
857    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
858
859    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
860            = new SparseArray<IntentFilterVerificationState>();
861
862    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
863
864    // List of packages names to keep cached, even if they are uninstalled for all users
865    private List<String> mKeepUninstalledPackages;
866
867    private UserManagerInternal mUserManagerInternal;
868
869    private DeviceIdleController.LocalService mDeviceIdleController;
870
871    private File mCacheDir;
872
873    private ArraySet<String> mPrivappPermissionsViolations;
874
875    private Future<?> mPrepareAppDataFuture;
876
877    private static class IFVerificationParams {
878        PackageParser.Package pkg;
879        boolean replacing;
880        int userId;
881        int verifierUid;
882
883        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
884                int _userId, int _verifierUid) {
885            pkg = _pkg;
886            replacing = _replacing;
887            userId = _userId;
888            replacing = _replacing;
889            verifierUid = _verifierUid;
890        }
891    }
892
893    private interface IntentFilterVerifier<T extends IntentFilter> {
894        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
895                                               T filter, String packageName);
896        void startVerifications(int userId);
897        void receiveVerificationResponse(int verificationId);
898    }
899
900    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
901        private Context mContext;
902        private ComponentName mIntentFilterVerifierComponent;
903        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
904
905        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
906            mContext = context;
907            mIntentFilterVerifierComponent = verifierComponent;
908        }
909
910        private String getDefaultScheme() {
911            return IntentFilter.SCHEME_HTTPS;
912        }
913
914        @Override
915        public void startVerifications(int userId) {
916            // Launch verifications requests
917            int count = mCurrentIntentFilterVerifications.size();
918            for (int n=0; n<count; n++) {
919                int verificationId = mCurrentIntentFilterVerifications.get(n);
920                final IntentFilterVerificationState ivs =
921                        mIntentFilterVerificationStates.get(verificationId);
922
923                String packageName = ivs.getPackageName();
924
925                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
926                final int filterCount = filters.size();
927                ArraySet<String> domainsSet = new ArraySet<>();
928                for (int m=0; m<filterCount; m++) {
929                    PackageParser.ActivityIntentInfo filter = filters.get(m);
930                    domainsSet.addAll(filter.getHostsList());
931                }
932                synchronized (mPackages) {
933                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
934                            packageName, domainsSet) != null) {
935                        scheduleWriteSettingsLocked();
936                    }
937                }
938                sendVerificationRequest(userId, verificationId, ivs);
939            }
940            mCurrentIntentFilterVerifications.clear();
941        }
942
943        private void sendVerificationRequest(int userId, int verificationId,
944                IntentFilterVerificationState ivs) {
945
946            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
949                    verificationId);
950            verificationIntent.putExtra(
951                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
952                    getDefaultScheme());
953            verificationIntent.putExtra(
954                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
955                    ivs.getHostsString());
956            verificationIntent.putExtra(
957                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
958                    ivs.getPackageName());
959            verificationIntent.setComponent(mIntentFilterVerifierComponent);
960            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
961
962            UserHandle user = new UserHandle(userId);
963            mContext.sendBroadcastAsUser(verificationIntent, user);
964            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
965                    "Sending IntentFilter verification broadcast");
966        }
967
968        public void receiveVerificationResponse(int verificationId) {
969            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
970
971            final boolean verified = ivs.isVerified();
972
973            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
974            final int count = filters.size();
975            if (DEBUG_DOMAIN_VERIFICATION) {
976                Slog.i(TAG, "Received verification response " + verificationId
977                        + " for " + count + " filters, verified=" + verified);
978            }
979            for (int n=0; n<count; n++) {
980                PackageParser.ActivityIntentInfo filter = filters.get(n);
981                filter.setVerified(verified);
982
983                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
984                        + " verified with result:" + verified + " and hosts:"
985                        + ivs.getHostsString());
986            }
987
988            mIntentFilterVerificationStates.remove(verificationId);
989
990            final String packageName = ivs.getPackageName();
991            IntentFilterVerificationInfo ivi = null;
992
993            synchronized (mPackages) {
994                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
995            }
996            if (ivi == null) {
997                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
998                        + verificationId + " packageName:" + packageName);
999                return;
1000            }
1001            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1002                    "Updating IntentFilterVerificationInfo for package " + packageName
1003                            +" verificationId:" + verificationId);
1004
1005            synchronized (mPackages) {
1006                if (verified) {
1007                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1008                } else {
1009                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1010                }
1011                scheduleWriteSettingsLocked();
1012
1013                final int userId = ivs.getUserId();
1014                if (userId != UserHandle.USER_ALL) {
1015                    final int userStatus =
1016                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1017
1018                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1019                    boolean needUpdate = false;
1020
1021                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1022                    // already been set by the User thru the Disambiguation dialog
1023                    switch (userStatus) {
1024                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1025                            if (verified) {
1026                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1027                            } else {
1028                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1029                            }
1030                            needUpdate = true;
1031                            break;
1032
1033                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1034                            if (verified) {
1035                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1036                                needUpdate = true;
1037                            }
1038                            break;
1039
1040                        default:
1041                            // Nothing to do
1042                    }
1043
1044                    if (needUpdate) {
1045                        mSettings.updateIntentFilterVerificationStatusLPw(
1046                                packageName, updatedStatus, userId);
1047                        scheduleWritePackageRestrictionsLocked(userId);
1048                    }
1049                }
1050            }
1051        }
1052
1053        @Override
1054        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1055                    ActivityIntentInfo filter, String packageName) {
1056            if (!hasValidDomains(filter)) {
1057                return false;
1058            }
1059            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1060            if (ivs == null) {
1061                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1062                        packageName);
1063            }
1064            if (DEBUG_DOMAIN_VERIFICATION) {
1065                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1066            }
1067            ivs.addFilter(filter);
1068            return true;
1069        }
1070
1071        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1072                int userId, int verificationId, String packageName) {
1073            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1074                    verifierUid, userId, packageName);
1075            ivs.setPendingState();
1076            synchronized (mPackages) {
1077                mIntentFilterVerificationStates.append(verificationId, ivs);
1078                mCurrentIntentFilterVerifications.add(verificationId);
1079            }
1080            return ivs;
1081        }
1082    }
1083
1084    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1085        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1086                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1087                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1088    }
1089
1090    // Set of pending broadcasts for aggregating enable/disable of components.
1091    static class PendingPackageBroadcasts {
1092        // for each user id, a map of <package name -> components within that package>
1093        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1094
1095        public PendingPackageBroadcasts() {
1096            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1097        }
1098
1099        public ArrayList<String> get(int userId, String packageName) {
1100            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1101            return packages.get(packageName);
1102        }
1103
1104        public void put(int userId, String packageName, ArrayList<String> components) {
1105            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1106            packages.put(packageName, components);
1107        }
1108
1109        public void remove(int userId, String packageName) {
1110            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1111            if (packages != null) {
1112                packages.remove(packageName);
1113            }
1114        }
1115
1116        public void remove(int userId) {
1117            mUidMap.remove(userId);
1118        }
1119
1120        public int userIdCount() {
1121            return mUidMap.size();
1122        }
1123
1124        public int userIdAt(int n) {
1125            return mUidMap.keyAt(n);
1126        }
1127
1128        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1129            return mUidMap.get(userId);
1130        }
1131
1132        public int size() {
1133            // total number of pending broadcast entries across all userIds
1134            int num = 0;
1135            for (int i = 0; i< mUidMap.size(); i++) {
1136                num += mUidMap.valueAt(i).size();
1137            }
1138            return num;
1139        }
1140
1141        public void clear() {
1142            mUidMap.clear();
1143        }
1144
1145        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1146            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1147            if (map == null) {
1148                map = new ArrayMap<String, ArrayList<String>>();
1149                mUidMap.put(userId, map);
1150            }
1151            return map;
1152        }
1153    }
1154    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1155
1156    // Service Connection to remote media container service to copy
1157    // package uri's from external media onto secure containers
1158    // or internal storage.
1159    private IMediaContainerService mContainerService = null;
1160
1161    static final int SEND_PENDING_BROADCAST = 1;
1162    static final int MCS_BOUND = 3;
1163    static final int END_COPY = 4;
1164    static final int INIT_COPY = 5;
1165    static final int MCS_UNBIND = 6;
1166    static final int START_CLEANING_PACKAGE = 7;
1167    static final int FIND_INSTALL_LOC = 8;
1168    static final int POST_INSTALL = 9;
1169    static final int MCS_RECONNECT = 10;
1170    static final int MCS_GIVE_UP = 11;
1171    static final int UPDATED_MEDIA_STATUS = 12;
1172    static final int WRITE_SETTINGS = 13;
1173    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1174    static final int PACKAGE_VERIFIED = 15;
1175    static final int CHECK_PENDING_VERIFICATION = 16;
1176    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1177    static final int INTENT_FILTER_VERIFIED = 18;
1178    static final int WRITE_PACKAGE_LIST = 19;
1179    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1180
1181    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1182
1183    // Delay time in millisecs
1184    static final int BROADCAST_DELAY = 10 * 1000;
1185
1186    static UserManagerService sUserManager;
1187
1188    // Stores a list of users whose package restrictions file needs to be updated
1189    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1190
1191    final private DefaultContainerConnection mDefContainerConn =
1192            new DefaultContainerConnection();
1193    class DefaultContainerConnection implements ServiceConnection {
1194        public void onServiceConnected(ComponentName name, IBinder service) {
1195            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1196            final IMediaContainerService imcs = IMediaContainerService.Stub
1197                    .asInterface(Binder.allowBlocking(service));
1198            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1199        }
1200
1201        public void onServiceDisconnected(ComponentName name) {
1202            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1203        }
1204    }
1205
1206    // Recordkeeping of restore-after-install operations that are currently in flight
1207    // between the Package Manager and the Backup Manager
1208    static class PostInstallData {
1209        public InstallArgs args;
1210        public PackageInstalledInfo res;
1211
1212        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1213            args = _a;
1214            res = _r;
1215        }
1216    }
1217
1218    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1219    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1220
1221    // XML tags for backup/restore of various bits of state
1222    private static final String TAG_PREFERRED_BACKUP = "pa";
1223    private static final String TAG_DEFAULT_APPS = "da";
1224    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1225
1226    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1227    private static final String TAG_ALL_GRANTS = "rt-grants";
1228    private static final String TAG_GRANT = "grant";
1229    private static final String ATTR_PACKAGE_NAME = "pkg";
1230
1231    private static final String TAG_PERMISSION = "perm";
1232    private static final String ATTR_PERMISSION_NAME = "name";
1233    private static final String ATTR_IS_GRANTED = "g";
1234    private static final String ATTR_USER_SET = "set";
1235    private static final String ATTR_USER_FIXED = "fixed";
1236    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1237
1238    // System/policy permission grants are not backed up
1239    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1240            FLAG_PERMISSION_POLICY_FIXED
1241            | FLAG_PERMISSION_SYSTEM_FIXED
1242            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1243
1244    // And we back up these user-adjusted states
1245    private static final int USER_RUNTIME_GRANT_MASK =
1246            FLAG_PERMISSION_USER_SET
1247            | FLAG_PERMISSION_USER_FIXED
1248            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1249
1250    final @Nullable String mRequiredVerifierPackage;
1251    final @NonNull String mRequiredInstallerPackage;
1252    final @NonNull String mRequiredUninstallerPackage;
1253    final @Nullable String mSetupWizardPackage;
1254    final @Nullable String mStorageManagerPackage;
1255    final @NonNull String mServicesSystemSharedLibraryPackageName;
1256    final @NonNull String mSharedSystemSharedLibraryPackageName;
1257
1258    final boolean mPermissionReviewRequired;
1259
1260    private final PackageUsage mPackageUsage = new PackageUsage();
1261    private final CompilerStats mCompilerStats = new CompilerStats();
1262
1263    class PackageHandler extends Handler {
1264        private boolean mBound = false;
1265        final ArrayList<HandlerParams> mPendingInstalls =
1266            new ArrayList<HandlerParams>();
1267
1268        private boolean connectToService() {
1269            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1270                    " DefaultContainerService");
1271            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1272            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1273            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1274                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1275                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1276                mBound = true;
1277                return true;
1278            }
1279            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1280            return false;
1281        }
1282
1283        private void disconnectService() {
1284            mContainerService = null;
1285            mBound = false;
1286            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1287            mContext.unbindService(mDefContainerConn);
1288            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1289        }
1290
1291        PackageHandler(Looper looper) {
1292            super(looper);
1293        }
1294
1295        public void handleMessage(Message msg) {
1296            try {
1297                doHandleMessage(msg);
1298            } finally {
1299                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300            }
1301        }
1302
1303        void doHandleMessage(Message msg) {
1304            switch (msg.what) {
1305                case INIT_COPY: {
1306                    HandlerParams params = (HandlerParams) msg.obj;
1307                    int idx = mPendingInstalls.size();
1308                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1309                    // If a bind was already initiated we dont really
1310                    // need to do anything. The pending install
1311                    // will be processed later on.
1312                    if (!mBound) {
1313                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1314                                System.identityHashCode(mHandler));
1315                        // If this is the only one pending we might
1316                        // have to bind to the service again.
1317                        if (!connectToService()) {
1318                            Slog.e(TAG, "Failed to bind to media container service");
1319                            params.serviceError();
1320                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1321                                    System.identityHashCode(mHandler));
1322                            if (params.traceMethod != null) {
1323                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1324                                        params.traceCookie);
1325                            }
1326                            return;
1327                        } else {
1328                            // Once we bind to the service, the first
1329                            // pending request will be processed.
1330                            mPendingInstalls.add(idx, params);
1331                        }
1332                    } else {
1333                        mPendingInstalls.add(idx, params);
1334                        // Already bound to the service. Just make
1335                        // sure we trigger off processing the first request.
1336                        if (idx == 0) {
1337                            mHandler.sendEmptyMessage(MCS_BOUND);
1338                        }
1339                    }
1340                    break;
1341                }
1342                case MCS_BOUND: {
1343                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1344                    if (msg.obj != null) {
1345                        mContainerService = (IMediaContainerService) msg.obj;
1346                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1347                                System.identityHashCode(mHandler));
1348                    }
1349                    if (mContainerService == null) {
1350                        if (!mBound) {
1351                            // Something seriously wrong since we are not bound and we are not
1352                            // waiting for connection. Bail out.
1353                            Slog.e(TAG, "Cannot bind to media container service");
1354                            for (HandlerParams params : mPendingInstalls) {
1355                                // Indicate service bind error
1356                                params.serviceError();
1357                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1358                                        System.identityHashCode(params));
1359                                if (params.traceMethod != null) {
1360                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1361                                            params.traceMethod, params.traceCookie);
1362                                }
1363                                return;
1364                            }
1365                            mPendingInstalls.clear();
1366                        } else {
1367                            Slog.w(TAG, "Waiting to connect to media container service");
1368                        }
1369                    } else if (mPendingInstalls.size() > 0) {
1370                        HandlerParams params = mPendingInstalls.get(0);
1371                        if (params != null) {
1372                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1373                                    System.identityHashCode(params));
1374                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1375                            if (params.startCopy()) {
1376                                // We are done...  look for more work or to
1377                                // go idle.
1378                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1379                                        "Checking for more work or unbind...");
1380                                // Delete pending install
1381                                if (mPendingInstalls.size() > 0) {
1382                                    mPendingInstalls.remove(0);
1383                                }
1384                                if (mPendingInstalls.size() == 0) {
1385                                    if (mBound) {
1386                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1387                                                "Posting delayed MCS_UNBIND");
1388                                        removeMessages(MCS_UNBIND);
1389                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1390                                        // Unbind after a little delay, to avoid
1391                                        // continual thrashing.
1392                                        sendMessageDelayed(ubmsg, 10000);
1393                                    }
1394                                } else {
1395                                    // There are more pending requests in queue.
1396                                    // Just post MCS_BOUND message to trigger processing
1397                                    // of next pending install.
1398                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1399                                            "Posting MCS_BOUND for next work");
1400                                    mHandler.sendEmptyMessage(MCS_BOUND);
1401                                }
1402                            }
1403                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1404                        }
1405                    } else {
1406                        // Should never happen ideally.
1407                        Slog.w(TAG, "Empty queue");
1408                    }
1409                    break;
1410                }
1411                case MCS_RECONNECT: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1413                    if (mPendingInstalls.size() > 0) {
1414                        if (mBound) {
1415                            disconnectService();
1416                        }
1417                        if (!connectToService()) {
1418                            Slog.e(TAG, "Failed to bind to media container service");
1419                            for (HandlerParams params : mPendingInstalls) {
1420                                // Indicate service bind error
1421                                params.serviceError();
1422                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1423                                        System.identityHashCode(params));
1424                            }
1425                            mPendingInstalls.clear();
1426                        }
1427                    }
1428                    break;
1429                }
1430                case MCS_UNBIND: {
1431                    // If there is no actual work left, then time to unbind.
1432                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1433
1434                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1435                        if (mBound) {
1436                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1437
1438                            disconnectService();
1439                        }
1440                    } else if (mPendingInstalls.size() > 0) {
1441                        // There are more pending requests in queue.
1442                        // Just post MCS_BOUND message to trigger processing
1443                        // of next pending install.
1444                        mHandler.sendEmptyMessage(MCS_BOUND);
1445                    }
1446
1447                    break;
1448                }
1449                case MCS_GIVE_UP: {
1450                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1451                    HandlerParams params = mPendingInstalls.remove(0);
1452                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1453                            System.identityHashCode(params));
1454                    break;
1455                }
1456                case SEND_PENDING_BROADCAST: {
1457                    String packages[];
1458                    ArrayList<String> components[];
1459                    int size = 0;
1460                    int uids[];
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1462                    synchronized (mPackages) {
1463                        if (mPendingBroadcasts == null) {
1464                            return;
1465                        }
1466                        size = mPendingBroadcasts.size();
1467                        if (size <= 0) {
1468                            // Nothing to be done. Just return
1469                            return;
1470                        }
1471                        packages = new String[size];
1472                        components = new ArrayList[size];
1473                        uids = new int[size];
1474                        int i = 0;  // filling out the above arrays
1475
1476                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1477                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1478                            Iterator<Map.Entry<String, ArrayList<String>>> it
1479                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1480                                            .entrySet().iterator();
1481                            while (it.hasNext() && i < size) {
1482                                Map.Entry<String, ArrayList<String>> ent = it.next();
1483                                packages[i] = ent.getKey();
1484                                components[i] = ent.getValue();
1485                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1486                                uids[i] = (ps != null)
1487                                        ? UserHandle.getUid(packageUserId, ps.appId)
1488                                        : -1;
1489                                i++;
1490                            }
1491                        }
1492                        size = i;
1493                        mPendingBroadcasts.clear();
1494                    }
1495                    // Send broadcasts
1496                    for (int i = 0; i < size; i++) {
1497                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                    break;
1501                }
1502                case START_CLEANING_PACKAGE: {
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1504                    final String packageName = (String)msg.obj;
1505                    final int userId = msg.arg1;
1506                    final boolean andCode = msg.arg2 != 0;
1507                    synchronized (mPackages) {
1508                        if (userId == UserHandle.USER_ALL) {
1509                            int[] users = sUserManager.getUserIds();
1510                            for (int user : users) {
1511                                mSettings.addPackageToCleanLPw(
1512                                        new PackageCleanItem(user, packageName, andCode));
1513                            }
1514                        } else {
1515                            mSettings.addPackageToCleanLPw(
1516                                    new PackageCleanItem(userId, packageName, andCode));
1517                        }
1518                    }
1519                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1520                    startCleaningPackages();
1521                } break;
1522                case POST_INSTALL: {
1523                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1524
1525                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1526                    final boolean didRestore = (msg.arg2 != 0);
1527                    mRunningInstalls.delete(msg.arg1);
1528
1529                    if (data != null) {
1530                        InstallArgs args = data.args;
1531                        PackageInstalledInfo parentRes = data.res;
1532
1533                        final boolean grantPermissions = (args.installFlags
1534                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1535                        final boolean killApp = (args.installFlags
1536                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1537                        final String[] grantedPermissions = args.installGrantPermissions;
1538
1539                        // Handle the parent package
1540                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1541                                grantedPermissions, didRestore, args.installerPackageName,
1542                                args.observer);
1543
1544                        // Handle the child packages
1545                        final int childCount = (parentRes.addedChildPackages != null)
1546                                ? parentRes.addedChildPackages.size() : 0;
1547                        for (int i = 0; i < childCount; i++) {
1548                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1549                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1550                                    grantedPermissions, false, args.installerPackageName,
1551                                    args.observer);
1552                        }
1553
1554                        // Log tracing if needed
1555                        if (args.traceMethod != null) {
1556                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1557                                    args.traceCookie);
1558                        }
1559                    } else {
1560                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1561                    }
1562
1563                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1564                } break;
1565                case UPDATED_MEDIA_STATUS: {
1566                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1567                    boolean reportStatus = msg.arg1 == 1;
1568                    boolean doGc = msg.arg2 == 1;
1569                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1570                    if (doGc) {
1571                        // Force a gc to clear up stale containers.
1572                        Runtime.getRuntime().gc();
1573                    }
1574                    if (msg.obj != null) {
1575                        @SuppressWarnings("unchecked")
1576                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1577                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1578                        // Unload containers
1579                        unloadAllContainers(args);
1580                    }
1581                    if (reportStatus) {
1582                        try {
1583                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1584                                    "Invoking StorageManagerService call back");
1585                            PackageHelper.getStorageManager().finishMediaUpdate();
1586                        } catch (RemoteException e) {
1587                            Log.e(TAG, "StorageManagerService not running?");
1588                        }
1589                    }
1590                } break;
1591                case WRITE_SETTINGS: {
1592                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1593                    synchronized (mPackages) {
1594                        removeMessages(WRITE_SETTINGS);
1595                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1596                        mSettings.writeLPr();
1597                        mDirtyUsers.clear();
1598                    }
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1600                } break;
1601                case WRITE_PACKAGE_RESTRICTIONS: {
1602                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1603                    synchronized (mPackages) {
1604                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1605                        for (int userId : mDirtyUsers) {
1606                            mSettings.writePackageRestrictionsLPr(userId);
1607                        }
1608                        mDirtyUsers.clear();
1609                    }
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1611                } break;
1612                case WRITE_PACKAGE_LIST: {
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1614                    synchronized (mPackages) {
1615                        removeMessages(WRITE_PACKAGE_LIST);
1616                        mSettings.writePackageListLPr(msg.arg1);
1617                    }
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1619                } break;
1620                case CHECK_PENDING_VERIFICATION: {
1621                    final int verificationId = msg.arg1;
1622                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1623
1624                    if ((state != null) && !state.timeoutExtended()) {
1625                        final InstallArgs args = state.getInstallArgs();
1626                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1627
1628                        Slog.i(TAG, "Verification timed out for " + originUri);
1629                        mPendingVerification.remove(verificationId);
1630
1631                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1632
1633                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1634                            Slog.i(TAG, "Continuing with installation of " + originUri);
1635                            state.setVerifierResponse(Binder.getCallingUid(),
1636                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1637                            broadcastPackageVerified(verificationId, originUri,
1638                                    PackageManager.VERIFICATION_ALLOW,
1639                                    state.getInstallArgs().getUser());
1640                            try {
1641                                ret = args.copyApk(mContainerService, true);
1642                            } catch (RemoteException e) {
1643                                Slog.e(TAG, "Could not contact the ContainerService");
1644                            }
1645                        } else {
1646                            broadcastPackageVerified(verificationId, originUri,
1647                                    PackageManager.VERIFICATION_REJECT,
1648                                    state.getInstallArgs().getUser());
1649                        }
1650
1651                        Trace.asyncTraceEnd(
1652                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1653
1654                        processPendingInstall(args, ret);
1655                        mHandler.sendEmptyMessage(MCS_UNBIND);
1656                    }
1657                    break;
1658                }
1659                case PACKAGE_VERIFIED: {
1660                    final int verificationId = msg.arg1;
1661
1662                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1663                    if (state == null) {
1664                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1665                        break;
1666                    }
1667
1668                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1669
1670                    state.setVerifierResponse(response.callerUid, response.code);
1671
1672                    if (state.isVerificationComplete()) {
1673                        mPendingVerification.remove(verificationId);
1674
1675                        final InstallArgs args = state.getInstallArgs();
1676                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1677
1678                        int ret;
1679                        if (state.isInstallAllowed()) {
1680                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1681                            broadcastPackageVerified(verificationId, originUri,
1682                                    response.code, state.getInstallArgs().getUser());
1683                            try {
1684                                ret = args.copyApk(mContainerService, true);
1685                            } catch (RemoteException e) {
1686                                Slog.e(TAG, "Could not contact the ContainerService");
1687                            }
1688                        } else {
1689                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1690                        }
1691
1692                        Trace.asyncTraceEnd(
1693                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1694
1695                        processPendingInstall(args, ret);
1696                        mHandler.sendEmptyMessage(MCS_UNBIND);
1697                    }
1698
1699                    break;
1700                }
1701                case START_INTENT_FILTER_VERIFICATIONS: {
1702                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1703                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1704                            params.replacing, params.pkg);
1705                    break;
1706                }
1707                case INTENT_FILTER_VERIFIED: {
1708                    final int verificationId = msg.arg1;
1709
1710                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1711                            verificationId);
1712                    if (state == null) {
1713                        Slog.w(TAG, "Invalid IntentFilter verification token "
1714                                + verificationId + " received");
1715                        break;
1716                    }
1717
1718                    final int userId = state.getUserId();
1719
1720                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1721                            "Processing IntentFilter verification with token:"
1722                            + verificationId + " and userId:" + userId);
1723
1724                    final IntentFilterVerificationResponse response =
1725                            (IntentFilterVerificationResponse) msg.obj;
1726
1727                    state.setVerifierResponse(response.callerUid, response.code);
1728
1729                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1730                            "IntentFilter verification with token:" + verificationId
1731                            + " and userId:" + userId
1732                            + " is settings verifier response with response code:"
1733                            + response.code);
1734
1735                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1736                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1737                                + response.getFailedDomainsString());
1738                    }
1739
1740                    if (state.isVerificationComplete()) {
1741                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1742                    } else {
1743                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1744                                "IntentFilter verification with token:" + verificationId
1745                                + " was not said to be complete");
1746                    }
1747
1748                    break;
1749                }
1750                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1751                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1752                            mInstantAppResolverConnection,
1753                            (EphemeralRequest) msg.obj,
1754                            mInstantAppInstallerActivity,
1755                            mHandler);
1756                }
1757            }
1758        }
1759    }
1760
1761    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1762            boolean killApp, String[] grantedPermissions,
1763            boolean launchedForRestore, String installerPackage,
1764            IPackageInstallObserver2 installObserver) {
1765        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1766            // Send the removed broadcasts
1767            if (res.removedInfo != null) {
1768                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1769            }
1770
1771            // Now that we successfully installed the package, grant runtime
1772            // permissions if requested before broadcasting the install. Also
1773            // for legacy apps in permission review mode we clear the permission
1774            // review flag which is used to emulate runtime permissions for
1775            // legacy apps.
1776            if (grantPermissions) {
1777                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1778            }
1779
1780            final boolean update = res.removedInfo != null
1781                    && res.removedInfo.removedPackage != null;
1782
1783            // If this is the first time we have child packages for a disabled privileged
1784            // app that had no children, we grant requested runtime permissions to the new
1785            // children if the parent on the system image had them already granted.
1786            if (res.pkg.parentPackage != null) {
1787                synchronized (mPackages) {
1788                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1789                }
1790            }
1791
1792            synchronized (mPackages) {
1793                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1794            }
1795
1796            final String packageName = res.pkg.applicationInfo.packageName;
1797
1798            // Determine the set of users who are adding this package for
1799            // the first time vs. those who are seeing an update.
1800            int[] firstUsers = EMPTY_INT_ARRAY;
1801            int[] updateUsers = EMPTY_INT_ARRAY;
1802            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1803            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1804            for (int newUser : res.newUsers) {
1805                if (ps.getInstantApp(newUser)) {
1806                    continue;
1807                }
1808                if (allNewUsers) {
1809                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1810                    continue;
1811                }
1812                boolean isNew = true;
1813                for (int origUser : res.origUsers) {
1814                    if (origUser == newUser) {
1815                        isNew = false;
1816                        break;
1817                    }
1818                }
1819                if (isNew) {
1820                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1821                } else {
1822                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1823                }
1824            }
1825
1826            // Send installed broadcasts if the package is not a static shared lib.
1827            if (res.pkg.staticSharedLibName == null) {
1828                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1829
1830                // Send added for users that see the package for the first time
1831                // sendPackageAddedForNewUsers also deals with system apps
1832                int appId = UserHandle.getAppId(res.uid);
1833                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1834                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1835
1836                // Send added for users that don't see the package for the first time
1837                Bundle extras = new Bundle(1);
1838                extras.putInt(Intent.EXTRA_UID, res.uid);
1839                if (update) {
1840                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1841                }
1842                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1843                        extras, 0 /*flags*/, null /*targetPackage*/,
1844                        null /*finishedReceiver*/, updateUsers);
1845
1846                // Send replaced for users that don't see the package for the first time
1847                if (update) {
1848                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1849                            packageName, extras, 0 /*flags*/,
1850                            null /*targetPackage*/, null /*finishedReceiver*/,
1851                            updateUsers);
1852                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1853                            null /*package*/, null /*extras*/, 0 /*flags*/,
1854                            packageName /*targetPackage*/,
1855                            null /*finishedReceiver*/, updateUsers);
1856                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1857                    // First-install and we did a restore, so we're responsible for the
1858                    // first-launch broadcast.
1859                    if (DEBUG_BACKUP) {
1860                        Slog.i(TAG, "Post-restore of " + packageName
1861                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1862                    }
1863                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1864                }
1865
1866                // Send broadcast package appeared if forward locked/external for all users
1867                // treat asec-hosted packages like removable media on upgrade
1868                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1869                    if (DEBUG_INSTALL) {
1870                        Slog.i(TAG, "upgrading pkg " + res.pkg
1871                                + " is ASEC-hosted -> AVAILABLE");
1872                    }
1873                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1874                    ArrayList<String> pkgList = new ArrayList<>(1);
1875                    pkgList.add(packageName);
1876                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1877                }
1878            }
1879
1880            // Work that needs to happen on first install within each user
1881            if (firstUsers != null && firstUsers.length > 0) {
1882                synchronized (mPackages) {
1883                    for (int userId : firstUsers) {
1884                        // If this app is a browser and it's newly-installed for some
1885                        // users, clear any default-browser state in those users. The
1886                        // app's nature doesn't depend on the user, so we can just check
1887                        // its browser nature in any user and generalize.
1888                        if (packageIsBrowser(packageName, userId)) {
1889                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1890                        }
1891
1892                        // We may also need to apply pending (restored) runtime
1893                        // permission grants within these users.
1894                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1895                    }
1896                }
1897            }
1898
1899            // Log current value of "unknown sources" setting
1900            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1901                    getUnknownSourcesSettings());
1902
1903            // Force a gc to clear up things
1904            Runtime.getRuntime().gc();
1905
1906            // Remove the replaced package's older resources safely now
1907            // We delete after a gc for applications  on sdcard.
1908            if (res.removedInfo != null && res.removedInfo.args != null) {
1909                synchronized (mInstallLock) {
1910                    res.removedInfo.args.doPostDeleteLI(true);
1911                }
1912            }
1913
1914            // Notify DexManager that the package was installed for new users.
1915            // The updated users should already be indexed and the package code paths
1916            // should not change.
1917            // Don't notify the manager for ephemeral apps as they are not expected to
1918            // survive long enough to benefit of background optimizations.
1919            for (int userId : firstUsers) {
1920                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1921                mDexManager.notifyPackageInstalled(info, userId);
1922            }
1923        }
1924
1925        // If someone is watching installs - notify them
1926        if (installObserver != null) {
1927            try {
1928                Bundle extras = extrasForInstallResult(res);
1929                installObserver.onPackageInstalled(res.name, res.returnCode,
1930                        res.returnMsg, extras);
1931            } catch (RemoteException e) {
1932                Slog.i(TAG, "Observer no longer exists.");
1933            }
1934        }
1935    }
1936
1937    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1938            PackageParser.Package pkg) {
1939        if (pkg.parentPackage == null) {
1940            return;
1941        }
1942        if (pkg.requestedPermissions == null) {
1943            return;
1944        }
1945        final PackageSetting disabledSysParentPs = mSettings
1946                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1947        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1948                || !disabledSysParentPs.isPrivileged()
1949                || (disabledSysParentPs.childPackageNames != null
1950                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1951            return;
1952        }
1953        final int[] allUserIds = sUserManager.getUserIds();
1954        final int permCount = pkg.requestedPermissions.size();
1955        for (int i = 0; i < permCount; i++) {
1956            String permission = pkg.requestedPermissions.get(i);
1957            BasePermission bp = mSettings.mPermissions.get(permission);
1958            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1959                continue;
1960            }
1961            for (int userId : allUserIds) {
1962                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1963                        permission, userId)) {
1964                    grantRuntimePermission(pkg.packageName, permission, userId);
1965                }
1966            }
1967        }
1968    }
1969
1970    private StorageEventListener mStorageListener = new StorageEventListener() {
1971        @Override
1972        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1973            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1974                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1975                    final String volumeUuid = vol.getFsUuid();
1976
1977                    // Clean up any users or apps that were removed or recreated
1978                    // while this volume was missing
1979                    sUserManager.reconcileUsers(volumeUuid);
1980                    reconcileApps(volumeUuid);
1981
1982                    // Clean up any install sessions that expired or were
1983                    // cancelled while this volume was missing
1984                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1985
1986                    loadPrivatePackages(vol);
1987
1988                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1989                    unloadPrivatePackages(vol);
1990                }
1991            }
1992
1993            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1994                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1995                    updateExternalMediaStatus(true, false);
1996                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1997                    updateExternalMediaStatus(false, false);
1998                }
1999            }
2000        }
2001
2002        @Override
2003        public void onVolumeForgotten(String fsUuid) {
2004            if (TextUtils.isEmpty(fsUuid)) {
2005                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2006                return;
2007            }
2008
2009            // Remove any apps installed on the forgotten volume
2010            synchronized (mPackages) {
2011                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2012                for (PackageSetting ps : packages) {
2013                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2014                    deletePackageVersioned(new VersionedPackage(ps.name,
2015                            PackageManager.VERSION_CODE_HIGHEST),
2016                            new LegacyPackageDeleteObserver(null).getBinder(),
2017                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2018                    // Try very hard to release any references to this package
2019                    // so we don't risk the system server being killed due to
2020                    // open FDs
2021                    AttributeCache.instance().removePackage(ps.name);
2022                }
2023
2024                mSettings.onVolumeForgotten(fsUuid);
2025                mSettings.writeLPr();
2026            }
2027        }
2028    };
2029
2030    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2031            String[] grantedPermissions) {
2032        for (int userId : userIds) {
2033            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2034        }
2035    }
2036
2037    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2038            String[] grantedPermissions) {
2039        SettingBase sb = (SettingBase) pkg.mExtras;
2040        if (sb == null) {
2041            return;
2042        }
2043
2044        PermissionsState permissionsState = sb.getPermissionsState();
2045
2046        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2047                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2048
2049        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2050                >= Build.VERSION_CODES.M;
2051
2052        for (String permission : pkg.requestedPermissions) {
2053            final BasePermission bp;
2054            synchronized (mPackages) {
2055                bp = mSettings.mPermissions.get(permission);
2056            }
2057            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2058                    && (grantedPermissions == null
2059                           || ArrayUtils.contains(grantedPermissions, permission))) {
2060                final int flags = permissionsState.getPermissionFlags(permission, userId);
2061                if (supportsRuntimePermissions) {
2062                    // Installer cannot change immutable permissions.
2063                    if ((flags & immutableFlags) == 0) {
2064                        grantRuntimePermission(pkg.packageName, permission, userId);
2065                    }
2066                } else if (mPermissionReviewRequired) {
2067                    // In permission review mode we clear the review flag when we
2068                    // are asked to install the app with all permissions granted.
2069                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2070                        updatePermissionFlags(permission, pkg.packageName,
2071                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2072                    }
2073                }
2074            }
2075        }
2076    }
2077
2078    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2079        Bundle extras = null;
2080        switch (res.returnCode) {
2081            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2082                extras = new Bundle();
2083                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2084                        res.origPermission);
2085                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2086                        res.origPackage);
2087                break;
2088            }
2089            case PackageManager.INSTALL_SUCCEEDED: {
2090                extras = new Bundle();
2091                extras.putBoolean(Intent.EXTRA_REPLACING,
2092                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2093                break;
2094            }
2095        }
2096        return extras;
2097    }
2098
2099    void scheduleWriteSettingsLocked() {
2100        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2101            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2102        }
2103    }
2104
2105    void scheduleWritePackageListLocked(int userId) {
2106        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2107            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2108            msg.arg1 = userId;
2109            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2110        }
2111    }
2112
2113    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2114        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2115        scheduleWritePackageRestrictionsLocked(userId);
2116    }
2117
2118    void scheduleWritePackageRestrictionsLocked(int userId) {
2119        final int[] userIds = (userId == UserHandle.USER_ALL)
2120                ? sUserManager.getUserIds() : new int[]{userId};
2121        for (int nextUserId : userIds) {
2122            if (!sUserManager.exists(nextUserId)) return;
2123            mDirtyUsers.add(nextUserId);
2124            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2125                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2126            }
2127        }
2128    }
2129
2130    public static PackageManagerService main(Context context, Installer installer,
2131            boolean factoryTest, boolean onlyCore) {
2132        // Self-check for initial settings.
2133        PackageManagerServiceCompilerMapping.checkProperties();
2134
2135        PackageManagerService m = new PackageManagerService(context, installer,
2136                factoryTest, onlyCore);
2137        m.enableSystemUserPackages();
2138        ServiceManager.addService("package", m);
2139        return m;
2140    }
2141
2142    private void enableSystemUserPackages() {
2143        if (!UserManager.isSplitSystemUser()) {
2144            return;
2145        }
2146        // For system user, enable apps based on the following conditions:
2147        // - app is whitelisted or belong to one of these groups:
2148        //   -- system app which has no launcher icons
2149        //   -- system app which has INTERACT_ACROSS_USERS permission
2150        //   -- system IME app
2151        // - app is not in the blacklist
2152        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2153        Set<String> enableApps = new ArraySet<>();
2154        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2155                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2156                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2157        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2158        enableApps.addAll(wlApps);
2159        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2160                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2161        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2162        enableApps.removeAll(blApps);
2163        Log.i(TAG, "Applications installed for system user: " + enableApps);
2164        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2165                UserHandle.SYSTEM);
2166        final int allAppsSize = allAps.size();
2167        synchronized (mPackages) {
2168            for (int i = 0; i < allAppsSize; i++) {
2169                String pName = allAps.get(i);
2170                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2171                // Should not happen, but we shouldn't be failing if it does
2172                if (pkgSetting == null) {
2173                    continue;
2174                }
2175                boolean install = enableApps.contains(pName);
2176                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2177                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2178                            + " for system user");
2179                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2180                }
2181            }
2182            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2183        }
2184    }
2185
2186    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2187        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2188                Context.DISPLAY_SERVICE);
2189        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2190    }
2191
2192    /**
2193     * Requests that files preopted on a secondary system partition be copied to the data partition
2194     * if possible.  Note that the actual copying of the files is accomplished by init for security
2195     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2196     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2197     */
2198    private static void requestCopyPreoptedFiles() {
2199        final int WAIT_TIME_MS = 100;
2200        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2201        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2202            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2203            // We will wait for up to 100 seconds.
2204            final long timeStart = SystemClock.uptimeMillis();
2205            final long timeEnd = timeStart + 100 * 1000;
2206            long timeNow = timeStart;
2207            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2208                try {
2209                    Thread.sleep(WAIT_TIME_MS);
2210                } catch (InterruptedException e) {
2211                    // Do nothing
2212                }
2213                timeNow = SystemClock.uptimeMillis();
2214                if (timeNow > timeEnd) {
2215                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2216                    Slog.wtf(TAG, "cppreopt did not finish!");
2217                    break;
2218                }
2219            }
2220
2221            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2222        }
2223    }
2224
2225    public PackageManagerService(Context context, Installer installer,
2226            boolean factoryTest, boolean onlyCore) {
2227        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2228        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2229                SystemClock.uptimeMillis());
2230
2231        if (mSdkVersion <= 0) {
2232            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2233        }
2234
2235        mContext = context;
2236
2237        mPermissionReviewRequired = context.getResources().getBoolean(
2238                R.bool.config_permissionReviewRequired);
2239
2240        mFactoryTest = factoryTest;
2241        mOnlyCore = onlyCore;
2242        mMetrics = new DisplayMetrics();
2243        mSettings = new Settings(mPackages);
2244        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2245                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2247                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2248        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2249                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2250        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2251                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2252        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2253                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2254        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2255                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2256
2257        String separateProcesses = SystemProperties.get("debug.separate_processes");
2258        if (separateProcesses != null && separateProcesses.length() > 0) {
2259            if ("*".equals(separateProcesses)) {
2260                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2261                mSeparateProcesses = null;
2262                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2263            } else {
2264                mDefParseFlags = 0;
2265                mSeparateProcesses = separateProcesses.split(",");
2266                Slog.w(TAG, "Running with debug.separate_processes: "
2267                        + separateProcesses);
2268            }
2269        } else {
2270            mDefParseFlags = 0;
2271            mSeparateProcesses = null;
2272        }
2273
2274        mInstaller = installer;
2275        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2276                "*dexopt*");
2277        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2278        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2279
2280        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2281                FgThread.get().getLooper());
2282
2283        getDefaultDisplayMetrics(context, mMetrics);
2284
2285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2286        SystemConfig systemConfig = SystemConfig.getInstance();
2287        mGlobalGids = systemConfig.getGlobalGids();
2288        mSystemPermissions = systemConfig.getSystemPermissions();
2289        mAvailableFeatures = systemConfig.getAvailableFeatures();
2290        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2291
2292        mProtectedPackages = new ProtectedPackages(mContext);
2293
2294        synchronized (mInstallLock) {
2295        // writer
2296        synchronized (mPackages) {
2297            mHandlerThread = new ServiceThread(TAG,
2298                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2299            mHandlerThread.start();
2300            mHandler = new PackageHandler(mHandlerThread.getLooper());
2301            mProcessLoggingHandler = new ProcessLoggingHandler();
2302            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2303
2304            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2305            mInstantAppRegistry = new InstantAppRegistry(this);
2306
2307            File dataDir = Environment.getDataDirectory();
2308            mAppInstallDir = new File(dataDir, "app");
2309            mAppLib32InstallDir = new File(dataDir, "app-lib");
2310            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2311            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2312            sUserManager = new UserManagerService(context, this,
2313                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2314
2315            // Propagate permission configuration in to package manager.
2316            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2317                    = systemConfig.getPermissions();
2318            for (int i=0; i<permConfig.size(); i++) {
2319                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2320                BasePermission bp = mSettings.mPermissions.get(perm.name);
2321                if (bp == null) {
2322                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2323                    mSettings.mPermissions.put(perm.name, bp);
2324                }
2325                if (perm.gids != null) {
2326                    bp.setGids(perm.gids, perm.perUser);
2327                }
2328            }
2329
2330            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2331            final int builtInLibCount = libConfig.size();
2332            for (int i = 0; i < builtInLibCount; i++) {
2333                String name = libConfig.keyAt(i);
2334                String path = libConfig.valueAt(i);
2335                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2336                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2337            }
2338
2339            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2340
2341            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2342            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2343            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2344
2345            // Clean up orphaned packages for which the code path doesn't exist
2346            // and they are an update to a system app - caused by bug/32321269
2347            final int packageSettingCount = mSettings.mPackages.size();
2348            for (int i = packageSettingCount - 1; i >= 0; i--) {
2349                PackageSetting ps = mSettings.mPackages.valueAt(i);
2350                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2351                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2352                    mSettings.mPackages.removeAt(i);
2353                    mSettings.enableSystemPackageLPw(ps.name);
2354                }
2355            }
2356
2357            if (mFirstBoot) {
2358                requestCopyPreoptedFiles();
2359            }
2360
2361            String customResolverActivity = Resources.getSystem().getString(
2362                    R.string.config_customResolverActivity);
2363            if (TextUtils.isEmpty(customResolverActivity)) {
2364                customResolverActivity = null;
2365            } else {
2366                mCustomResolverComponentName = ComponentName.unflattenFromString(
2367                        customResolverActivity);
2368            }
2369
2370            long startTime = SystemClock.uptimeMillis();
2371
2372            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2373                    startTime);
2374
2375            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2376            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2377
2378            if (bootClassPath == null) {
2379                Slog.w(TAG, "No BOOTCLASSPATH found!");
2380            }
2381
2382            if (systemServerClassPath == null) {
2383                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2384            }
2385
2386            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2387            final String[] dexCodeInstructionSets =
2388                    getDexCodeInstructionSets(
2389                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2390
2391            /**
2392             * Ensure all external libraries have had dexopt run on them.
2393             */
2394            if (mSharedLibraries.size() > 0) {
2395                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2396                // NOTE: For now, we're compiling these system "shared libraries"
2397                // (and framework jars) into all available architectures. It's possible
2398                // to compile them only when we come across an app that uses them (there's
2399                // already logic for that in scanPackageLI) but that adds some complexity.
2400                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2401                    final int libCount = mSharedLibraries.size();
2402                    for (int i = 0; i < libCount; i++) {
2403                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2404                        final int versionCount = versionedLib.size();
2405                        for (int j = 0; j < versionCount; j++) {
2406                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2407                            final String libPath = libEntry.path != null
2408                                    ? libEntry.path : libEntry.apk;
2409                            if (libPath == null) {
2410                                continue;
2411                            }
2412                            try {
2413                                // Shared libraries do not have profiles so we perform a full
2414                                // AOT compilation (if needed).
2415                                int dexoptNeeded = DexFile.getDexOptNeeded(
2416                                        libPath, dexCodeInstructionSet,
2417                                        getCompilerFilterForReason(REASON_SHARED_APK),
2418                                        false /* newProfile */);
2419                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2420                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2421                                            dexCodeInstructionSet, dexoptNeeded, null,
2422                                            DEXOPT_PUBLIC,
2423                                            getCompilerFilterForReason(REASON_SHARED_APK),
2424                                            StorageManager.UUID_PRIVATE_INTERNAL,
2425                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2426                                }
2427                            } catch (FileNotFoundException e) {
2428                                Slog.w(TAG, "Library not found: " + libPath);
2429                            } catch (IOException | InstallerException e) {
2430                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2431                                        + e.getMessage());
2432                            }
2433                        }
2434                    }
2435                }
2436                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2437            }
2438
2439            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2440
2441            final VersionInfo ver = mSettings.getInternalVersion();
2442            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2443
2444            // when upgrading from pre-M, promote system app permissions from install to runtime
2445            mPromoteSystemApps =
2446                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2447
2448            // When upgrading from pre-N, we need to handle package extraction like first boot,
2449            // as there is no profiling data available.
2450            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2451
2452            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2453
2454            // save off the names of pre-existing system packages prior to scanning; we don't
2455            // want to automatically grant runtime permissions for new system apps
2456            if (mPromoteSystemApps) {
2457                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2458                while (pkgSettingIter.hasNext()) {
2459                    PackageSetting ps = pkgSettingIter.next();
2460                    if (isSystemApp(ps)) {
2461                        mExistingSystemPackages.add(ps.name);
2462                    }
2463                }
2464            }
2465
2466            mCacheDir = preparePackageParserCache(mIsUpgrade);
2467
2468            // Set flag to monitor and not change apk file paths when
2469            // scanning install directories.
2470            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2471
2472            if (mIsUpgrade || mFirstBoot) {
2473                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2474            }
2475
2476            // Collect vendor overlay packages. (Do this before scanning any apps.)
2477            // For security and version matching reason, only consider
2478            // overlay packages if they reside in the right directory.
2479            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2480            if (overlayThemeDir.isEmpty()) {
2481                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2482            }
2483            if (!overlayThemeDir.isEmpty()) {
2484                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2485                        | PackageParser.PARSE_IS_SYSTEM
2486                        | PackageParser.PARSE_IS_SYSTEM_DIR
2487                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2488            }
2489            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2490                    | PackageParser.PARSE_IS_SYSTEM
2491                    | PackageParser.PARSE_IS_SYSTEM_DIR
2492                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2493
2494            // Find base frameworks (resource packages without code).
2495            scanDirTracedLI(frameworkDir, mDefParseFlags
2496                    | PackageParser.PARSE_IS_SYSTEM
2497                    | PackageParser.PARSE_IS_SYSTEM_DIR
2498                    | PackageParser.PARSE_IS_PRIVILEGED,
2499                    scanFlags | SCAN_NO_DEX, 0);
2500
2501            // Collected privileged system packages.
2502            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2503            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2504                    | PackageParser.PARSE_IS_SYSTEM
2505                    | PackageParser.PARSE_IS_SYSTEM_DIR
2506                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2507
2508            // Collect ordinary system packages.
2509            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2510            scanDirTracedLI(systemAppDir, mDefParseFlags
2511                    | PackageParser.PARSE_IS_SYSTEM
2512                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2513
2514            // Collect all vendor packages.
2515            File vendorAppDir = new File("/vendor/app");
2516            try {
2517                vendorAppDir = vendorAppDir.getCanonicalFile();
2518            } catch (IOException e) {
2519                // failed to look up canonical path, continue with original one
2520            }
2521            scanDirTracedLI(vendorAppDir, mDefParseFlags
2522                    | PackageParser.PARSE_IS_SYSTEM
2523                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2524
2525            // Collect all OEM packages.
2526            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2527            scanDirTracedLI(oemAppDir, mDefParseFlags
2528                    | PackageParser.PARSE_IS_SYSTEM
2529                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2530
2531            // Prune any system packages that no longer exist.
2532            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2533            if (!mOnlyCore) {
2534                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2535                while (psit.hasNext()) {
2536                    PackageSetting ps = psit.next();
2537
2538                    /*
2539                     * If this is not a system app, it can't be a
2540                     * disable system app.
2541                     */
2542                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2543                        continue;
2544                    }
2545
2546                    /*
2547                     * If the package is scanned, it's not erased.
2548                     */
2549                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2550                    if (scannedPkg != null) {
2551                        /*
2552                         * If the system app is both scanned and in the
2553                         * disabled packages list, then it must have been
2554                         * added via OTA. Remove it from the currently
2555                         * scanned package so the previously user-installed
2556                         * application can be scanned.
2557                         */
2558                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2559                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2560                                    + ps.name + "; removing system app.  Last known codePath="
2561                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2562                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2563                                    + scannedPkg.mVersionCode);
2564                            removePackageLI(scannedPkg, true);
2565                            mExpectingBetter.put(ps.name, ps.codePath);
2566                        }
2567
2568                        continue;
2569                    }
2570
2571                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2572                        psit.remove();
2573                        logCriticalInfo(Log.WARN, "System package " + ps.name
2574                                + " no longer exists; it's data will be wiped");
2575                        // Actual deletion of code and data will be handled by later
2576                        // reconciliation step
2577                    } else {
2578                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2579                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2580                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2581                        }
2582                    }
2583                }
2584            }
2585
2586            //look for any incomplete package installations
2587            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2588            for (int i = 0; i < deletePkgsList.size(); i++) {
2589                // Actual deletion of code and data will be handled by later
2590                // reconciliation step
2591                final String packageName = deletePkgsList.get(i).name;
2592                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2593                synchronized (mPackages) {
2594                    mSettings.removePackageLPw(packageName);
2595                }
2596            }
2597
2598            //delete tmp files
2599            deleteTempPackageFiles();
2600
2601            // Remove any shared userIDs that have no associated packages
2602            mSettings.pruneSharedUsersLPw();
2603
2604            if (!mOnlyCore) {
2605                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2606                        SystemClock.uptimeMillis());
2607                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2608
2609                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2610                        | PackageParser.PARSE_FORWARD_LOCK,
2611                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2612
2613                /**
2614                 * Remove disable package settings for any updated system
2615                 * apps that were removed via an OTA. If they're not a
2616                 * previously-updated app, remove them completely.
2617                 * Otherwise, just revoke their system-level permissions.
2618                 */
2619                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2620                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2621                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2622
2623                    String msg;
2624                    if (deletedPkg == null) {
2625                        msg = "Updated system package " + deletedAppName
2626                                + " no longer exists; it's data will be wiped";
2627                        // Actual deletion of code and data will be handled by later
2628                        // reconciliation step
2629                    } else {
2630                        msg = "Updated system app + " + deletedAppName
2631                                + " no longer present; removing system privileges for "
2632                                + deletedAppName;
2633
2634                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2635
2636                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2637                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2638                    }
2639                    logCriticalInfo(Log.WARN, msg);
2640                }
2641
2642                /**
2643                 * Make sure all system apps that we expected to appear on
2644                 * the userdata partition actually showed up. If they never
2645                 * appeared, crawl back and revive the system version.
2646                 */
2647                for (int i = 0; i < mExpectingBetter.size(); i++) {
2648                    final String packageName = mExpectingBetter.keyAt(i);
2649                    if (!mPackages.containsKey(packageName)) {
2650                        final File scanFile = mExpectingBetter.valueAt(i);
2651
2652                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2653                                + " but never showed up; reverting to system");
2654
2655                        int reparseFlags = mDefParseFlags;
2656                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2657                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2658                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2659                                    | PackageParser.PARSE_IS_PRIVILEGED;
2660                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2661                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2662                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2663                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2664                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2665                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2666                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2667                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2668                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2669                        } else {
2670                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2671                            continue;
2672                        }
2673
2674                        mSettings.enableSystemPackageLPw(packageName);
2675
2676                        try {
2677                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2678                        } catch (PackageManagerException e) {
2679                            Slog.e(TAG, "Failed to parse original system package: "
2680                                    + e.getMessage());
2681                        }
2682                    }
2683                }
2684            }
2685            mExpectingBetter.clear();
2686
2687            // Resolve the storage manager.
2688            mStorageManagerPackage = getStorageManagerPackageName();
2689
2690            // Resolve protected action filters. Only the setup wizard is allowed to
2691            // have a high priority filter for these actions.
2692            mSetupWizardPackage = getSetupWizardPackageName();
2693            if (mProtectedFilters.size() > 0) {
2694                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2695                    Slog.i(TAG, "No setup wizard;"
2696                        + " All protected intents capped to priority 0");
2697                }
2698                for (ActivityIntentInfo filter : mProtectedFilters) {
2699                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2700                        if (DEBUG_FILTERS) {
2701                            Slog.i(TAG, "Found setup wizard;"
2702                                + " allow priority " + filter.getPriority() + ";"
2703                                + " package: " + filter.activity.info.packageName
2704                                + " activity: " + filter.activity.className
2705                                + " priority: " + filter.getPriority());
2706                        }
2707                        // skip setup wizard; allow it to keep the high priority filter
2708                        continue;
2709                    }
2710                    Slog.w(TAG, "Protected action; cap priority to 0;"
2711                            + " package: " + filter.activity.info.packageName
2712                            + " activity: " + filter.activity.className
2713                            + " origPrio: " + filter.getPriority());
2714                    filter.setPriority(0);
2715                }
2716            }
2717            mDeferProtectedFilters = false;
2718            mProtectedFilters.clear();
2719
2720            // Now that we know all of the shared libraries, update all clients to have
2721            // the correct library paths.
2722            updateAllSharedLibrariesLPw(null);
2723
2724            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2725                // NOTE: We ignore potential failures here during a system scan (like
2726                // the rest of the commands above) because there's precious little we
2727                // can do about it. A settings error is reported, though.
2728                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2729            }
2730
2731            // Now that we know all the packages we are keeping,
2732            // read and update their last usage times.
2733            mPackageUsage.read(mPackages);
2734            mCompilerStats.read();
2735
2736            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2737                    SystemClock.uptimeMillis());
2738            Slog.i(TAG, "Time to scan packages: "
2739                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2740                    + " seconds");
2741
2742            // If the platform SDK has changed since the last time we booted,
2743            // we need to re-grant app permission to catch any new ones that
2744            // appear.  This is really a hack, and means that apps can in some
2745            // cases get permissions that the user didn't initially explicitly
2746            // allow...  it would be nice to have some better way to handle
2747            // this situation.
2748            int updateFlags = UPDATE_PERMISSIONS_ALL;
2749            if (ver.sdkVersion != mSdkVersion) {
2750                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2751                        + mSdkVersion + "; regranting permissions for internal storage");
2752                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2753            }
2754            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2755            ver.sdkVersion = mSdkVersion;
2756
2757            // If this is the first boot or an update from pre-M, and it is a normal
2758            // boot, then we need to initialize the default preferred apps across
2759            // all defined users.
2760            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2761                for (UserInfo user : sUserManager.getUsers(true)) {
2762                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2763                    applyFactoryDefaultBrowserLPw(user.id);
2764                    primeDomainVerificationsLPw(user.id);
2765                }
2766            }
2767
2768            // Prepare storage for system user really early during boot,
2769            // since core system apps like SettingsProvider and SystemUI
2770            // can't wait for user to start
2771            final int storageFlags;
2772            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2773                storageFlags = StorageManager.FLAG_STORAGE_DE;
2774            } else {
2775                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2776            }
2777            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2778                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2779                    true /* onlyCoreApps */);
2780            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2781                if (deferPackages == null || deferPackages.isEmpty()) {
2782                    return;
2783                }
2784                int count = 0;
2785                for (String pkgName : deferPackages) {
2786                    PackageParser.Package pkg = null;
2787                    synchronized (mPackages) {
2788                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2789                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2790                            pkg = ps.pkg;
2791                        }
2792                    }
2793                    if (pkg != null) {
2794                        synchronized (mInstallLock) {
2795                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2796                                    true /* maybeMigrateAppData */);
2797                        }
2798                        count++;
2799                    }
2800                }
2801                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2802            }, "prepareAppData");
2803
2804            // If this is first boot after an OTA, and a normal boot, then
2805            // we need to clear code cache directories.
2806            // Note that we do *not* clear the application profiles. These remain valid
2807            // across OTAs and are used to drive profile verification (post OTA) and
2808            // profile compilation (without waiting to collect a fresh set of profiles).
2809            if (mIsUpgrade && !onlyCore) {
2810                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2811                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2812                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2813                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2814                        // No apps are running this early, so no need to freeze
2815                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2816                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2817                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2818                    }
2819                }
2820                ver.fingerprint = Build.FINGERPRINT;
2821            }
2822
2823            checkDefaultBrowser();
2824
2825            // clear only after permissions and other defaults have been updated
2826            mExistingSystemPackages.clear();
2827            mPromoteSystemApps = false;
2828
2829            // All the changes are done during package scanning.
2830            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2831
2832            // can downgrade to reader
2833            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2834            mSettings.writeLPr();
2835            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2836
2837            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2838            // early on (before the package manager declares itself as early) because other
2839            // components in the system server might ask for package contexts for these apps.
2840            //
2841            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2842            // (i.e, that the data partition is unavailable).
2843            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2844                long start = System.nanoTime();
2845                List<PackageParser.Package> coreApps = new ArrayList<>();
2846                for (PackageParser.Package pkg : mPackages.values()) {
2847                    if (pkg.coreApp) {
2848                        coreApps.add(pkg);
2849                    }
2850                }
2851
2852                int[] stats = performDexOptUpgrade(coreApps, false,
2853                        getCompilerFilterForReason(REASON_CORE_APP));
2854
2855                final int elapsedTimeSeconds =
2856                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2857                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2858
2859                if (DEBUG_DEXOPT) {
2860                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2861                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2862                }
2863
2864
2865                // TODO: Should we log these stats to tron too ?
2866                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2867                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2868                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2869                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2870            }
2871
2872            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2873                    SystemClock.uptimeMillis());
2874
2875            if (!mOnlyCore) {
2876                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2877                mRequiredInstallerPackage = getRequiredInstallerLPr();
2878                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2879                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2880                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2881                        mIntentFilterVerifierComponent);
2882                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2883                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2884                        SharedLibraryInfo.VERSION_UNDEFINED);
2885                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2886                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2887                        SharedLibraryInfo.VERSION_UNDEFINED);
2888            } else {
2889                mRequiredVerifierPackage = null;
2890                mRequiredInstallerPackage = null;
2891                mRequiredUninstallerPackage = null;
2892                mIntentFilterVerifierComponent = null;
2893                mIntentFilterVerifier = null;
2894                mServicesSystemSharedLibraryPackageName = null;
2895                mSharedSystemSharedLibraryPackageName = null;
2896            }
2897
2898            mInstallerService = new PackageInstallerService(context, this);
2899
2900            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2901            if (ephemeralResolverComponent != null) {
2902                if (DEBUG_EPHEMERAL) {
2903                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2904                }
2905                mInstantAppResolverConnection =
2906                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2907            } else {
2908                mInstantAppResolverConnection = null;
2909            }
2910            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2911            if (mInstantAppInstallerComponent != null) {
2912                if (DEBUG_EPHEMERAL) {
2913                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2914                }
2915                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2916            }
2917
2918            // Read and update the usage of dex files.
2919            // Do this at the end of PM init so that all the packages have their
2920            // data directory reconciled.
2921            // At this point we know the code paths of the packages, so we can validate
2922            // the disk file and build the internal cache.
2923            // The usage file is expected to be small so loading and verifying it
2924            // should take a fairly small time compare to the other activities (e.g. package
2925            // scanning).
2926            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2927            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2928            for (int userId : currentUserIds) {
2929                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2930            }
2931            mDexManager.load(userPackages);
2932        } // synchronized (mPackages)
2933        } // synchronized (mInstallLock)
2934
2935        // Now after opening every single application zip, make sure they
2936        // are all flushed.  Not really needed, but keeps things nice and
2937        // tidy.
2938        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2939        Runtime.getRuntime().gc();
2940        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2941
2942        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2943        FallbackCategoryProvider.loadFallbacks();
2944        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945
2946        // The initial scanning above does many calls into installd while
2947        // holding the mPackages lock, but we're mostly interested in yelling
2948        // once we have a booted system.
2949        mInstaller.setWarnIfHeld(mPackages);
2950
2951        // Expose private service for system components to use.
2952        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2953        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2954    }
2955
2956    private static File preparePackageParserCache(boolean isUpgrade) {
2957        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2958            return null;
2959        }
2960
2961        // Disable package parsing on eng builds to allow for faster incremental development.
2962        if ("eng".equals(Build.TYPE)) {
2963            return null;
2964        }
2965
2966        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2967            Slog.i(TAG, "Disabling package parser cache due to system property.");
2968            return null;
2969        }
2970
2971        // The base directory for the package parser cache lives under /data/system/.
2972        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2973                "package_cache");
2974        if (cacheBaseDir == null) {
2975            return null;
2976        }
2977
2978        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2979        // This also serves to "GC" unused entries when the package cache version changes (which
2980        // can only happen during upgrades).
2981        if (isUpgrade) {
2982            FileUtils.deleteContents(cacheBaseDir);
2983        }
2984
2985
2986        // Return the versioned package cache directory. This is something like
2987        // "/data/system/package_cache/1"
2988        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2989
2990        // The following is a workaround to aid development on non-numbered userdebug
2991        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2992        // the system partition is newer.
2993        //
2994        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2995        // that starts with "eng." to signify that this is an engineering build and not
2996        // destined for release.
2997        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2998            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2999
3000            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3001            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3002            // in general and should not be used for production changes. In this specific case,
3003            // we know that they will work.
3004            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3005            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3006                FileUtils.deleteContents(cacheBaseDir);
3007                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3008            }
3009        }
3010
3011        return cacheDir;
3012    }
3013
3014    @Override
3015    public boolean isFirstBoot() {
3016        return mFirstBoot;
3017    }
3018
3019    @Override
3020    public boolean isOnlyCoreApps() {
3021        return mOnlyCore;
3022    }
3023
3024    @Override
3025    public boolean isUpgrade() {
3026        return mIsUpgrade;
3027    }
3028
3029    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3030        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3031
3032        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3033                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3034                UserHandle.USER_SYSTEM);
3035        if (matches.size() == 1) {
3036            return matches.get(0).getComponentInfo().packageName;
3037        } else if (matches.size() == 0) {
3038            Log.e(TAG, "There should probably be a verifier, but, none were found");
3039            return null;
3040        }
3041        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3042    }
3043
3044    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3045        synchronized (mPackages) {
3046            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3047            if (libraryEntry == null) {
3048                throw new IllegalStateException("Missing required shared library:" + name);
3049            }
3050            return libraryEntry.apk;
3051        }
3052    }
3053
3054    private @NonNull String getRequiredInstallerLPr() {
3055        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3056        intent.addCategory(Intent.CATEGORY_DEFAULT);
3057        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3058
3059        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3060                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3061                UserHandle.USER_SYSTEM);
3062        if (matches.size() == 1) {
3063            ResolveInfo resolveInfo = matches.get(0);
3064            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3065                throw new RuntimeException("The installer must be a privileged app");
3066            }
3067            return matches.get(0).getComponentInfo().packageName;
3068        } else {
3069            throw new RuntimeException("There must be exactly one installer; found " + matches);
3070        }
3071    }
3072
3073    private @NonNull String getRequiredUninstallerLPr() {
3074        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3075        intent.addCategory(Intent.CATEGORY_DEFAULT);
3076        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3077
3078        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3079                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3080                UserHandle.USER_SYSTEM);
3081        if (resolveInfo == null ||
3082                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3083            throw new RuntimeException("There must be exactly one uninstaller; found "
3084                    + resolveInfo);
3085        }
3086        return resolveInfo.getComponentInfo().packageName;
3087    }
3088
3089    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3090        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3091
3092        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3093                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3094                UserHandle.USER_SYSTEM);
3095        ResolveInfo best = null;
3096        final int N = matches.size();
3097        for (int i = 0; i < N; i++) {
3098            final ResolveInfo cur = matches.get(i);
3099            final String packageName = cur.getComponentInfo().packageName;
3100            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3101                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3102                continue;
3103            }
3104
3105            if (best == null || cur.priority > best.priority) {
3106                best = cur;
3107            }
3108        }
3109
3110        if (best != null) {
3111            return best.getComponentInfo().getComponentName();
3112        } else {
3113            throw new RuntimeException("There must be at least one intent filter verifier");
3114        }
3115    }
3116
3117    private @Nullable ComponentName getEphemeralResolverLPr() {
3118        final String[] packageArray =
3119                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3120        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3121            if (DEBUG_EPHEMERAL) {
3122                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3123            }
3124            return null;
3125        }
3126
3127        final int resolveFlags =
3128                MATCH_DIRECT_BOOT_AWARE
3129                | MATCH_DIRECT_BOOT_UNAWARE
3130                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3131        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3132        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3133                resolveFlags, UserHandle.USER_SYSTEM);
3134
3135        final int N = resolvers.size();
3136        if (N == 0) {
3137            if (DEBUG_EPHEMERAL) {
3138                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3139            }
3140            return null;
3141        }
3142
3143        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3144        for (int i = 0; i < N; i++) {
3145            final ResolveInfo info = resolvers.get(i);
3146
3147            if (info.serviceInfo == null) {
3148                continue;
3149            }
3150
3151            final String packageName = info.serviceInfo.packageName;
3152            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3153                if (DEBUG_EPHEMERAL) {
3154                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3155                            + " pkg: " + packageName + ", info:" + info);
3156                }
3157                continue;
3158            }
3159
3160            if (DEBUG_EPHEMERAL) {
3161                Slog.v(TAG, "Ephemeral resolver found;"
3162                        + " pkg: " + packageName + ", info:" + info);
3163            }
3164            return new ComponentName(packageName, info.serviceInfo.name);
3165        }
3166        if (DEBUG_EPHEMERAL) {
3167            Slog.v(TAG, "Ephemeral resolver NOT found");
3168        }
3169        return null;
3170    }
3171
3172    private @Nullable ComponentName getEphemeralInstallerLPr() {
3173        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3174        intent.addCategory(Intent.CATEGORY_DEFAULT);
3175        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3176
3177        final int resolveFlags =
3178                MATCH_DIRECT_BOOT_AWARE
3179                | MATCH_DIRECT_BOOT_UNAWARE
3180                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3181        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3182                resolveFlags, UserHandle.USER_SYSTEM);
3183        Iterator<ResolveInfo> iter = matches.iterator();
3184        while (iter.hasNext()) {
3185            final ResolveInfo rInfo = iter.next();
3186            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3187            if (ps != null) {
3188                final PermissionsState permissionsState = ps.getPermissionsState();
3189                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3190                    continue;
3191                }
3192            }
3193            iter.remove();
3194        }
3195        if (matches.size() == 0) {
3196            return null;
3197        } else if (matches.size() == 1) {
3198            return matches.get(0).getComponentInfo().getComponentName();
3199        } else {
3200            throw new RuntimeException(
3201                    "There must be at most one ephemeral installer; found " + matches);
3202        }
3203    }
3204
3205    private void primeDomainVerificationsLPw(int userId) {
3206        if (DEBUG_DOMAIN_VERIFICATION) {
3207            Slog.d(TAG, "Priming domain verifications in user " + userId);
3208        }
3209
3210        SystemConfig systemConfig = SystemConfig.getInstance();
3211        ArraySet<String> packages = systemConfig.getLinkedApps();
3212
3213        for (String packageName : packages) {
3214            PackageParser.Package pkg = mPackages.get(packageName);
3215            if (pkg != null) {
3216                if (!pkg.isSystemApp()) {
3217                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3218                    continue;
3219                }
3220
3221                ArraySet<String> domains = null;
3222                for (PackageParser.Activity a : pkg.activities) {
3223                    for (ActivityIntentInfo filter : a.intents) {
3224                        if (hasValidDomains(filter)) {
3225                            if (domains == null) {
3226                                domains = new ArraySet<String>();
3227                            }
3228                            domains.addAll(filter.getHostsList());
3229                        }
3230                    }
3231                }
3232
3233                if (domains != null && domains.size() > 0) {
3234                    if (DEBUG_DOMAIN_VERIFICATION) {
3235                        Slog.v(TAG, "      + " + packageName);
3236                    }
3237                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3238                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3239                    // and then 'always' in the per-user state actually used for intent resolution.
3240                    final IntentFilterVerificationInfo ivi;
3241                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3242                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3243                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3244                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3245                } else {
3246                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3247                            + "' does not handle web links");
3248                }
3249            } else {
3250                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3251            }
3252        }
3253
3254        scheduleWritePackageRestrictionsLocked(userId);
3255        scheduleWriteSettingsLocked();
3256    }
3257
3258    private void applyFactoryDefaultBrowserLPw(int userId) {
3259        // The default browser app's package name is stored in a string resource,
3260        // with a product-specific overlay used for vendor customization.
3261        String browserPkg = mContext.getResources().getString(
3262                com.android.internal.R.string.default_browser);
3263        if (!TextUtils.isEmpty(browserPkg)) {
3264            // non-empty string => required to be a known package
3265            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3266            if (ps == null) {
3267                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3268                browserPkg = null;
3269            } else {
3270                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3271            }
3272        }
3273
3274        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3275        // default.  If there's more than one, just leave everything alone.
3276        if (browserPkg == null) {
3277            calculateDefaultBrowserLPw(userId);
3278        }
3279    }
3280
3281    private void calculateDefaultBrowserLPw(int userId) {
3282        List<String> allBrowsers = resolveAllBrowserApps(userId);
3283        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3284        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3285    }
3286
3287    private List<String> resolveAllBrowserApps(int userId) {
3288        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3289        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3290                PackageManager.MATCH_ALL, userId);
3291
3292        final int count = list.size();
3293        List<String> result = new ArrayList<String>(count);
3294        for (int i=0; i<count; i++) {
3295            ResolveInfo info = list.get(i);
3296            if (info.activityInfo == null
3297                    || !info.handleAllWebDataURI
3298                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3299                    || result.contains(info.activityInfo.packageName)) {
3300                continue;
3301            }
3302            result.add(info.activityInfo.packageName);
3303        }
3304
3305        return result;
3306    }
3307
3308    private boolean packageIsBrowser(String packageName, int userId) {
3309        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3310                PackageManager.MATCH_ALL, userId);
3311        final int N = list.size();
3312        for (int i = 0; i < N; i++) {
3313            ResolveInfo info = list.get(i);
3314            if (packageName.equals(info.activityInfo.packageName)) {
3315                return true;
3316            }
3317        }
3318        return false;
3319    }
3320
3321    private void checkDefaultBrowser() {
3322        final int myUserId = UserHandle.myUserId();
3323        final String packageName = getDefaultBrowserPackageName(myUserId);
3324        if (packageName != null) {
3325            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3326            if (info == null) {
3327                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3328                synchronized (mPackages) {
3329                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3330                }
3331            }
3332        }
3333    }
3334
3335    @Override
3336    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3337            throws RemoteException {
3338        try {
3339            return super.onTransact(code, data, reply, flags);
3340        } catch (RuntimeException e) {
3341            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3342                Slog.wtf(TAG, "Package Manager Crash", e);
3343            }
3344            throw e;
3345        }
3346    }
3347
3348    static int[] appendInts(int[] cur, int[] add) {
3349        if (add == null) return cur;
3350        if (cur == null) return add;
3351        final int N = add.length;
3352        for (int i=0; i<N; i++) {
3353            cur = appendInt(cur, add[i]);
3354        }
3355        return cur;
3356    }
3357
3358    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3359        if (!sUserManager.exists(userId)) return null;
3360        if (ps == null) {
3361            return null;
3362        }
3363        final PackageParser.Package p = ps.pkg;
3364        if (p == null) {
3365            return null;
3366        }
3367        // Filter out ephemeral app metadata:
3368        //   * The system/shell/root can see metadata for any app
3369        //   * An installed app can see metadata for 1) other installed apps
3370        //     and 2) ephemeral apps that have explicitly interacted with it
3371        //   * Ephemeral apps can only see their own metadata
3372        //   * Holding a signature permission allows seeing instant apps
3373        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3374        if (callingAppId != Process.SYSTEM_UID
3375                && callingAppId != Process.SHELL_UID
3376                && callingAppId != Process.ROOT_UID
3377                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3378                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3379            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3380            if (instantAppPackageName != null) {
3381                // ephemeral apps can only get information on themselves
3382                if (!instantAppPackageName.equals(p.packageName)) {
3383                    return null;
3384                }
3385            } else {
3386                if (ps.getInstantApp(userId)) {
3387                    // only get access to the ephemeral app if we've been granted access
3388                    if (!mInstantAppRegistry.isInstantAccessGranted(
3389                            userId, callingAppId, ps.appId)) {
3390                        return null;
3391                    }
3392                }
3393            }
3394        }
3395
3396        final PermissionsState permissionsState = ps.getPermissionsState();
3397
3398        // Compute GIDs only if requested
3399        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3400                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3401        // Compute granted permissions only if package has requested permissions
3402        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3403                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3404        final PackageUserState state = ps.readUserState(userId);
3405
3406        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3407                && ps.isSystem()) {
3408            flags |= MATCH_ANY_USER;
3409        }
3410
3411        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3412                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3413
3414        if (packageInfo == null) {
3415            return null;
3416        }
3417
3418        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3419                resolveExternalPackageNameLPr(p);
3420
3421        return packageInfo;
3422    }
3423
3424    @Override
3425    public void checkPackageStartable(String packageName, int userId) {
3426        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3427
3428        synchronized (mPackages) {
3429            final PackageSetting ps = mSettings.mPackages.get(packageName);
3430            if (ps == null) {
3431                throw new SecurityException("Package " + packageName + " was not found!");
3432            }
3433
3434            if (!ps.getInstalled(userId)) {
3435                throw new SecurityException(
3436                        "Package " + packageName + " was not installed for user " + userId + "!");
3437            }
3438
3439            if (mSafeMode && !ps.isSystem()) {
3440                throw new SecurityException("Package " + packageName + " not a system app!");
3441            }
3442
3443            if (mFrozenPackages.contains(packageName)) {
3444                throw new SecurityException("Package " + packageName + " is currently frozen!");
3445            }
3446
3447            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3448                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3449                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3450            }
3451        }
3452    }
3453
3454    @Override
3455    public boolean isPackageAvailable(String packageName, int userId) {
3456        if (!sUserManager.exists(userId)) return false;
3457        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3458                false /* requireFullPermission */, false /* checkShell */, "is package available");
3459        synchronized (mPackages) {
3460            PackageParser.Package p = mPackages.get(packageName);
3461            if (p != null) {
3462                final PackageSetting ps = (PackageSetting) p.mExtras;
3463                if (ps != null) {
3464                    final PackageUserState state = ps.readUserState(userId);
3465                    if (state != null) {
3466                        return PackageParser.isAvailable(state);
3467                    }
3468                }
3469            }
3470        }
3471        return false;
3472    }
3473
3474    @Override
3475    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3476        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3477                flags, userId);
3478    }
3479
3480    @Override
3481    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3482            int flags, int userId) {
3483        return getPackageInfoInternal(versionedPackage.getPackageName(),
3484                // TODO: We will change version code to long, so in the new API it is long
3485                (int) versionedPackage.getVersionCode(), flags, userId);
3486    }
3487
3488    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3489            int flags, int userId) {
3490        if (!sUserManager.exists(userId)) return null;
3491        flags = updateFlagsForPackage(flags, userId, packageName);
3492        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3493                false /* requireFullPermission */, false /* checkShell */, "get package info");
3494
3495        // reader
3496        synchronized (mPackages) {
3497            // Normalize package name to handle renamed packages and static libs
3498            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3499
3500            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3501            if (matchFactoryOnly) {
3502                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3503                if (ps != null) {
3504                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3505                        return null;
3506                    }
3507                    return generatePackageInfo(ps, flags, userId);
3508                }
3509            }
3510
3511            PackageParser.Package p = mPackages.get(packageName);
3512            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3513                return null;
3514            }
3515            if (DEBUG_PACKAGE_INFO)
3516                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3517            if (p != null) {
3518                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3519                        Binder.getCallingUid(), userId)) {
3520                    return null;
3521                }
3522                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3523            }
3524            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3525                final PackageSetting ps = mSettings.mPackages.get(packageName);
3526                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3527                    return null;
3528                }
3529                return generatePackageInfo(ps, flags, userId);
3530            }
3531        }
3532        return null;
3533    }
3534
3535
3536    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3537        // System/shell/root get to see all static libs
3538        final int appId = UserHandle.getAppId(uid);
3539        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3540                || appId == Process.ROOT_UID) {
3541            return false;
3542        }
3543
3544        // No package means no static lib as it is always on internal storage
3545        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3546            return false;
3547        }
3548
3549        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3550                ps.pkg.staticSharedLibVersion);
3551        if (libEntry == null) {
3552            return false;
3553        }
3554
3555        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3556        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3557        if (uidPackageNames == null) {
3558            return true;
3559        }
3560
3561        for (String uidPackageName : uidPackageNames) {
3562            if (ps.name.equals(uidPackageName)) {
3563                return false;
3564            }
3565            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3566            if (uidPs != null) {
3567                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3568                        libEntry.info.getName());
3569                if (index < 0) {
3570                    continue;
3571                }
3572                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3573                    return false;
3574                }
3575            }
3576        }
3577        return true;
3578    }
3579
3580    @Override
3581    public String[] currentToCanonicalPackageNames(String[] names) {
3582        String[] out = new String[names.length];
3583        // reader
3584        synchronized (mPackages) {
3585            for (int i=names.length-1; i>=0; i--) {
3586                PackageSetting ps = mSettings.mPackages.get(names[i]);
3587                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3588            }
3589        }
3590        return out;
3591    }
3592
3593    @Override
3594    public String[] canonicalToCurrentPackageNames(String[] names) {
3595        String[] out = new String[names.length];
3596        // reader
3597        synchronized (mPackages) {
3598            for (int i=names.length-1; i>=0; i--) {
3599                String cur = mSettings.getRenamedPackageLPr(names[i]);
3600                out[i] = cur != null ? cur : names[i];
3601            }
3602        }
3603        return out;
3604    }
3605
3606    @Override
3607    public int getPackageUid(String packageName, int flags, int userId) {
3608        if (!sUserManager.exists(userId)) return -1;
3609        flags = updateFlagsForPackage(flags, userId, packageName);
3610        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3611                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3612
3613        // reader
3614        synchronized (mPackages) {
3615            final PackageParser.Package p = mPackages.get(packageName);
3616            if (p != null && p.isMatch(flags)) {
3617                return UserHandle.getUid(userId, p.applicationInfo.uid);
3618            }
3619            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3620                final PackageSetting ps = mSettings.mPackages.get(packageName);
3621                if (ps != null && ps.isMatch(flags)) {
3622                    return UserHandle.getUid(userId, ps.appId);
3623                }
3624            }
3625        }
3626
3627        return -1;
3628    }
3629
3630    @Override
3631    public int[] getPackageGids(String packageName, int flags, int userId) {
3632        if (!sUserManager.exists(userId)) return null;
3633        flags = updateFlagsForPackage(flags, userId, packageName);
3634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635                false /* requireFullPermission */, false /* checkShell */,
3636                "getPackageGids");
3637
3638        // reader
3639        synchronized (mPackages) {
3640            final PackageParser.Package p = mPackages.get(packageName);
3641            if (p != null && p.isMatch(flags)) {
3642                PackageSetting ps = (PackageSetting) p.mExtras;
3643                // TODO: Shouldn't this be checking for package installed state for userId and
3644                // return null?
3645                return ps.getPermissionsState().computeGids(userId);
3646            }
3647            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3648                final PackageSetting ps = mSettings.mPackages.get(packageName);
3649                if (ps != null && ps.isMatch(flags)) {
3650                    return ps.getPermissionsState().computeGids(userId);
3651                }
3652            }
3653        }
3654
3655        return null;
3656    }
3657
3658    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3659        if (bp.perm != null) {
3660            return PackageParser.generatePermissionInfo(bp.perm, flags);
3661        }
3662        PermissionInfo pi = new PermissionInfo();
3663        pi.name = bp.name;
3664        pi.packageName = bp.sourcePackage;
3665        pi.nonLocalizedLabel = bp.name;
3666        pi.protectionLevel = bp.protectionLevel;
3667        return pi;
3668    }
3669
3670    @Override
3671    public PermissionInfo getPermissionInfo(String name, int flags) {
3672        // reader
3673        synchronized (mPackages) {
3674            final BasePermission p = mSettings.mPermissions.get(name);
3675            if (p != null) {
3676                return generatePermissionInfo(p, flags);
3677            }
3678            return null;
3679        }
3680    }
3681
3682    @Override
3683    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3684            int flags) {
3685        // reader
3686        synchronized (mPackages) {
3687            if (group != null && !mPermissionGroups.containsKey(group)) {
3688                // This is thrown as NameNotFoundException
3689                return null;
3690            }
3691
3692            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3693            for (BasePermission p : mSettings.mPermissions.values()) {
3694                if (group == null) {
3695                    if (p.perm == null || p.perm.info.group == null) {
3696                        out.add(generatePermissionInfo(p, flags));
3697                    }
3698                } else {
3699                    if (p.perm != null && group.equals(p.perm.info.group)) {
3700                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3701                    }
3702                }
3703            }
3704            return new ParceledListSlice<>(out);
3705        }
3706    }
3707
3708    @Override
3709    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3710        // reader
3711        synchronized (mPackages) {
3712            return PackageParser.generatePermissionGroupInfo(
3713                    mPermissionGroups.get(name), flags);
3714        }
3715    }
3716
3717    @Override
3718    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3719        // reader
3720        synchronized (mPackages) {
3721            final int N = mPermissionGroups.size();
3722            ArrayList<PermissionGroupInfo> out
3723                    = new ArrayList<PermissionGroupInfo>(N);
3724            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3725                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3726            }
3727            return new ParceledListSlice<>(out);
3728        }
3729    }
3730
3731    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3732            int uid, int userId) {
3733        if (!sUserManager.exists(userId)) return null;
3734        PackageSetting ps = mSettings.mPackages.get(packageName);
3735        if (ps != null) {
3736            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3737                return null;
3738            }
3739            if (ps.pkg == null) {
3740                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3741                if (pInfo != null) {
3742                    return pInfo.applicationInfo;
3743                }
3744                return null;
3745            }
3746            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3747                    ps.readUserState(userId), userId);
3748            if (ai != null) {
3749                rebaseEnabledOverlays(ai, userId);
3750                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3751            }
3752            return ai;
3753        }
3754        return null;
3755    }
3756
3757    @Override
3758    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3759        if (!sUserManager.exists(userId)) return null;
3760        flags = updateFlagsForApplication(flags, userId, packageName);
3761        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3762                false /* requireFullPermission */, false /* checkShell */, "get application info");
3763
3764        // writer
3765        synchronized (mPackages) {
3766            // Normalize package name to handle renamed packages and static libs
3767            packageName = resolveInternalPackageNameLPr(packageName,
3768                    PackageManager.VERSION_CODE_HIGHEST);
3769
3770            PackageParser.Package p = mPackages.get(packageName);
3771            if (DEBUG_PACKAGE_INFO) Log.v(
3772                    TAG, "getApplicationInfo " + packageName
3773                    + ": " + p);
3774            if (p != null) {
3775                PackageSetting ps = mSettings.mPackages.get(packageName);
3776                if (ps == null) return null;
3777                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3778                    return null;
3779                }
3780                // Note: isEnabledLP() does not apply here - always return info
3781                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3782                        p, flags, ps.readUserState(userId), userId);
3783                if (ai != null) {
3784                    rebaseEnabledOverlays(ai, userId);
3785                    ai.packageName = resolveExternalPackageNameLPr(p);
3786                }
3787                return ai;
3788            }
3789            if ("android".equals(packageName)||"system".equals(packageName)) {
3790                return mAndroidApplication;
3791            }
3792            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3793                // Already generates the external package name
3794                return generateApplicationInfoFromSettingsLPw(packageName,
3795                        Binder.getCallingUid(), flags, userId);
3796            }
3797        }
3798        return null;
3799    }
3800
3801    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3802        List<String> paths = new ArrayList<>();
3803        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3804            mEnabledOverlayPaths.get(userId);
3805        if (userSpecificOverlays != null) {
3806            if (!"android".equals(ai.packageName)) {
3807                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3808                if (frameworkOverlays != null) {
3809                    paths.addAll(frameworkOverlays);
3810                }
3811            }
3812
3813            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3814            if (appOverlays != null) {
3815                paths.addAll(appOverlays);
3816            }
3817        }
3818        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3819    }
3820
3821    private String normalizePackageNameLPr(String packageName) {
3822        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3823        return normalizedPackageName != null ? normalizedPackageName : packageName;
3824    }
3825
3826    @Override
3827    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3828            final IPackageDataObserver observer) {
3829        mContext.enforceCallingOrSelfPermission(
3830                android.Manifest.permission.CLEAR_APP_CACHE, null);
3831        mHandler.post(() -> {
3832            boolean success = false;
3833            try {
3834                freeStorage(volumeUuid, freeStorageSize, 0);
3835                success = true;
3836            } catch (IOException e) {
3837                Slog.w(TAG, e);
3838            }
3839            if (observer != null) {
3840                try {
3841                    observer.onRemoveCompleted(null, success);
3842                } catch (RemoteException e) {
3843                    Slog.w(TAG, e);
3844                }
3845            }
3846        });
3847    }
3848
3849    @Override
3850    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3851            final IntentSender pi) {
3852        mContext.enforceCallingOrSelfPermission(
3853                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3854        mHandler.post(() -> {
3855            boolean success = false;
3856            try {
3857                freeStorage(volumeUuid, freeStorageSize, 0);
3858                success = true;
3859            } catch (IOException e) {
3860                Slog.w(TAG, e);
3861            }
3862            if (pi != null) {
3863                try {
3864                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3865                } catch (SendIntentException e) {
3866                    Slog.w(TAG, e);
3867                }
3868            }
3869        });
3870    }
3871
3872    /**
3873     * Blocking call to clear various types of cached data across the system
3874     * until the requested bytes are available.
3875     */
3876    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3877        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3878        final File file = storage.findPathForUuid(volumeUuid);
3879
3880        if (ENABLE_FREE_CACHE_V2) {
3881            final boolean aggressive = (storageFlags
3882                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3883
3884            // 1. Pre-flight to determine if we have any chance to succeed
3885            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3886
3887            // 3. Consider parsed APK data (aggressive only)
3888            if (aggressive) {
3889                FileUtils.deleteContents(mCacheDir);
3890            }
3891            if (file.getUsableSpace() >= bytes) return;
3892
3893            // 4. Consider cached app data (above quotas)
3894            try {
3895                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3896            } catch (InstallerException ignored) {
3897            }
3898            if (file.getUsableSpace() >= bytes) return;
3899
3900            // 5. Consider shared libraries with refcount=0 and age>2h
3901            // 6. Consider dexopt output (aggressive only)
3902            // 7. Consider ephemeral apps not used in last week
3903
3904            // 8. Consider cached app data (below quotas)
3905            try {
3906                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3907                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3908            } catch (InstallerException ignored) {
3909            }
3910            if (file.getUsableSpace() >= bytes) return;
3911
3912            // 9. Consider DropBox entries
3913            // 10. Consider ephemeral cookies
3914
3915        } else {
3916            try {
3917                mInstaller.freeCache(volumeUuid, bytes, 0);
3918            } catch (InstallerException ignored) {
3919            }
3920            if (file.getUsableSpace() >= bytes) return;
3921        }
3922
3923        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3924    }
3925
3926    /**
3927     * Update given flags based on encryption status of current user.
3928     */
3929    private int updateFlags(int flags, int userId) {
3930        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3931                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3932            // Caller expressed an explicit opinion about what encryption
3933            // aware/unaware components they want to see, so fall through and
3934            // give them what they want
3935        } else {
3936            // Caller expressed no opinion, so match based on user state
3937            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3938                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3939            } else {
3940                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3941            }
3942        }
3943        return flags;
3944    }
3945
3946    private UserManagerInternal getUserManagerInternal() {
3947        if (mUserManagerInternal == null) {
3948            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3949        }
3950        return mUserManagerInternal;
3951    }
3952
3953    private DeviceIdleController.LocalService getDeviceIdleController() {
3954        if (mDeviceIdleController == null) {
3955            mDeviceIdleController =
3956                    LocalServices.getService(DeviceIdleController.LocalService.class);
3957        }
3958        return mDeviceIdleController;
3959    }
3960
3961    /**
3962     * Update given flags when being used to request {@link PackageInfo}.
3963     */
3964    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3965        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3966        boolean triaged = true;
3967        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3968                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3969            // Caller is asking for component details, so they'd better be
3970            // asking for specific encryption matching behavior, or be triaged
3971            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3972                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3973                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3974                triaged = false;
3975            }
3976        }
3977        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3978                | PackageManager.MATCH_SYSTEM_ONLY
3979                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3980            triaged = false;
3981        }
3982        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3983            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3984                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3985                    + Debug.getCallers(5));
3986        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3987                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3988            // If the caller wants all packages and has a restricted profile associated with it,
3989            // then match all users. This is to make sure that launchers that need to access work
3990            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3991            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3992            flags |= PackageManager.MATCH_ANY_USER;
3993        }
3994        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3995            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3996                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3997        }
3998        return updateFlags(flags, userId);
3999    }
4000
4001    /**
4002     * Update given flags when being used to request {@link ApplicationInfo}.
4003     */
4004    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4005        return updateFlagsForPackage(flags, userId, cookie);
4006    }
4007
4008    /**
4009     * Update given flags when being used to request {@link ComponentInfo}.
4010     */
4011    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4012        if (cookie instanceof Intent) {
4013            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4014                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4015            }
4016        }
4017
4018        boolean triaged = true;
4019        // Caller is asking for component details, so they'd better be
4020        // asking for specific encryption matching behavior, or be triaged
4021        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4022                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4023                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4024            triaged = false;
4025        }
4026        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4027            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4028                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4029        }
4030
4031        return updateFlags(flags, userId);
4032    }
4033
4034    /**
4035     * Update given intent when being used to request {@link ResolveInfo}.
4036     */
4037    private Intent updateIntentForResolve(Intent intent) {
4038        if (intent.getSelector() != null) {
4039            intent = intent.getSelector();
4040        }
4041        if (DEBUG_PREFERRED) {
4042            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4043        }
4044        return intent;
4045    }
4046
4047    /**
4048     * Update given flags when being used to request {@link ResolveInfo}.
4049     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4050     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4051     * flag set. However, this flag is only honoured in three circumstances:
4052     * <ul>
4053     * <li>when called from a system process</li>
4054     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4055     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4056     * action and a {@code android.intent.category.BROWSABLE} category</li>
4057     * </ul>
4058     */
4059    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4060        // Safe mode means we shouldn't match any third-party components
4061        if (mSafeMode) {
4062            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4063        }
4064        final int callingUid = Binder.getCallingUid();
4065        if (getInstantAppPackageName(callingUid) != null) {
4066            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4067            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4068            flags |= PackageManager.MATCH_INSTANT;
4069        } else {
4070            // Otherwise, prevent leaking ephemeral components
4071            final boolean isSpecialProcess =
4072                    callingUid == Process.SYSTEM_UID
4073                    || callingUid == Process.SHELL_UID
4074                    || callingUid == 0;
4075            final boolean allowMatchInstant =
4076                    (includeInstantApp
4077                            && Intent.ACTION_VIEW.equals(intent.getAction())
4078                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4079                            && hasWebURI(intent))
4080                    || isSpecialProcess
4081                    || mContext.checkCallingOrSelfPermission(
4082                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4083            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4084            if (!allowMatchInstant) {
4085                flags &= ~PackageManager.MATCH_INSTANT;
4086            }
4087        }
4088        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4089    }
4090
4091    @Override
4092    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4093        if (!sUserManager.exists(userId)) return null;
4094        flags = updateFlagsForComponent(flags, userId, component);
4095        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4096                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4097        synchronized (mPackages) {
4098            PackageParser.Activity a = mActivities.mActivities.get(component);
4099
4100            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4101            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4102                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4103                if (ps == null) return null;
4104                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4105                        userId);
4106            }
4107            if (mResolveComponentName.equals(component)) {
4108                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4109                        new PackageUserState(), userId);
4110            }
4111        }
4112        return null;
4113    }
4114
4115    @Override
4116    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4117            String resolvedType) {
4118        synchronized (mPackages) {
4119            if (component.equals(mResolveComponentName)) {
4120                // The resolver supports EVERYTHING!
4121                return true;
4122            }
4123            PackageParser.Activity a = mActivities.mActivities.get(component);
4124            if (a == null) {
4125                return false;
4126            }
4127            for (int i=0; i<a.intents.size(); i++) {
4128                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4129                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4130                    return true;
4131                }
4132            }
4133            return false;
4134        }
4135    }
4136
4137    @Override
4138    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4139        if (!sUserManager.exists(userId)) return null;
4140        flags = updateFlagsForComponent(flags, userId, component);
4141        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4142                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4143        synchronized (mPackages) {
4144            PackageParser.Activity a = mReceivers.mActivities.get(component);
4145            if (DEBUG_PACKAGE_INFO) Log.v(
4146                TAG, "getReceiverInfo " + component + ": " + a);
4147            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4148                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4149                if (ps == null) return null;
4150                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4151                        userId);
4152            }
4153        }
4154        return null;
4155    }
4156
4157    @Override
4158    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4159        if (!sUserManager.exists(userId)) return null;
4160        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4161
4162        flags = updateFlagsForPackage(flags, userId, null);
4163
4164        final boolean canSeeStaticLibraries =
4165                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4166                        == PERMISSION_GRANTED
4167                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4168                        == PERMISSION_GRANTED
4169                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4170                        == PERMISSION_GRANTED
4171                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4172                        == PERMISSION_GRANTED;
4173
4174        synchronized (mPackages) {
4175            List<SharedLibraryInfo> result = null;
4176
4177            final int libCount = mSharedLibraries.size();
4178            for (int i = 0; i < libCount; i++) {
4179                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4180                if (versionedLib == null) {
4181                    continue;
4182                }
4183
4184                final int versionCount = versionedLib.size();
4185                for (int j = 0; j < versionCount; j++) {
4186                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4187                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4188                        break;
4189                    }
4190                    final long identity = Binder.clearCallingIdentity();
4191                    try {
4192                        // TODO: We will change version code to long, so in the new API it is long
4193                        PackageInfo packageInfo = getPackageInfoVersioned(
4194                                libInfo.getDeclaringPackage(), flags, userId);
4195                        if (packageInfo == null) {
4196                            continue;
4197                        }
4198                    } finally {
4199                        Binder.restoreCallingIdentity(identity);
4200                    }
4201
4202                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4203                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4204                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4205
4206                    if (result == null) {
4207                        result = new ArrayList<>();
4208                    }
4209                    result.add(resLibInfo);
4210                }
4211            }
4212
4213            return result != null ? new ParceledListSlice<>(result) : null;
4214        }
4215    }
4216
4217    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4218            SharedLibraryInfo libInfo, int flags, int userId) {
4219        List<VersionedPackage> versionedPackages = null;
4220        final int packageCount = mSettings.mPackages.size();
4221        for (int i = 0; i < packageCount; i++) {
4222            PackageSetting ps = mSettings.mPackages.valueAt(i);
4223
4224            if (ps == null) {
4225                continue;
4226            }
4227
4228            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4229                continue;
4230            }
4231
4232            final String libName = libInfo.getName();
4233            if (libInfo.isStatic()) {
4234                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4235                if (libIdx < 0) {
4236                    continue;
4237                }
4238                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4239                    continue;
4240                }
4241                if (versionedPackages == null) {
4242                    versionedPackages = new ArrayList<>();
4243                }
4244                // If the dependent is a static shared lib, use the public package name
4245                String dependentPackageName = ps.name;
4246                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4247                    dependentPackageName = ps.pkg.manifestPackageName;
4248                }
4249                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4250            } else if (ps.pkg != null) {
4251                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4252                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4253                    if (versionedPackages == null) {
4254                        versionedPackages = new ArrayList<>();
4255                    }
4256                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4257                }
4258            }
4259        }
4260
4261        return versionedPackages;
4262    }
4263
4264    @Override
4265    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4266        if (!sUserManager.exists(userId)) return null;
4267        flags = updateFlagsForComponent(flags, userId, component);
4268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4269                false /* requireFullPermission */, false /* checkShell */, "get service info");
4270        synchronized (mPackages) {
4271            PackageParser.Service s = mServices.mServices.get(component);
4272            if (DEBUG_PACKAGE_INFO) Log.v(
4273                TAG, "getServiceInfo " + component + ": " + s);
4274            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4275                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4276                if (ps == null) return null;
4277                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4278                        userId);
4279            }
4280        }
4281        return null;
4282    }
4283
4284    @Override
4285    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4286        if (!sUserManager.exists(userId)) return null;
4287        flags = updateFlagsForComponent(flags, userId, component);
4288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4289                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4290        synchronized (mPackages) {
4291            PackageParser.Provider p = mProviders.mProviders.get(component);
4292            if (DEBUG_PACKAGE_INFO) Log.v(
4293                TAG, "getProviderInfo " + component + ": " + p);
4294            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4296                if (ps == null) return null;
4297                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4298                        userId);
4299            }
4300        }
4301        return null;
4302    }
4303
4304    @Override
4305    public String[] getSystemSharedLibraryNames() {
4306        synchronized (mPackages) {
4307            Set<String> libs = null;
4308            final int libCount = mSharedLibraries.size();
4309            for (int i = 0; i < libCount; i++) {
4310                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4311                if (versionedLib == null) {
4312                    continue;
4313                }
4314                final int versionCount = versionedLib.size();
4315                for (int j = 0; j < versionCount; j++) {
4316                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4317                    if (!libEntry.info.isStatic()) {
4318                        if (libs == null) {
4319                            libs = new ArraySet<>();
4320                        }
4321                        libs.add(libEntry.info.getName());
4322                        break;
4323                    }
4324                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4325                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4326                            UserHandle.getUserId(Binder.getCallingUid()))) {
4327                        if (libs == null) {
4328                            libs = new ArraySet<>();
4329                        }
4330                        libs.add(libEntry.info.getName());
4331                        break;
4332                    }
4333                }
4334            }
4335
4336            if (libs != null) {
4337                String[] libsArray = new String[libs.size()];
4338                libs.toArray(libsArray);
4339                return libsArray;
4340            }
4341
4342            return null;
4343        }
4344    }
4345
4346    @Override
4347    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4348        synchronized (mPackages) {
4349            return mServicesSystemSharedLibraryPackageName;
4350        }
4351    }
4352
4353    @Override
4354    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4355        synchronized (mPackages) {
4356            return mSharedSystemSharedLibraryPackageName;
4357        }
4358    }
4359
4360    private void updateSequenceNumberLP(String packageName, int[] userList) {
4361        for (int i = userList.length - 1; i >= 0; --i) {
4362            final int userId = userList[i];
4363            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4364            if (changedPackages == null) {
4365                changedPackages = new SparseArray<>();
4366                mChangedPackages.put(userId, changedPackages);
4367            }
4368            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4369            if (sequenceNumbers == null) {
4370                sequenceNumbers = new HashMap<>();
4371                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4372            }
4373            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4374            if (sequenceNumber != null) {
4375                changedPackages.remove(sequenceNumber);
4376            }
4377            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4378            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4379        }
4380        mChangedPackagesSequenceNumber++;
4381    }
4382
4383    @Override
4384    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4385        synchronized (mPackages) {
4386            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4387                return null;
4388            }
4389            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4390            if (changedPackages == null) {
4391                return null;
4392            }
4393            final List<String> packageNames =
4394                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4395            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4396                final String packageName = changedPackages.get(i);
4397                if (packageName != null) {
4398                    packageNames.add(packageName);
4399                }
4400            }
4401            return packageNames.isEmpty()
4402                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4403        }
4404    }
4405
4406    @Override
4407    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4408        ArrayList<FeatureInfo> res;
4409        synchronized (mAvailableFeatures) {
4410            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4411            res.addAll(mAvailableFeatures.values());
4412        }
4413        final FeatureInfo fi = new FeatureInfo();
4414        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4415                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4416        res.add(fi);
4417
4418        return new ParceledListSlice<>(res);
4419    }
4420
4421    @Override
4422    public boolean hasSystemFeature(String name, int version) {
4423        synchronized (mAvailableFeatures) {
4424            final FeatureInfo feat = mAvailableFeatures.get(name);
4425            if (feat == null) {
4426                return false;
4427            } else {
4428                return feat.version >= version;
4429            }
4430        }
4431    }
4432
4433    @Override
4434    public int checkPermission(String permName, String pkgName, int userId) {
4435        if (!sUserManager.exists(userId)) {
4436            return PackageManager.PERMISSION_DENIED;
4437        }
4438
4439        synchronized (mPackages) {
4440            final PackageParser.Package p = mPackages.get(pkgName);
4441            if (p != null && p.mExtras != null) {
4442                final PackageSetting ps = (PackageSetting) p.mExtras;
4443                final PermissionsState permissionsState = ps.getPermissionsState();
4444                if (permissionsState.hasPermission(permName, userId)) {
4445                    return PackageManager.PERMISSION_GRANTED;
4446                }
4447                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4448                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4449                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4450                    return PackageManager.PERMISSION_GRANTED;
4451                }
4452            }
4453        }
4454
4455        return PackageManager.PERMISSION_DENIED;
4456    }
4457
4458    @Override
4459    public int checkUidPermission(String permName, int uid) {
4460        final int userId = UserHandle.getUserId(uid);
4461
4462        if (!sUserManager.exists(userId)) {
4463            return PackageManager.PERMISSION_DENIED;
4464        }
4465
4466        synchronized (mPackages) {
4467            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4468            if (obj != null) {
4469                final SettingBase ps = (SettingBase) obj;
4470                final PermissionsState permissionsState = ps.getPermissionsState();
4471                if (permissionsState.hasPermission(permName, userId)) {
4472                    return PackageManager.PERMISSION_GRANTED;
4473                }
4474                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4475                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4476                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4477                    return PackageManager.PERMISSION_GRANTED;
4478                }
4479            } else {
4480                ArraySet<String> perms = mSystemPermissions.get(uid);
4481                if (perms != null) {
4482                    if (perms.contains(permName)) {
4483                        return PackageManager.PERMISSION_GRANTED;
4484                    }
4485                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4486                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4487                        return PackageManager.PERMISSION_GRANTED;
4488                    }
4489                }
4490            }
4491        }
4492
4493        return PackageManager.PERMISSION_DENIED;
4494    }
4495
4496    @Override
4497    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4498        if (UserHandle.getCallingUserId() != userId) {
4499            mContext.enforceCallingPermission(
4500                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4501                    "isPermissionRevokedByPolicy for user " + userId);
4502        }
4503
4504        if (checkPermission(permission, packageName, userId)
4505                == PackageManager.PERMISSION_GRANTED) {
4506            return false;
4507        }
4508
4509        final long identity = Binder.clearCallingIdentity();
4510        try {
4511            final int flags = getPermissionFlags(permission, packageName, userId);
4512            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4513        } finally {
4514            Binder.restoreCallingIdentity(identity);
4515        }
4516    }
4517
4518    @Override
4519    public String getPermissionControllerPackageName() {
4520        synchronized (mPackages) {
4521            return mRequiredInstallerPackage;
4522        }
4523    }
4524
4525    /**
4526     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4527     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4528     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4529     * @param message the message to log on security exception
4530     */
4531    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4532            boolean checkShell, String message) {
4533        if (userId < 0) {
4534            throw new IllegalArgumentException("Invalid userId " + userId);
4535        }
4536        if (checkShell) {
4537            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4538        }
4539        if (userId == UserHandle.getUserId(callingUid)) return;
4540        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4541            if (requireFullPermission) {
4542                mContext.enforceCallingOrSelfPermission(
4543                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4544            } else {
4545                try {
4546                    mContext.enforceCallingOrSelfPermission(
4547                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4548                } catch (SecurityException se) {
4549                    mContext.enforceCallingOrSelfPermission(
4550                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4551                }
4552            }
4553        }
4554    }
4555
4556    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4557        if (callingUid == Process.SHELL_UID) {
4558            if (userHandle >= 0
4559                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4560                throw new SecurityException("Shell does not have permission to access user "
4561                        + userHandle);
4562            } else if (userHandle < 0) {
4563                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4564                        + Debug.getCallers(3));
4565            }
4566        }
4567    }
4568
4569    private BasePermission findPermissionTreeLP(String permName) {
4570        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4571            if (permName.startsWith(bp.name) &&
4572                    permName.length() > bp.name.length() &&
4573                    permName.charAt(bp.name.length()) == '.') {
4574                return bp;
4575            }
4576        }
4577        return null;
4578    }
4579
4580    private BasePermission checkPermissionTreeLP(String permName) {
4581        if (permName != null) {
4582            BasePermission bp = findPermissionTreeLP(permName);
4583            if (bp != null) {
4584                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4585                    return bp;
4586                }
4587                throw new SecurityException("Calling uid "
4588                        + Binder.getCallingUid()
4589                        + " is not allowed to add to permission tree "
4590                        + bp.name + " owned by uid " + bp.uid);
4591            }
4592        }
4593        throw new SecurityException("No permission tree found for " + permName);
4594    }
4595
4596    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4597        if (s1 == null) {
4598            return s2 == null;
4599        }
4600        if (s2 == null) {
4601            return false;
4602        }
4603        if (s1.getClass() != s2.getClass()) {
4604            return false;
4605        }
4606        return s1.equals(s2);
4607    }
4608
4609    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4610        if (pi1.icon != pi2.icon) return false;
4611        if (pi1.logo != pi2.logo) return false;
4612        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4613        if (!compareStrings(pi1.name, pi2.name)) return false;
4614        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4615        // We'll take care of setting this one.
4616        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4617        // These are not currently stored in settings.
4618        //if (!compareStrings(pi1.group, pi2.group)) return false;
4619        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4620        //if (pi1.labelRes != pi2.labelRes) return false;
4621        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4622        return true;
4623    }
4624
4625    int permissionInfoFootprint(PermissionInfo info) {
4626        int size = info.name.length();
4627        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4628        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4629        return size;
4630    }
4631
4632    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4633        int size = 0;
4634        for (BasePermission perm : mSettings.mPermissions.values()) {
4635            if (perm.uid == tree.uid) {
4636                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4637            }
4638        }
4639        return size;
4640    }
4641
4642    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4643        // We calculate the max size of permissions defined by this uid and throw
4644        // if that plus the size of 'info' would exceed our stated maximum.
4645        if (tree.uid != Process.SYSTEM_UID) {
4646            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4647            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4648                throw new SecurityException("Permission tree size cap exceeded");
4649            }
4650        }
4651    }
4652
4653    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4654        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4655            throw new SecurityException("Label must be specified in permission");
4656        }
4657        BasePermission tree = checkPermissionTreeLP(info.name);
4658        BasePermission bp = mSettings.mPermissions.get(info.name);
4659        boolean added = bp == null;
4660        boolean changed = true;
4661        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4662        if (added) {
4663            enforcePermissionCapLocked(info, tree);
4664            bp = new BasePermission(info.name, tree.sourcePackage,
4665                    BasePermission.TYPE_DYNAMIC);
4666        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4667            throw new SecurityException(
4668                    "Not allowed to modify non-dynamic permission "
4669                    + info.name);
4670        } else {
4671            if (bp.protectionLevel == fixedLevel
4672                    && bp.perm.owner.equals(tree.perm.owner)
4673                    && bp.uid == tree.uid
4674                    && comparePermissionInfos(bp.perm.info, info)) {
4675                changed = false;
4676            }
4677        }
4678        bp.protectionLevel = fixedLevel;
4679        info = new PermissionInfo(info);
4680        info.protectionLevel = fixedLevel;
4681        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4682        bp.perm.info.packageName = tree.perm.info.packageName;
4683        bp.uid = tree.uid;
4684        if (added) {
4685            mSettings.mPermissions.put(info.name, bp);
4686        }
4687        if (changed) {
4688            if (!async) {
4689                mSettings.writeLPr();
4690            } else {
4691                scheduleWriteSettingsLocked();
4692            }
4693        }
4694        return added;
4695    }
4696
4697    @Override
4698    public boolean addPermission(PermissionInfo info) {
4699        synchronized (mPackages) {
4700            return addPermissionLocked(info, false);
4701        }
4702    }
4703
4704    @Override
4705    public boolean addPermissionAsync(PermissionInfo info) {
4706        synchronized (mPackages) {
4707            return addPermissionLocked(info, true);
4708        }
4709    }
4710
4711    @Override
4712    public void removePermission(String name) {
4713        synchronized (mPackages) {
4714            checkPermissionTreeLP(name);
4715            BasePermission bp = mSettings.mPermissions.get(name);
4716            if (bp != null) {
4717                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4718                    throw new SecurityException(
4719                            "Not allowed to modify non-dynamic permission "
4720                            + name);
4721                }
4722                mSettings.mPermissions.remove(name);
4723                mSettings.writeLPr();
4724            }
4725        }
4726    }
4727
4728    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4729            BasePermission bp) {
4730        int index = pkg.requestedPermissions.indexOf(bp.name);
4731        if (index == -1) {
4732            throw new SecurityException("Package " + pkg.packageName
4733                    + " has not requested permission " + bp.name);
4734        }
4735        if (!bp.isRuntime() && !bp.isDevelopment()) {
4736            throw new SecurityException("Permission " + bp.name
4737                    + " is not a changeable permission type");
4738        }
4739    }
4740
4741    @Override
4742    public void grantRuntimePermission(String packageName, String name, final int userId) {
4743        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4744    }
4745
4746    private void grantRuntimePermission(String packageName, String name, final int userId,
4747            boolean overridePolicy) {
4748        if (!sUserManager.exists(userId)) {
4749            Log.e(TAG, "No such user:" + userId);
4750            return;
4751        }
4752
4753        mContext.enforceCallingOrSelfPermission(
4754                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4755                "grantRuntimePermission");
4756
4757        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4758                true /* requireFullPermission */, true /* checkShell */,
4759                "grantRuntimePermission");
4760
4761        final int uid;
4762        final SettingBase sb;
4763
4764        synchronized (mPackages) {
4765            final PackageParser.Package pkg = mPackages.get(packageName);
4766            if (pkg == null) {
4767                throw new IllegalArgumentException("Unknown package: " + packageName);
4768            }
4769
4770            final BasePermission bp = mSettings.mPermissions.get(name);
4771            if (bp == null) {
4772                throw new IllegalArgumentException("Unknown permission: " + name);
4773            }
4774
4775            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4776
4777            // If a permission review is required for legacy apps we represent
4778            // their permissions as always granted runtime ones since we need
4779            // to keep the review required permission flag per user while an
4780            // install permission's state is shared across all users.
4781            if (mPermissionReviewRequired
4782                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4783                    && bp.isRuntime()) {
4784                return;
4785            }
4786
4787            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4788            sb = (SettingBase) pkg.mExtras;
4789            if (sb == null) {
4790                throw new IllegalArgumentException("Unknown package: " + packageName);
4791            }
4792
4793            final PermissionsState permissionsState = sb.getPermissionsState();
4794
4795            final int flags = permissionsState.getPermissionFlags(name, userId);
4796            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4797                throw new SecurityException("Cannot grant system fixed permission "
4798                        + name + " for package " + packageName);
4799            }
4800            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4801                throw new SecurityException("Cannot grant policy fixed permission "
4802                        + name + " for package " + packageName);
4803            }
4804
4805            if (bp.isDevelopment()) {
4806                // Development permissions must be handled specially, since they are not
4807                // normal runtime permissions.  For now they apply to all users.
4808                if (permissionsState.grantInstallPermission(bp) !=
4809                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4810                    scheduleWriteSettingsLocked();
4811                }
4812                return;
4813            }
4814
4815            final PackageSetting ps = mSettings.mPackages.get(packageName);
4816            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4817                throw new SecurityException("Cannot grant non-ephemeral permission"
4818                        + name + " for package " + packageName);
4819            }
4820
4821            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4822                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4823                return;
4824            }
4825
4826            final int result = permissionsState.grantRuntimePermission(bp, userId);
4827            switch (result) {
4828                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4829                    return;
4830                }
4831
4832                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4833                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4834                    mHandler.post(new Runnable() {
4835                        @Override
4836                        public void run() {
4837                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4838                        }
4839                    });
4840                }
4841                break;
4842            }
4843
4844            if (bp.isRuntime()) {
4845                logPermissionGranted(mContext, name, packageName);
4846            }
4847
4848            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4849
4850            // Not critical if that is lost - app has to request again.
4851            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4852        }
4853
4854        // Only need to do this if user is initialized. Otherwise it's a new user
4855        // and there are no processes running as the user yet and there's no need
4856        // to make an expensive call to remount processes for the changed permissions.
4857        if (READ_EXTERNAL_STORAGE.equals(name)
4858                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4859            final long token = Binder.clearCallingIdentity();
4860            try {
4861                if (sUserManager.isInitialized(userId)) {
4862                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4863                            StorageManagerInternal.class);
4864                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4865                }
4866            } finally {
4867                Binder.restoreCallingIdentity(token);
4868            }
4869        }
4870    }
4871
4872    @Override
4873    public void revokeRuntimePermission(String packageName, String name, int userId) {
4874        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4875    }
4876
4877    private void revokeRuntimePermission(String packageName, String name, int userId,
4878            boolean overridePolicy) {
4879        if (!sUserManager.exists(userId)) {
4880            Log.e(TAG, "No such user:" + userId);
4881            return;
4882        }
4883
4884        mContext.enforceCallingOrSelfPermission(
4885                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4886                "revokeRuntimePermission");
4887
4888        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4889                true /* requireFullPermission */, true /* checkShell */,
4890                "revokeRuntimePermission");
4891
4892        final int appId;
4893
4894        synchronized (mPackages) {
4895            final PackageParser.Package pkg = mPackages.get(packageName);
4896            if (pkg == null) {
4897                throw new IllegalArgumentException("Unknown package: " + packageName);
4898            }
4899
4900            final BasePermission bp = mSettings.mPermissions.get(name);
4901            if (bp == null) {
4902                throw new IllegalArgumentException("Unknown permission: " + name);
4903            }
4904
4905            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4906
4907            // If a permission review is required for legacy apps we represent
4908            // their permissions as always granted runtime ones since we need
4909            // to keep the review required permission flag per user while an
4910            // install permission's state is shared across all users.
4911            if (mPermissionReviewRequired
4912                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4913                    && bp.isRuntime()) {
4914                return;
4915            }
4916
4917            SettingBase sb = (SettingBase) pkg.mExtras;
4918            if (sb == null) {
4919                throw new IllegalArgumentException("Unknown package: " + packageName);
4920            }
4921
4922            final PermissionsState permissionsState = sb.getPermissionsState();
4923
4924            final int flags = permissionsState.getPermissionFlags(name, userId);
4925            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4926                throw new SecurityException("Cannot revoke system fixed permission "
4927                        + name + " for package " + packageName);
4928            }
4929            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4930                throw new SecurityException("Cannot revoke policy fixed permission "
4931                        + name + " for package " + packageName);
4932            }
4933
4934            if (bp.isDevelopment()) {
4935                // Development permissions must be handled specially, since they are not
4936                // normal runtime permissions.  For now they apply to all users.
4937                if (permissionsState.revokeInstallPermission(bp) !=
4938                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4939                    scheduleWriteSettingsLocked();
4940                }
4941                return;
4942            }
4943
4944            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4945                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4946                return;
4947            }
4948
4949            if (bp.isRuntime()) {
4950                logPermissionRevoked(mContext, name, packageName);
4951            }
4952
4953            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4954
4955            // Critical, after this call app should never have the permission.
4956            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4957
4958            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4959        }
4960
4961        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4962    }
4963
4964    /**
4965     * Get the first event id for the permission.
4966     *
4967     * <p>There are four events for each permission: <ul>
4968     *     <li>Request permission: first id + 0</li>
4969     *     <li>Grant permission: first id + 1</li>
4970     *     <li>Request for permission denied: first id + 2</li>
4971     *     <li>Revoke permission: first id + 3</li>
4972     * </ul></p>
4973     *
4974     * @param name name of the permission
4975     *
4976     * @return The first event id for the permission
4977     */
4978    private static int getBaseEventId(@NonNull String name) {
4979        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4980
4981        if (eventIdIndex == -1) {
4982            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4983                    || "user".equals(Build.TYPE)) {
4984                Log.i(TAG, "Unknown permission " + name);
4985
4986                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4987            } else {
4988                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4989                //
4990                // Also update
4991                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4992                // - metrics_constants.proto
4993                throw new IllegalStateException("Unknown permission " + name);
4994            }
4995        }
4996
4997        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4998    }
4999
5000    /**
5001     * Log that a permission was revoked.
5002     *
5003     * @param context Context of the caller
5004     * @param name name of the permission
5005     * @param packageName package permission if for
5006     */
5007    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5008            @NonNull String packageName) {
5009        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5010    }
5011
5012    /**
5013     * Log that a permission request was granted.
5014     *
5015     * @param context Context of the caller
5016     * @param name name of the permission
5017     * @param packageName package permission if for
5018     */
5019    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5020            @NonNull String packageName) {
5021        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5022    }
5023
5024    @Override
5025    public void resetRuntimePermissions() {
5026        mContext.enforceCallingOrSelfPermission(
5027                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5028                "revokeRuntimePermission");
5029
5030        int callingUid = Binder.getCallingUid();
5031        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5032            mContext.enforceCallingOrSelfPermission(
5033                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5034                    "resetRuntimePermissions");
5035        }
5036
5037        synchronized (mPackages) {
5038            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5039            for (int userId : UserManagerService.getInstance().getUserIds()) {
5040                final int packageCount = mPackages.size();
5041                for (int i = 0; i < packageCount; i++) {
5042                    PackageParser.Package pkg = mPackages.valueAt(i);
5043                    if (!(pkg.mExtras instanceof PackageSetting)) {
5044                        continue;
5045                    }
5046                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5047                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5048                }
5049            }
5050        }
5051    }
5052
5053    @Override
5054    public int getPermissionFlags(String name, String packageName, int userId) {
5055        if (!sUserManager.exists(userId)) {
5056            return 0;
5057        }
5058
5059        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5060
5061        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5062                true /* requireFullPermission */, false /* checkShell */,
5063                "getPermissionFlags");
5064
5065        synchronized (mPackages) {
5066            final PackageParser.Package pkg = mPackages.get(packageName);
5067            if (pkg == null) {
5068                return 0;
5069            }
5070
5071            final BasePermission bp = mSettings.mPermissions.get(name);
5072            if (bp == null) {
5073                return 0;
5074            }
5075
5076            SettingBase sb = (SettingBase) pkg.mExtras;
5077            if (sb == null) {
5078                return 0;
5079            }
5080
5081            PermissionsState permissionsState = sb.getPermissionsState();
5082            return permissionsState.getPermissionFlags(name, userId);
5083        }
5084    }
5085
5086    @Override
5087    public void updatePermissionFlags(String name, String packageName, int flagMask,
5088            int flagValues, int userId) {
5089        if (!sUserManager.exists(userId)) {
5090            return;
5091        }
5092
5093        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5094
5095        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5096                true /* requireFullPermission */, true /* checkShell */,
5097                "updatePermissionFlags");
5098
5099        // Only the system can change these flags and nothing else.
5100        if (getCallingUid() != Process.SYSTEM_UID) {
5101            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5102            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5103            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5104            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5105            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5106        }
5107
5108        synchronized (mPackages) {
5109            final PackageParser.Package pkg = mPackages.get(packageName);
5110            if (pkg == null) {
5111                throw new IllegalArgumentException("Unknown package: " + packageName);
5112            }
5113
5114            final BasePermission bp = mSettings.mPermissions.get(name);
5115            if (bp == null) {
5116                throw new IllegalArgumentException("Unknown permission: " + name);
5117            }
5118
5119            SettingBase sb = (SettingBase) pkg.mExtras;
5120            if (sb == null) {
5121                throw new IllegalArgumentException("Unknown package: " + packageName);
5122            }
5123
5124            PermissionsState permissionsState = sb.getPermissionsState();
5125
5126            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5127
5128            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5129                // Install and runtime permissions are stored in different places,
5130                // so figure out what permission changed and persist the change.
5131                if (permissionsState.getInstallPermissionState(name) != null) {
5132                    scheduleWriteSettingsLocked();
5133                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5134                        || hadState) {
5135                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5136                }
5137            }
5138        }
5139    }
5140
5141    /**
5142     * Update the permission flags for all packages and runtime permissions of a user in order
5143     * to allow device or profile owner to remove POLICY_FIXED.
5144     */
5145    @Override
5146    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5147        if (!sUserManager.exists(userId)) {
5148            return;
5149        }
5150
5151        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5152
5153        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5154                true /* requireFullPermission */, true /* checkShell */,
5155                "updatePermissionFlagsForAllApps");
5156
5157        // Only the system can change system fixed flags.
5158        if (getCallingUid() != Process.SYSTEM_UID) {
5159            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5160            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5161        }
5162
5163        synchronized (mPackages) {
5164            boolean changed = false;
5165            final int packageCount = mPackages.size();
5166            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5167                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5168                SettingBase sb = (SettingBase) pkg.mExtras;
5169                if (sb == null) {
5170                    continue;
5171                }
5172                PermissionsState permissionsState = sb.getPermissionsState();
5173                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5174                        userId, flagMask, flagValues);
5175            }
5176            if (changed) {
5177                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5178            }
5179        }
5180    }
5181
5182    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5183        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5184                != PackageManager.PERMISSION_GRANTED
5185            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5186                != PackageManager.PERMISSION_GRANTED) {
5187            throw new SecurityException(message + " requires "
5188                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5189                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5190        }
5191    }
5192
5193    @Override
5194    public boolean shouldShowRequestPermissionRationale(String permissionName,
5195            String packageName, int userId) {
5196        if (UserHandle.getCallingUserId() != userId) {
5197            mContext.enforceCallingPermission(
5198                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5199                    "canShowRequestPermissionRationale for user " + userId);
5200        }
5201
5202        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5203        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5204            return false;
5205        }
5206
5207        if (checkPermission(permissionName, packageName, userId)
5208                == PackageManager.PERMISSION_GRANTED) {
5209            return false;
5210        }
5211
5212        final int flags;
5213
5214        final long identity = Binder.clearCallingIdentity();
5215        try {
5216            flags = getPermissionFlags(permissionName,
5217                    packageName, userId);
5218        } finally {
5219            Binder.restoreCallingIdentity(identity);
5220        }
5221
5222        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5223                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5224                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5225
5226        if ((flags & fixedFlags) != 0) {
5227            return false;
5228        }
5229
5230        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5231    }
5232
5233    @Override
5234    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5235        mContext.enforceCallingOrSelfPermission(
5236                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5237                "addOnPermissionsChangeListener");
5238
5239        synchronized (mPackages) {
5240            mOnPermissionChangeListeners.addListenerLocked(listener);
5241        }
5242    }
5243
5244    @Override
5245    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5246        synchronized (mPackages) {
5247            mOnPermissionChangeListeners.removeListenerLocked(listener);
5248        }
5249    }
5250
5251    @Override
5252    public boolean isProtectedBroadcast(String actionName) {
5253        synchronized (mPackages) {
5254            if (mProtectedBroadcasts.contains(actionName)) {
5255                return true;
5256            } else if (actionName != null) {
5257                // TODO: remove these terrible hacks
5258                if (actionName.startsWith("android.net.netmon.lingerExpired")
5259                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5260                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5261                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5262                    return true;
5263                }
5264            }
5265        }
5266        return false;
5267    }
5268
5269    @Override
5270    public int checkSignatures(String pkg1, String pkg2) {
5271        synchronized (mPackages) {
5272            final PackageParser.Package p1 = mPackages.get(pkg1);
5273            final PackageParser.Package p2 = mPackages.get(pkg2);
5274            if (p1 == null || p1.mExtras == null
5275                    || p2 == null || p2.mExtras == null) {
5276                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5277            }
5278            return compareSignatures(p1.mSignatures, p2.mSignatures);
5279        }
5280    }
5281
5282    @Override
5283    public int checkUidSignatures(int uid1, int uid2) {
5284        // Map to base uids.
5285        uid1 = UserHandle.getAppId(uid1);
5286        uid2 = UserHandle.getAppId(uid2);
5287        // reader
5288        synchronized (mPackages) {
5289            Signature[] s1;
5290            Signature[] s2;
5291            Object obj = mSettings.getUserIdLPr(uid1);
5292            if (obj != null) {
5293                if (obj instanceof SharedUserSetting) {
5294                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5295                } else if (obj instanceof PackageSetting) {
5296                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5297                } else {
5298                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5299                }
5300            } else {
5301                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5302            }
5303            obj = mSettings.getUserIdLPr(uid2);
5304            if (obj != null) {
5305                if (obj instanceof SharedUserSetting) {
5306                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5307                } else if (obj instanceof PackageSetting) {
5308                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5309                } else {
5310                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5311                }
5312            } else {
5313                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5314            }
5315            return compareSignatures(s1, s2);
5316        }
5317    }
5318
5319    /**
5320     * This method should typically only be used when granting or revoking
5321     * permissions, since the app may immediately restart after this call.
5322     * <p>
5323     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5324     * guard your work against the app being relaunched.
5325     */
5326    private void killUid(int appId, int userId, String reason) {
5327        final long identity = Binder.clearCallingIdentity();
5328        try {
5329            IActivityManager am = ActivityManager.getService();
5330            if (am != null) {
5331                try {
5332                    am.killUid(appId, userId, reason);
5333                } catch (RemoteException e) {
5334                    /* ignore - same process */
5335                }
5336            }
5337        } finally {
5338            Binder.restoreCallingIdentity(identity);
5339        }
5340    }
5341
5342    /**
5343     * Compares two sets of signatures. Returns:
5344     * <br />
5345     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5346     * <br />
5347     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5348     * <br />
5349     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5350     * <br />
5351     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5352     * <br />
5353     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5354     */
5355    static int compareSignatures(Signature[] s1, Signature[] s2) {
5356        if (s1 == null) {
5357            return s2 == null
5358                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5359                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5360        }
5361
5362        if (s2 == null) {
5363            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5364        }
5365
5366        if (s1.length != s2.length) {
5367            return PackageManager.SIGNATURE_NO_MATCH;
5368        }
5369
5370        // Since both signature sets are of size 1, we can compare without HashSets.
5371        if (s1.length == 1) {
5372            return s1[0].equals(s2[0]) ?
5373                    PackageManager.SIGNATURE_MATCH :
5374                    PackageManager.SIGNATURE_NO_MATCH;
5375        }
5376
5377        ArraySet<Signature> set1 = new ArraySet<Signature>();
5378        for (Signature sig : s1) {
5379            set1.add(sig);
5380        }
5381        ArraySet<Signature> set2 = new ArraySet<Signature>();
5382        for (Signature sig : s2) {
5383            set2.add(sig);
5384        }
5385        // Make sure s2 contains all signatures in s1.
5386        if (set1.equals(set2)) {
5387            return PackageManager.SIGNATURE_MATCH;
5388        }
5389        return PackageManager.SIGNATURE_NO_MATCH;
5390    }
5391
5392    /**
5393     * If the database version for this type of package (internal storage or
5394     * external storage) is less than the version where package signatures
5395     * were updated, return true.
5396     */
5397    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5398        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5399        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5400    }
5401
5402    /**
5403     * Used for backward compatibility to make sure any packages with
5404     * certificate chains get upgraded to the new style. {@code existingSigs}
5405     * will be in the old format (since they were stored on disk from before the
5406     * system upgrade) and {@code scannedSigs} will be in the newer format.
5407     */
5408    private int compareSignaturesCompat(PackageSignatures existingSigs,
5409            PackageParser.Package scannedPkg) {
5410        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5411            return PackageManager.SIGNATURE_NO_MATCH;
5412        }
5413
5414        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5415        for (Signature sig : existingSigs.mSignatures) {
5416            existingSet.add(sig);
5417        }
5418        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5419        for (Signature sig : scannedPkg.mSignatures) {
5420            try {
5421                Signature[] chainSignatures = sig.getChainSignatures();
5422                for (Signature chainSig : chainSignatures) {
5423                    scannedCompatSet.add(chainSig);
5424                }
5425            } catch (CertificateEncodingException e) {
5426                scannedCompatSet.add(sig);
5427            }
5428        }
5429        /*
5430         * Make sure the expanded scanned set contains all signatures in the
5431         * existing one.
5432         */
5433        if (scannedCompatSet.equals(existingSet)) {
5434            // Migrate the old signatures to the new scheme.
5435            existingSigs.assignSignatures(scannedPkg.mSignatures);
5436            // The new KeySets will be re-added later in the scanning process.
5437            synchronized (mPackages) {
5438                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5439            }
5440            return PackageManager.SIGNATURE_MATCH;
5441        }
5442        return PackageManager.SIGNATURE_NO_MATCH;
5443    }
5444
5445    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5446        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5447        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5448    }
5449
5450    private int compareSignaturesRecover(PackageSignatures existingSigs,
5451            PackageParser.Package scannedPkg) {
5452        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5453            return PackageManager.SIGNATURE_NO_MATCH;
5454        }
5455
5456        String msg = null;
5457        try {
5458            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5459                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5460                        + scannedPkg.packageName);
5461                return PackageManager.SIGNATURE_MATCH;
5462            }
5463        } catch (CertificateException e) {
5464            msg = e.getMessage();
5465        }
5466
5467        logCriticalInfo(Log.INFO,
5468                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5469        return PackageManager.SIGNATURE_NO_MATCH;
5470    }
5471
5472    @Override
5473    public List<String> getAllPackages() {
5474        synchronized (mPackages) {
5475            return new ArrayList<String>(mPackages.keySet());
5476        }
5477    }
5478
5479    @Override
5480    public String[] getPackagesForUid(int uid) {
5481        final int userId = UserHandle.getUserId(uid);
5482        uid = UserHandle.getAppId(uid);
5483        // reader
5484        synchronized (mPackages) {
5485            Object obj = mSettings.getUserIdLPr(uid);
5486            if (obj instanceof SharedUserSetting) {
5487                final SharedUserSetting sus = (SharedUserSetting) obj;
5488                final int N = sus.packages.size();
5489                String[] res = new String[N];
5490                final Iterator<PackageSetting> it = sus.packages.iterator();
5491                int i = 0;
5492                while (it.hasNext()) {
5493                    PackageSetting ps = it.next();
5494                    if (ps.getInstalled(userId)) {
5495                        res[i++] = ps.name;
5496                    } else {
5497                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5498                    }
5499                }
5500                return res;
5501            } else if (obj instanceof PackageSetting) {
5502                final PackageSetting ps = (PackageSetting) obj;
5503                if (ps.getInstalled(userId)) {
5504                    return new String[]{ps.name};
5505                }
5506            }
5507        }
5508        return null;
5509    }
5510
5511    @Override
5512    public String getNameForUid(int uid) {
5513        // reader
5514        synchronized (mPackages) {
5515            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5516            if (obj instanceof SharedUserSetting) {
5517                final SharedUserSetting sus = (SharedUserSetting) obj;
5518                return sus.name + ":" + sus.userId;
5519            } else if (obj instanceof PackageSetting) {
5520                final PackageSetting ps = (PackageSetting) obj;
5521                return ps.name;
5522            }
5523        }
5524        return null;
5525    }
5526
5527    @Override
5528    public int getUidForSharedUser(String sharedUserName) {
5529        if(sharedUserName == null) {
5530            return -1;
5531        }
5532        // reader
5533        synchronized (mPackages) {
5534            SharedUserSetting suid;
5535            try {
5536                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5537                if (suid != null) {
5538                    return suid.userId;
5539                }
5540            } catch (PackageManagerException ignore) {
5541                // can't happen, but, still need to catch it
5542            }
5543            return -1;
5544        }
5545    }
5546
5547    @Override
5548    public int getFlagsForUid(int uid) {
5549        synchronized (mPackages) {
5550            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5551            if (obj instanceof SharedUserSetting) {
5552                final SharedUserSetting sus = (SharedUserSetting) obj;
5553                return sus.pkgFlags;
5554            } else if (obj instanceof PackageSetting) {
5555                final PackageSetting ps = (PackageSetting) obj;
5556                return ps.pkgFlags;
5557            }
5558        }
5559        return 0;
5560    }
5561
5562    @Override
5563    public int getPrivateFlagsForUid(int uid) {
5564        synchronized (mPackages) {
5565            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5566            if (obj instanceof SharedUserSetting) {
5567                final SharedUserSetting sus = (SharedUserSetting) obj;
5568                return sus.pkgPrivateFlags;
5569            } else if (obj instanceof PackageSetting) {
5570                final PackageSetting ps = (PackageSetting) obj;
5571                return ps.pkgPrivateFlags;
5572            }
5573        }
5574        return 0;
5575    }
5576
5577    @Override
5578    public boolean isUidPrivileged(int uid) {
5579        uid = UserHandle.getAppId(uid);
5580        // reader
5581        synchronized (mPackages) {
5582            Object obj = mSettings.getUserIdLPr(uid);
5583            if (obj instanceof SharedUserSetting) {
5584                final SharedUserSetting sus = (SharedUserSetting) obj;
5585                final Iterator<PackageSetting> it = sus.packages.iterator();
5586                while (it.hasNext()) {
5587                    if (it.next().isPrivileged()) {
5588                        return true;
5589                    }
5590                }
5591            } else if (obj instanceof PackageSetting) {
5592                final PackageSetting ps = (PackageSetting) obj;
5593                return ps.isPrivileged();
5594            }
5595        }
5596        return false;
5597    }
5598
5599    @Override
5600    public String[] getAppOpPermissionPackages(String permissionName) {
5601        synchronized (mPackages) {
5602            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5603            if (pkgs == null) {
5604                return null;
5605            }
5606            return pkgs.toArray(new String[pkgs.size()]);
5607        }
5608    }
5609
5610    @Override
5611    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5612            int flags, int userId) {
5613        return resolveIntentInternal(
5614                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5615    }
5616
5617    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5618            int flags, int userId, boolean includeInstantApp) {
5619        try {
5620            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5621
5622            if (!sUserManager.exists(userId)) return null;
5623            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5624            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5625                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5626
5627            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5628            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5629                    flags, userId, includeInstantApp);
5630            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5631
5632            final ResolveInfo bestChoice =
5633                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5634            return bestChoice;
5635        } finally {
5636            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5637        }
5638    }
5639
5640    @Override
5641    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5642        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5643            throw new SecurityException(
5644                    "findPersistentPreferredActivity can only be run by the system");
5645        }
5646        if (!sUserManager.exists(userId)) {
5647            return null;
5648        }
5649        intent = updateIntentForResolve(intent);
5650        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5651        final int flags = updateFlagsForResolve(0, userId, intent, false);
5652        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5653                userId);
5654        synchronized (mPackages) {
5655            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5656                    userId);
5657        }
5658    }
5659
5660    @Override
5661    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5662            IntentFilter filter, int match, ComponentName activity) {
5663        final int userId = UserHandle.getCallingUserId();
5664        if (DEBUG_PREFERRED) {
5665            Log.v(TAG, "setLastChosenActivity intent=" + intent
5666                + " resolvedType=" + resolvedType
5667                + " flags=" + flags
5668                + " filter=" + filter
5669                + " match=" + match
5670                + " activity=" + activity);
5671            filter.dump(new PrintStreamPrinter(System.out), "    ");
5672        }
5673        intent.setComponent(null);
5674        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5675                userId);
5676        // Find any earlier preferred or last chosen entries and nuke them
5677        findPreferredActivity(intent, resolvedType,
5678                flags, query, 0, false, true, false, userId);
5679        // Add the new activity as the last chosen for this filter
5680        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5681                "Setting last chosen");
5682    }
5683
5684    @Override
5685    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5686        final int userId = UserHandle.getCallingUserId();
5687        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5688        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5689                userId);
5690        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5691                false, false, false, userId);
5692    }
5693
5694    /**
5695     * Returns whether or not instant apps have been disabled remotely.
5696     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5697     * held. Otherwise we run the risk of deadlock.
5698     */
5699    private boolean isEphemeralDisabled() {
5700        // ephemeral apps have been disabled across the board
5701        if (DISABLE_EPHEMERAL_APPS) {
5702            return true;
5703        }
5704        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5705        if (!mSystemReady) {
5706            return true;
5707        }
5708        // we can't get a content resolver until the system is ready; these checks must happen last
5709        final ContentResolver resolver = mContext.getContentResolver();
5710        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5711            return true;
5712        }
5713        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5714    }
5715
5716    private boolean isEphemeralAllowed(
5717            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5718            boolean skipPackageCheck) {
5719        final int callingUser = UserHandle.getCallingUserId();
5720        if (callingUser != UserHandle.USER_SYSTEM) {
5721            return false;
5722        }
5723        if (mInstantAppResolverConnection == null) {
5724            return false;
5725        }
5726        if (mInstantAppInstallerComponent == null) {
5727            return false;
5728        }
5729        if (intent.getComponent() != null) {
5730            return false;
5731        }
5732        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5733            return false;
5734        }
5735        if (!skipPackageCheck && intent.getPackage() != null) {
5736            return false;
5737        }
5738        final boolean isWebUri = hasWebURI(intent);
5739        if (!isWebUri || intent.getData().getHost() == null) {
5740            return false;
5741        }
5742        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5743        // Or if there's already an ephemeral app installed that handles the action
5744        synchronized (mPackages) {
5745            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5746            for (int n = 0; n < count; n++) {
5747                ResolveInfo info = resolvedActivities.get(n);
5748                String packageName = info.activityInfo.packageName;
5749                PackageSetting ps = mSettings.mPackages.get(packageName);
5750                if (ps != null) {
5751                    // Try to get the status from User settings first
5752                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5753                    int status = (int) (packedStatus >> 32);
5754                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5755                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5756                        if (DEBUG_EPHEMERAL) {
5757                            Slog.v(TAG, "DENY ephemeral apps;"
5758                                + " pkg: " + packageName + ", status: " + status);
5759                        }
5760                        return false;
5761                    }
5762                    if (ps.getInstantApp(userId)) {
5763                        return false;
5764                    }
5765                }
5766            }
5767        }
5768        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5769        return true;
5770    }
5771
5772    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5773            Intent origIntent, String resolvedType, String callingPackage,
5774            int userId) {
5775        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5776                new EphemeralRequest(responseObj, origIntent, resolvedType,
5777                        callingPackage, userId));
5778        mHandler.sendMessage(msg);
5779    }
5780
5781    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5782            int flags, List<ResolveInfo> query, int userId) {
5783        if (query != null) {
5784            final int N = query.size();
5785            if (N == 1) {
5786                return query.get(0);
5787            } else if (N > 1) {
5788                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5789                // If there is more than one activity with the same priority,
5790                // then let the user decide between them.
5791                ResolveInfo r0 = query.get(0);
5792                ResolveInfo r1 = query.get(1);
5793                if (DEBUG_INTENT_MATCHING || debug) {
5794                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5795                            + r1.activityInfo.name + "=" + r1.priority);
5796                }
5797                // If the first activity has a higher priority, or a different
5798                // default, then it is always desirable to pick it.
5799                if (r0.priority != r1.priority
5800                        || r0.preferredOrder != r1.preferredOrder
5801                        || r0.isDefault != r1.isDefault) {
5802                    return query.get(0);
5803                }
5804                // If we have saved a preference for a preferred activity for
5805                // this Intent, use that.
5806                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5807                        flags, query, r0.priority, true, false, debug, userId);
5808                if (ri != null) {
5809                    return ri;
5810                }
5811                // If we have an ephemeral app, use it
5812                for (int i = 0; i < N; i++) {
5813                    ri = query.get(i);
5814                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5815                        return ri;
5816                    }
5817                }
5818                ri = new ResolveInfo(mResolveInfo);
5819                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5820                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5821                // If all of the options come from the same package, show the application's
5822                // label and icon instead of the generic resolver's.
5823                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5824                // and then throw away the ResolveInfo itself, meaning that the caller loses
5825                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5826                // a fallback for this case; we only set the target package's resources on
5827                // the ResolveInfo, not the ActivityInfo.
5828                final String intentPackage = intent.getPackage();
5829                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5830                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5831                    ri.resolvePackageName = intentPackage;
5832                    if (userNeedsBadging(userId)) {
5833                        ri.noResourceId = true;
5834                    } else {
5835                        ri.icon = appi.icon;
5836                    }
5837                    ri.iconResourceId = appi.icon;
5838                    ri.labelRes = appi.labelRes;
5839                }
5840                ri.activityInfo.applicationInfo = new ApplicationInfo(
5841                        ri.activityInfo.applicationInfo);
5842                if (userId != 0) {
5843                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5844                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5845                }
5846                // Make sure that the resolver is displayable in car mode
5847                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5848                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5849                return ri;
5850            }
5851        }
5852        return null;
5853    }
5854
5855    /**
5856     * Return true if the given list is not empty and all of its contents have
5857     * an activityInfo with the given package name.
5858     */
5859    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5860        if (ArrayUtils.isEmpty(list)) {
5861            return false;
5862        }
5863        for (int i = 0, N = list.size(); i < N; i++) {
5864            final ResolveInfo ri = list.get(i);
5865            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5866            if (ai == null || !packageName.equals(ai.packageName)) {
5867                return false;
5868            }
5869        }
5870        return true;
5871    }
5872
5873    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5874            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5875        final int N = query.size();
5876        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5877                .get(userId);
5878        // Get the list of persistent preferred activities that handle the intent
5879        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5880        List<PersistentPreferredActivity> pprefs = ppir != null
5881                ? ppir.queryIntent(intent, resolvedType,
5882                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5883                        userId)
5884                : null;
5885        if (pprefs != null && pprefs.size() > 0) {
5886            final int M = pprefs.size();
5887            for (int i=0; i<M; i++) {
5888                final PersistentPreferredActivity ppa = pprefs.get(i);
5889                if (DEBUG_PREFERRED || debug) {
5890                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5891                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5892                            + "\n  component=" + ppa.mComponent);
5893                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5894                }
5895                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5896                        flags | MATCH_DISABLED_COMPONENTS, userId);
5897                if (DEBUG_PREFERRED || debug) {
5898                    Slog.v(TAG, "Found persistent preferred activity:");
5899                    if (ai != null) {
5900                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5901                    } else {
5902                        Slog.v(TAG, "  null");
5903                    }
5904                }
5905                if (ai == null) {
5906                    // This previously registered persistent preferred activity
5907                    // component is no longer known. Ignore it and do NOT remove it.
5908                    continue;
5909                }
5910                for (int j=0; j<N; j++) {
5911                    final ResolveInfo ri = query.get(j);
5912                    if (!ri.activityInfo.applicationInfo.packageName
5913                            .equals(ai.applicationInfo.packageName)) {
5914                        continue;
5915                    }
5916                    if (!ri.activityInfo.name.equals(ai.name)) {
5917                        continue;
5918                    }
5919                    //  Found a persistent preference that can handle the intent.
5920                    if (DEBUG_PREFERRED || debug) {
5921                        Slog.v(TAG, "Returning persistent preferred activity: " +
5922                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5923                    }
5924                    return ri;
5925                }
5926            }
5927        }
5928        return null;
5929    }
5930
5931    // TODO: handle preferred activities missing while user has amnesia
5932    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5933            List<ResolveInfo> query, int priority, boolean always,
5934            boolean removeMatches, boolean debug, int userId) {
5935        if (!sUserManager.exists(userId)) return null;
5936        flags = updateFlagsForResolve(flags, userId, intent, false);
5937        intent = updateIntentForResolve(intent);
5938        // writer
5939        synchronized (mPackages) {
5940            // Try to find a matching persistent preferred activity.
5941            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5942                    debug, userId);
5943
5944            // If a persistent preferred activity matched, use it.
5945            if (pri != null) {
5946                return pri;
5947            }
5948
5949            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5950            // Get the list of preferred activities that handle the intent
5951            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5952            List<PreferredActivity> prefs = pir != null
5953                    ? pir.queryIntent(intent, resolvedType,
5954                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5955                            userId)
5956                    : null;
5957            if (prefs != null && prefs.size() > 0) {
5958                boolean changed = false;
5959                try {
5960                    // First figure out how good the original match set is.
5961                    // We will only allow preferred activities that came
5962                    // from the same match quality.
5963                    int match = 0;
5964
5965                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5966
5967                    final int N = query.size();
5968                    for (int j=0; j<N; j++) {
5969                        final ResolveInfo ri = query.get(j);
5970                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5971                                + ": 0x" + Integer.toHexString(match));
5972                        if (ri.match > match) {
5973                            match = ri.match;
5974                        }
5975                    }
5976
5977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5978                            + Integer.toHexString(match));
5979
5980                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5981                    final int M = prefs.size();
5982                    for (int i=0; i<M; i++) {
5983                        final PreferredActivity pa = prefs.get(i);
5984                        if (DEBUG_PREFERRED || debug) {
5985                            Slog.v(TAG, "Checking PreferredActivity ds="
5986                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5987                                    + "\n  component=" + pa.mPref.mComponent);
5988                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5989                        }
5990                        if (pa.mPref.mMatch != match) {
5991                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5992                                    + Integer.toHexString(pa.mPref.mMatch));
5993                            continue;
5994                        }
5995                        // If it's not an "always" type preferred activity and that's what we're
5996                        // looking for, skip it.
5997                        if (always && !pa.mPref.mAlways) {
5998                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5999                            continue;
6000                        }
6001                        final ActivityInfo ai = getActivityInfo(
6002                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6003                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6004                                userId);
6005                        if (DEBUG_PREFERRED || debug) {
6006                            Slog.v(TAG, "Found preferred activity:");
6007                            if (ai != null) {
6008                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6009                            } else {
6010                                Slog.v(TAG, "  null");
6011                            }
6012                        }
6013                        if (ai == null) {
6014                            // This previously registered preferred activity
6015                            // component is no longer known.  Most likely an update
6016                            // to the app was installed and in the new version this
6017                            // component no longer exists.  Clean it up by removing
6018                            // it from the preferred activities list, and skip it.
6019                            Slog.w(TAG, "Removing dangling preferred activity: "
6020                                    + pa.mPref.mComponent);
6021                            pir.removeFilter(pa);
6022                            changed = true;
6023                            continue;
6024                        }
6025                        for (int j=0; j<N; j++) {
6026                            final ResolveInfo ri = query.get(j);
6027                            if (!ri.activityInfo.applicationInfo.packageName
6028                                    .equals(ai.applicationInfo.packageName)) {
6029                                continue;
6030                            }
6031                            if (!ri.activityInfo.name.equals(ai.name)) {
6032                                continue;
6033                            }
6034
6035                            if (removeMatches) {
6036                                pir.removeFilter(pa);
6037                                changed = true;
6038                                if (DEBUG_PREFERRED) {
6039                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6040                                }
6041                                break;
6042                            }
6043
6044                            // Okay we found a previously set preferred or last chosen app.
6045                            // If the result set is different from when this
6046                            // was created, we need to clear it and re-ask the
6047                            // user their preference, if we're looking for an "always" type entry.
6048                            if (always && !pa.mPref.sameSet(query)) {
6049                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6050                                        + intent + " type " + resolvedType);
6051                                if (DEBUG_PREFERRED) {
6052                                    Slog.v(TAG, "Removing preferred activity since set changed "
6053                                            + pa.mPref.mComponent);
6054                                }
6055                                pir.removeFilter(pa);
6056                                // Re-add the filter as a "last chosen" entry (!always)
6057                                PreferredActivity lastChosen = new PreferredActivity(
6058                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6059                                pir.addFilter(lastChosen);
6060                                changed = true;
6061                                return null;
6062                            }
6063
6064                            // Yay! Either the set matched or we're looking for the last chosen
6065                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6066                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6067                            return ri;
6068                        }
6069                    }
6070                } finally {
6071                    if (changed) {
6072                        if (DEBUG_PREFERRED) {
6073                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6074                        }
6075                        scheduleWritePackageRestrictionsLocked(userId);
6076                    }
6077                }
6078            }
6079        }
6080        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6081        return null;
6082    }
6083
6084    /*
6085     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6086     */
6087    @Override
6088    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6089            int targetUserId) {
6090        mContext.enforceCallingOrSelfPermission(
6091                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6092        List<CrossProfileIntentFilter> matches =
6093                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6094        if (matches != null) {
6095            int size = matches.size();
6096            for (int i = 0; i < size; i++) {
6097                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6098            }
6099        }
6100        if (hasWebURI(intent)) {
6101            // cross-profile app linking works only towards the parent.
6102            final UserInfo parent = getProfileParent(sourceUserId);
6103            synchronized(mPackages) {
6104                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6105                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6106                        intent, resolvedType, flags, sourceUserId, parent.id);
6107                return xpDomainInfo != null;
6108            }
6109        }
6110        return false;
6111    }
6112
6113    private UserInfo getProfileParent(int userId) {
6114        final long identity = Binder.clearCallingIdentity();
6115        try {
6116            return sUserManager.getProfileParent(userId);
6117        } finally {
6118            Binder.restoreCallingIdentity(identity);
6119        }
6120    }
6121
6122    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6123            String resolvedType, int userId) {
6124        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6125        if (resolver != null) {
6126            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6127        }
6128        return null;
6129    }
6130
6131    @Override
6132    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6133            String resolvedType, int flags, int userId) {
6134        try {
6135            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6136
6137            return new ParceledListSlice<>(
6138                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6139        } finally {
6140            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6141        }
6142    }
6143
6144    /**
6145     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6146     * instant, returns {@code null}.
6147     */
6148    private String getInstantAppPackageName(int callingUid) {
6149        final int appId = UserHandle.getAppId(callingUid);
6150        synchronized (mPackages) {
6151            final Object obj = mSettings.getUserIdLPr(appId);
6152            if (obj instanceof PackageSetting) {
6153                final PackageSetting ps = (PackageSetting) obj;
6154                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6155                return isInstantApp ? ps.pkg.packageName : null;
6156            }
6157        }
6158        return null;
6159    }
6160
6161    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6162            String resolvedType, int flags, int userId) {
6163        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6164    }
6165
6166    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6167            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6168        if (!sUserManager.exists(userId)) return Collections.emptyList();
6169        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6170        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6171        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6172                false /* requireFullPermission */, false /* checkShell */,
6173                "query intent activities");
6174        ComponentName comp = intent.getComponent();
6175        if (comp == null) {
6176            if (intent.getSelector() != null) {
6177                intent = intent.getSelector();
6178                comp = intent.getComponent();
6179            }
6180        }
6181
6182        if (comp != null) {
6183            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6184            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6185            if (ai != null) {
6186                // When specifying an explicit component, we prevent the activity from being
6187                // used when either 1) the calling package is normal and the activity is within
6188                // an ephemeral application or 2) the calling package is ephemeral and the
6189                // activity is not visible to ephemeral applications.
6190                final boolean matchInstantApp =
6191                        (flags & PackageManager.MATCH_INSTANT) != 0;
6192                final boolean matchVisibleToInstantAppOnly =
6193                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6194                final boolean isCallerInstantApp =
6195                        instantAppPkgName != null;
6196                final boolean isTargetSameInstantApp =
6197                        comp.getPackageName().equals(instantAppPkgName);
6198                final boolean isTargetInstantApp =
6199                        (ai.applicationInfo.privateFlags
6200                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6201                final boolean isTargetHiddenFromInstantApp =
6202                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6203                final boolean blockResolution =
6204                        !isTargetSameInstantApp
6205                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6206                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6207                                        && isTargetHiddenFromInstantApp));
6208                if (!blockResolution) {
6209                    final ResolveInfo ri = new ResolveInfo();
6210                    ri.activityInfo = ai;
6211                    list.add(ri);
6212                }
6213            }
6214            return applyPostResolutionFilter(list, instantAppPkgName);
6215        }
6216
6217        // reader
6218        boolean sortResult = false;
6219        boolean addEphemeral = false;
6220        List<ResolveInfo> result;
6221        final String pkgName = intent.getPackage();
6222        final boolean ephemeralDisabled = isEphemeralDisabled();
6223        synchronized (mPackages) {
6224            if (pkgName == null) {
6225                List<CrossProfileIntentFilter> matchingFilters =
6226                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6227                // Check for results that need to skip the current profile.
6228                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6229                        resolvedType, flags, userId);
6230                if (xpResolveInfo != null) {
6231                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6232                    xpResult.add(xpResolveInfo);
6233                    return applyPostResolutionFilter(
6234                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6235                }
6236
6237                // Check for results in the current profile.
6238                result = filterIfNotSystemUser(mActivities.queryIntent(
6239                        intent, resolvedType, flags, userId), userId);
6240                addEphemeral = !ephemeralDisabled
6241                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6242
6243                // Check for cross profile results.
6244                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6245                xpResolveInfo = queryCrossProfileIntents(
6246                        matchingFilters, intent, resolvedType, flags, userId,
6247                        hasNonNegativePriorityResult);
6248                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6249                    boolean isVisibleToUser = filterIfNotSystemUser(
6250                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6251                    if (isVisibleToUser) {
6252                        result.add(xpResolveInfo);
6253                        sortResult = true;
6254                    }
6255                }
6256                if (hasWebURI(intent)) {
6257                    CrossProfileDomainInfo xpDomainInfo = null;
6258                    final UserInfo parent = getProfileParent(userId);
6259                    if (parent != null) {
6260                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6261                                flags, userId, parent.id);
6262                    }
6263                    if (xpDomainInfo != null) {
6264                        if (xpResolveInfo != null) {
6265                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6266                            // in the result.
6267                            result.remove(xpResolveInfo);
6268                        }
6269                        if (result.size() == 0 && !addEphemeral) {
6270                            // No result in current profile, but found candidate in parent user.
6271                            // And we are not going to add emphemeral app, so we can return the
6272                            // result straight away.
6273                            result.add(xpDomainInfo.resolveInfo);
6274                            return applyPostResolutionFilter(result, instantAppPkgName);
6275                        }
6276                    } else if (result.size() <= 1 && !addEphemeral) {
6277                        // No result in parent user and <= 1 result in current profile, and we
6278                        // are not going to add emphemeral app, so we can return the result without
6279                        // further processing.
6280                        return applyPostResolutionFilter(result, instantAppPkgName);
6281                    }
6282                    // We have more than one candidate (combining results from current and parent
6283                    // profile), so we need filtering and sorting.
6284                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6285                            intent, flags, result, xpDomainInfo, userId);
6286                    sortResult = true;
6287                }
6288            } else {
6289                final PackageParser.Package pkg = mPackages.get(pkgName);
6290                if (pkg != null) {
6291                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6292                            mActivities.queryIntentForPackage(
6293                                    intent, resolvedType, flags, pkg.activities, userId),
6294                            userId), instantAppPkgName);
6295                } else {
6296                    // the caller wants to resolve for a particular package; however, there
6297                    // were no installed results, so, try to find an ephemeral result
6298                    addEphemeral =  !ephemeralDisabled
6299                            && isEphemeralAllowed(
6300                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6301                    result = new ArrayList<ResolveInfo>();
6302                }
6303            }
6304        }
6305        if (addEphemeral) {
6306            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6307            final EphemeralRequest requestObject = new EphemeralRequest(
6308                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6309                    null /*callingPackage*/, userId);
6310            final AuxiliaryResolveInfo auxiliaryResponse =
6311                    EphemeralResolver.doEphemeralResolutionPhaseOne(
6312                            mContext, mInstantAppResolverConnection, requestObject);
6313            if (auxiliaryResponse != null) {
6314                if (DEBUG_EPHEMERAL) {
6315                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6316                }
6317                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6318                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6319                // make sure this resolver is the default
6320                ephemeralInstaller.isDefault = true;
6321                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6322                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6323                // add a non-generic filter
6324                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6325                ephemeralInstaller.filter.addDataPath(
6326                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6327                ephemeralInstaller.instantAppAvailable = true;
6328                result.add(ephemeralInstaller);
6329            }
6330            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6331        }
6332        if (sortResult) {
6333            Collections.sort(result, mResolvePrioritySorter);
6334        }
6335        return applyPostResolutionFilter(result, instantAppPkgName);
6336    }
6337
6338    private static class CrossProfileDomainInfo {
6339        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6340        ResolveInfo resolveInfo;
6341        /* Best domain verification status of the activities found in the other profile */
6342        int bestDomainVerificationStatus;
6343    }
6344
6345    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6346            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6347        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6348                sourceUserId)) {
6349            return null;
6350        }
6351        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6352                resolvedType, flags, parentUserId);
6353
6354        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6355            return null;
6356        }
6357        CrossProfileDomainInfo result = null;
6358        int size = resultTargetUser.size();
6359        for (int i = 0; i < size; i++) {
6360            ResolveInfo riTargetUser = resultTargetUser.get(i);
6361            // Intent filter verification is only for filters that specify a host. So don't return
6362            // those that handle all web uris.
6363            if (riTargetUser.handleAllWebDataURI) {
6364                continue;
6365            }
6366            String packageName = riTargetUser.activityInfo.packageName;
6367            PackageSetting ps = mSettings.mPackages.get(packageName);
6368            if (ps == null) {
6369                continue;
6370            }
6371            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6372            int status = (int)(verificationState >> 32);
6373            if (result == null) {
6374                result = new CrossProfileDomainInfo();
6375                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6376                        sourceUserId, parentUserId);
6377                result.bestDomainVerificationStatus = status;
6378            } else {
6379                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6380                        result.bestDomainVerificationStatus);
6381            }
6382        }
6383        // Don't consider matches with status NEVER across profiles.
6384        if (result != null && result.bestDomainVerificationStatus
6385                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6386            return null;
6387        }
6388        return result;
6389    }
6390
6391    /**
6392     * Verification statuses are ordered from the worse to the best, except for
6393     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6394     */
6395    private int bestDomainVerificationStatus(int status1, int status2) {
6396        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6397            return status2;
6398        }
6399        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6400            return status1;
6401        }
6402        return (int) MathUtils.max(status1, status2);
6403    }
6404
6405    private boolean isUserEnabled(int userId) {
6406        long callingId = Binder.clearCallingIdentity();
6407        try {
6408            UserInfo userInfo = sUserManager.getUserInfo(userId);
6409            return userInfo != null && userInfo.isEnabled();
6410        } finally {
6411            Binder.restoreCallingIdentity(callingId);
6412        }
6413    }
6414
6415    /**
6416     * Filter out activities with systemUserOnly flag set, when current user is not System.
6417     *
6418     * @return filtered list
6419     */
6420    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6421        if (userId == UserHandle.USER_SYSTEM) {
6422            return resolveInfos;
6423        }
6424        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6425            ResolveInfo info = resolveInfos.get(i);
6426            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6427                resolveInfos.remove(i);
6428            }
6429        }
6430        return resolveInfos;
6431    }
6432
6433    /**
6434     * Filters out ephemeral activities.
6435     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6436     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6437     *
6438     * @param resolveInfos The pre-filtered list of resolved activities
6439     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6440     *          is performed.
6441     * @return A filtered list of resolved activities.
6442     */
6443    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6444            String ephemeralPkgName) {
6445        // TODO: When adding on-demand split support for non-instant apps, remove this check
6446        // and always apply post filtering
6447        if (ephemeralPkgName == null) {
6448            return resolveInfos;
6449        }
6450        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6451            final ResolveInfo info = resolveInfos.get(i);
6452            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6453            // allow activities that are defined in the provided package
6454            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6455                if (info.activityInfo.splitName != null
6456                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6457                                info.activityInfo.splitName)) {
6458                    // requested activity is defined in a split that hasn't been installed yet.
6459                    // add the installer to the resolve list
6460                    if (DEBUG_EPHEMERAL) {
6461                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6462                    }
6463                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6464                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6465                            info.activityInfo.packageName, info.activityInfo.splitName,
6466                            info.activityInfo.applicationInfo.versionCode);
6467                    // make sure this resolver is the default
6468                    installerInfo.isDefault = true;
6469                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6470                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6471                    // add a non-generic filter
6472                    installerInfo.filter = new IntentFilter();
6473                    // load resources from the correct package
6474                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6475                    resolveInfos.set(i, installerInfo);
6476                }
6477                continue;
6478            }
6479            // allow activities that have been explicitly exposed to ephemeral apps
6480            if (!isEphemeralApp
6481                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6482                continue;
6483            }
6484            resolveInfos.remove(i);
6485        }
6486        return resolveInfos;
6487    }
6488
6489    /**
6490     * @param resolveInfos list of resolve infos in descending priority order
6491     * @return if the list contains a resolve info with non-negative priority
6492     */
6493    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6494        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6495    }
6496
6497    private static boolean hasWebURI(Intent intent) {
6498        if (intent.getData() == null) {
6499            return false;
6500        }
6501        final String scheme = intent.getScheme();
6502        if (TextUtils.isEmpty(scheme)) {
6503            return false;
6504        }
6505        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6506    }
6507
6508    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6509            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6510            int userId) {
6511        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6512
6513        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6514            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6515                    candidates.size());
6516        }
6517
6518        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6519        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6520        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6521        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6522        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6523        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6524
6525        synchronized (mPackages) {
6526            final int count = candidates.size();
6527            // First, try to use linked apps. Partition the candidates into four lists:
6528            // one for the final results, one for the "do not use ever", one for "undefined status"
6529            // and finally one for "browser app type".
6530            for (int n=0; n<count; n++) {
6531                ResolveInfo info = candidates.get(n);
6532                String packageName = info.activityInfo.packageName;
6533                PackageSetting ps = mSettings.mPackages.get(packageName);
6534                if (ps != null) {
6535                    // Add to the special match all list (Browser use case)
6536                    if (info.handleAllWebDataURI) {
6537                        matchAllList.add(info);
6538                        continue;
6539                    }
6540                    // Try to get the status from User settings first
6541                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6542                    int status = (int)(packedStatus >> 32);
6543                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6544                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6545                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6546                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6547                                    + " : linkgen=" + linkGeneration);
6548                        }
6549                        // Use link-enabled generation as preferredOrder, i.e.
6550                        // prefer newly-enabled over earlier-enabled.
6551                        info.preferredOrder = linkGeneration;
6552                        alwaysList.add(info);
6553                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6554                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6555                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6556                        }
6557                        neverList.add(info);
6558                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6559                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6560                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6561                        }
6562                        alwaysAskList.add(info);
6563                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6564                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6565                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6566                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6567                        }
6568                        undefinedList.add(info);
6569                    }
6570                }
6571            }
6572
6573            // We'll want to include browser possibilities in a few cases
6574            boolean includeBrowser = false;
6575
6576            // First try to add the "always" resolution(s) for the current user, if any
6577            if (alwaysList.size() > 0) {
6578                result.addAll(alwaysList);
6579            } else {
6580                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6581                result.addAll(undefinedList);
6582                // Maybe add one for the other profile.
6583                if (xpDomainInfo != null && (
6584                        xpDomainInfo.bestDomainVerificationStatus
6585                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6586                    result.add(xpDomainInfo.resolveInfo);
6587                }
6588                includeBrowser = true;
6589            }
6590
6591            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6592            // If there were 'always' entries their preferred order has been set, so we also
6593            // back that off to make the alternatives equivalent
6594            if (alwaysAskList.size() > 0) {
6595                for (ResolveInfo i : result) {
6596                    i.preferredOrder = 0;
6597                }
6598                result.addAll(alwaysAskList);
6599                includeBrowser = true;
6600            }
6601
6602            if (includeBrowser) {
6603                // Also add browsers (all of them or only the default one)
6604                if (DEBUG_DOMAIN_VERIFICATION) {
6605                    Slog.v(TAG, "   ...including browsers in candidate set");
6606                }
6607                if ((matchFlags & MATCH_ALL) != 0) {
6608                    result.addAll(matchAllList);
6609                } else {
6610                    // Browser/generic handling case.  If there's a default browser, go straight
6611                    // to that (but only if there is no other higher-priority match).
6612                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6613                    int maxMatchPrio = 0;
6614                    ResolveInfo defaultBrowserMatch = null;
6615                    final int numCandidates = matchAllList.size();
6616                    for (int n = 0; n < numCandidates; n++) {
6617                        ResolveInfo info = matchAllList.get(n);
6618                        // track the highest overall match priority...
6619                        if (info.priority > maxMatchPrio) {
6620                            maxMatchPrio = info.priority;
6621                        }
6622                        // ...and the highest-priority default browser match
6623                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6624                            if (defaultBrowserMatch == null
6625                                    || (defaultBrowserMatch.priority < info.priority)) {
6626                                if (debug) {
6627                                    Slog.v(TAG, "Considering default browser match " + info);
6628                                }
6629                                defaultBrowserMatch = info;
6630                            }
6631                        }
6632                    }
6633                    if (defaultBrowserMatch != null
6634                            && defaultBrowserMatch.priority >= maxMatchPrio
6635                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6636                    {
6637                        if (debug) {
6638                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6639                        }
6640                        result.add(defaultBrowserMatch);
6641                    } else {
6642                        result.addAll(matchAllList);
6643                    }
6644                }
6645
6646                // If there is nothing selected, add all candidates and remove the ones that the user
6647                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6648                if (result.size() == 0) {
6649                    result.addAll(candidates);
6650                    result.removeAll(neverList);
6651                }
6652            }
6653        }
6654        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6655            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6656                    result.size());
6657            for (ResolveInfo info : result) {
6658                Slog.v(TAG, "  + " + info.activityInfo);
6659            }
6660        }
6661        return result;
6662    }
6663
6664    // Returns a packed value as a long:
6665    //
6666    // high 'int'-sized word: link status: undefined/ask/never/always.
6667    // low 'int'-sized word: relative priority among 'always' results.
6668    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6669        long result = ps.getDomainVerificationStatusForUser(userId);
6670        // if none available, get the master status
6671        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6672            if (ps.getIntentFilterVerificationInfo() != null) {
6673                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6674            }
6675        }
6676        return result;
6677    }
6678
6679    private ResolveInfo querySkipCurrentProfileIntents(
6680            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6681            int flags, int sourceUserId) {
6682        if (matchingFilters != null) {
6683            int size = matchingFilters.size();
6684            for (int i = 0; i < size; i ++) {
6685                CrossProfileIntentFilter filter = matchingFilters.get(i);
6686                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6687                    // Checking if there are activities in the target user that can handle the
6688                    // intent.
6689                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6690                            resolvedType, flags, sourceUserId);
6691                    if (resolveInfo != null) {
6692                        return resolveInfo;
6693                    }
6694                }
6695            }
6696        }
6697        return null;
6698    }
6699
6700    // Return matching ResolveInfo in target user if any.
6701    private ResolveInfo queryCrossProfileIntents(
6702            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6703            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6704        if (matchingFilters != null) {
6705            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6706            // match the same intent. For performance reasons, it is better not to
6707            // run queryIntent twice for the same userId
6708            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6709            int size = matchingFilters.size();
6710            for (int i = 0; i < size; i++) {
6711                CrossProfileIntentFilter filter = matchingFilters.get(i);
6712                int targetUserId = filter.getTargetUserId();
6713                boolean skipCurrentProfile =
6714                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6715                boolean skipCurrentProfileIfNoMatchFound =
6716                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6717                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6718                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6719                    // Checking if there are activities in the target user that can handle the
6720                    // intent.
6721                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6722                            resolvedType, flags, sourceUserId);
6723                    if (resolveInfo != null) return resolveInfo;
6724                    alreadyTriedUserIds.put(targetUserId, true);
6725                }
6726            }
6727        }
6728        return null;
6729    }
6730
6731    /**
6732     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6733     * will forward the intent to the filter's target user.
6734     * Otherwise, returns null.
6735     */
6736    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6737            String resolvedType, int flags, int sourceUserId) {
6738        int targetUserId = filter.getTargetUserId();
6739        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6740                resolvedType, flags, targetUserId);
6741        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6742            // If all the matches in the target profile are suspended, return null.
6743            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6744                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6745                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6746                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6747                            targetUserId);
6748                }
6749            }
6750        }
6751        return null;
6752    }
6753
6754    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6755            int sourceUserId, int targetUserId) {
6756        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6757        long ident = Binder.clearCallingIdentity();
6758        boolean targetIsProfile;
6759        try {
6760            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6761        } finally {
6762            Binder.restoreCallingIdentity(ident);
6763        }
6764        String className;
6765        if (targetIsProfile) {
6766            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6767        } else {
6768            className = FORWARD_INTENT_TO_PARENT;
6769        }
6770        ComponentName forwardingActivityComponentName = new ComponentName(
6771                mAndroidApplication.packageName, className);
6772        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6773                sourceUserId);
6774        if (!targetIsProfile) {
6775            forwardingActivityInfo.showUserIcon = targetUserId;
6776            forwardingResolveInfo.noResourceId = true;
6777        }
6778        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6779        forwardingResolveInfo.priority = 0;
6780        forwardingResolveInfo.preferredOrder = 0;
6781        forwardingResolveInfo.match = 0;
6782        forwardingResolveInfo.isDefault = true;
6783        forwardingResolveInfo.filter = filter;
6784        forwardingResolveInfo.targetUserId = targetUserId;
6785        return forwardingResolveInfo;
6786    }
6787
6788    @Override
6789    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6790            Intent[] specifics, String[] specificTypes, Intent intent,
6791            String resolvedType, int flags, int userId) {
6792        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6793                specificTypes, intent, resolvedType, flags, userId));
6794    }
6795
6796    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6797            Intent[] specifics, String[] specificTypes, Intent intent,
6798            String resolvedType, int flags, int userId) {
6799        if (!sUserManager.exists(userId)) return Collections.emptyList();
6800        flags = updateFlagsForResolve(flags, userId, intent, false);
6801        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6802                false /* requireFullPermission */, false /* checkShell */,
6803                "query intent activity options");
6804        final String resultsAction = intent.getAction();
6805
6806        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6807                | PackageManager.GET_RESOLVED_FILTER, userId);
6808
6809        if (DEBUG_INTENT_MATCHING) {
6810            Log.v(TAG, "Query " + intent + ": " + results);
6811        }
6812
6813        int specificsPos = 0;
6814        int N;
6815
6816        // todo: note that the algorithm used here is O(N^2).  This
6817        // isn't a problem in our current environment, but if we start running
6818        // into situations where we have more than 5 or 10 matches then this
6819        // should probably be changed to something smarter...
6820
6821        // First we go through and resolve each of the specific items
6822        // that were supplied, taking care of removing any corresponding
6823        // duplicate items in the generic resolve list.
6824        if (specifics != null) {
6825            for (int i=0; i<specifics.length; i++) {
6826                final Intent sintent = specifics[i];
6827                if (sintent == null) {
6828                    continue;
6829                }
6830
6831                if (DEBUG_INTENT_MATCHING) {
6832                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6833                }
6834
6835                String action = sintent.getAction();
6836                if (resultsAction != null && resultsAction.equals(action)) {
6837                    // If this action was explicitly requested, then don't
6838                    // remove things that have it.
6839                    action = null;
6840                }
6841
6842                ResolveInfo ri = null;
6843                ActivityInfo ai = null;
6844
6845                ComponentName comp = sintent.getComponent();
6846                if (comp == null) {
6847                    ri = resolveIntent(
6848                        sintent,
6849                        specificTypes != null ? specificTypes[i] : null,
6850                            flags, userId);
6851                    if (ri == null) {
6852                        continue;
6853                    }
6854                    if (ri == mResolveInfo) {
6855                        // ACK!  Must do something better with this.
6856                    }
6857                    ai = ri.activityInfo;
6858                    comp = new ComponentName(ai.applicationInfo.packageName,
6859                            ai.name);
6860                } else {
6861                    ai = getActivityInfo(comp, flags, userId);
6862                    if (ai == null) {
6863                        continue;
6864                    }
6865                }
6866
6867                // Look for any generic query activities that are duplicates
6868                // of this specific one, and remove them from the results.
6869                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6870                N = results.size();
6871                int j;
6872                for (j=specificsPos; j<N; j++) {
6873                    ResolveInfo sri = results.get(j);
6874                    if ((sri.activityInfo.name.equals(comp.getClassName())
6875                            && sri.activityInfo.applicationInfo.packageName.equals(
6876                                    comp.getPackageName()))
6877                        || (action != null && sri.filter.matchAction(action))) {
6878                        results.remove(j);
6879                        if (DEBUG_INTENT_MATCHING) Log.v(
6880                            TAG, "Removing duplicate item from " + j
6881                            + " due to specific " + specificsPos);
6882                        if (ri == null) {
6883                            ri = sri;
6884                        }
6885                        j--;
6886                        N--;
6887                    }
6888                }
6889
6890                // Add this specific item to its proper place.
6891                if (ri == null) {
6892                    ri = new ResolveInfo();
6893                    ri.activityInfo = ai;
6894                }
6895                results.add(specificsPos, ri);
6896                ri.specificIndex = i;
6897                specificsPos++;
6898            }
6899        }
6900
6901        // Now we go through the remaining generic results and remove any
6902        // duplicate actions that are found here.
6903        N = results.size();
6904        for (int i=specificsPos; i<N-1; i++) {
6905            final ResolveInfo rii = results.get(i);
6906            if (rii.filter == null) {
6907                continue;
6908            }
6909
6910            // Iterate over all of the actions of this result's intent
6911            // filter...  typically this should be just one.
6912            final Iterator<String> it = rii.filter.actionsIterator();
6913            if (it == null) {
6914                continue;
6915            }
6916            while (it.hasNext()) {
6917                final String action = it.next();
6918                if (resultsAction != null && resultsAction.equals(action)) {
6919                    // If this action was explicitly requested, then don't
6920                    // remove things that have it.
6921                    continue;
6922                }
6923                for (int j=i+1; j<N; j++) {
6924                    final ResolveInfo rij = results.get(j);
6925                    if (rij.filter != null && rij.filter.hasAction(action)) {
6926                        results.remove(j);
6927                        if (DEBUG_INTENT_MATCHING) Log.v(
6928                            TAG, "Removing duplicate item from " + j
6929                            + " due to action " + action + " at " + i);
6930                        j--;
6931                        N--;
6932                    }
6933                }
6934            }
6935
6936            // If the caller didn't request filter information, drop it now
6937            // so we don't have to marshall/unmarshall it.
6938            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6939                rii.filter = null;
6940            }
6941        }
6942
6943        // Filter out the caller activity if so requested.
6944        if (caller != null) {
6945            N = results.size();
6946            for (int i=0; i<N; i++) {
6947                ActivityInfo ainfo = results.get(i).activityInfo;
6948                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6949                        && caller.getClassName().equals(ainfo.name)) {
6950                    results.remove(i);
6951                    break;
6952                }
6953            }
6954        }
6955
6956        // If the caller didn't request filter information,
6957        // drop them now so we don't have to
6958        // marshall/unmarshall it.
6959        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6960            N = results.size();
6961            for (int i=0; i<N; i++) {
6962                results.get(i).filter = null;
6963            }
6964        }
6965
6966        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6967        return results;
6968    }
6969
6970    @Override
6971    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6972            String resolvedType, int flags, int userId) {
6973        return new ParceledListSlice<>(
6974                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6975    }
6976
6977    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6978            String resolvedType, int flags, int userId) {
6979        if (!sUserManager.exists(userId)) return Collections.emptyList();
6980        flags = updateFlagsForResolve(flags, userId, intent, false);
6981        ComponentName comp = intent.getComponent();
6982        if (comp == null) {
6983            if (intent.getSelector() != null) {
6984                intent = intent.getSelector();
6985                comp = intent.getComponent();
6986            }
6987        }
6988        if (comp != null) {
6989            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6990            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6991            if (ai != null) {
6992                ResolveInfo ri = new ResolveInfo();
6993                ri.activityInfo = ai;
6994                list.add(ri);
6995            }
6996            return list;
6997        }
6998
6999        // reader
7000        synchronized (mPackages) {
7001            String pkgName = intent.getPackage();
7002            if (pkgName == null) {
7003                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7004            }
7005            final PackageParser.Package pkg = mPackages.get(pkgName);
7006            if (pkg != null) {
7007                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7008                        userId);
7009            }
7010            return Collections.emptyList();
7011        }
7012    }
7013
7014    @Override
7015    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7016        if (!sUserManager.exists(userId)) return null;
7017        flags = updateFlagsForResolve(flags, userId, intent, false);
7018        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7019        if (query != null) {
7020            if (query.size() >= 1) {
7021                // If there is more than one service with the same priority,
7022                // just arbitrarily pick the first one.
7023                return query.get(0);
7024            }
7025        }
7026        return null;
7027    }
7028
7029    @Override
7030    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7031            String resolvedType, int flags, int userId) {
7032        return new ParceledListSlice<>(
7033                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7034    }
7035
7036    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7037            String resolvedType, int flags, int userId) {
7038        if (!sUserManager.exists(userId)) return Collections.emptyList();
7039        flags = updateFlagsForResolve(flags, userId, intent, false);
7040        ComponentName comp = intent.getComponent();
7041        if (comp == null) {
7042            if (intent.getSelector() != null) {
7043                intent = intent.getSelector();
7044                comp = intent.getComponent();
7045            }
7046        }
7047        if (comp != null) {
7048            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7049            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7050            if (si != null) {
7051                final ResolveInfo ri = new ResolveInfo();
7052                ri.serviceInfo = si;
7053                list.add(ri);
7054            }
7055            return list;
7056        }
7057
7058        // reader
7059        synchronized (mPackages) {
7060            String pkgName = intent.getPackage();
7061            if (pkgName == null) {
7062                return mServices.queryIntent(intent, resolvedType, flags, userId);
7063            }
7064            final PackageParser.Package pkg = mPackages.get(pkgName);
7065            if (pkg != null) {
7066                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7067                        userId);
7068            }
7069            return Collections.emptyList();
7070        }
7071    }
7072
7073    @Override
7074    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7075            String resolvedType, int flags, int userId) {
7076        return new ParceledListSlice<>(
7077                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7078    }
7079
7080    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7081            Intent intent, String resolvedType, int flags, int userId) {
7082        if (!sUserManager.exists(userId)) return Collections.emptyList();
7083        flags = updateFlagsForResolve(flags, userId, intent, false);
7084        ComponentName comp = intent.getComponent();
7085        if (comp == null) {
7086            if (intent.getSelector() != null) {
7087                intent = intent.getSelector();
7088                comp = intent.getComponent();
7089            }
7090        }
7091        if (comp != null) {
7092            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7093            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7094            if (pi != null) {
7095                final ResolveInfo ri = new ResolveInfo();
7096                ri.providerInfo = pi;
7097                list.add(ri);
7098            }
7099            return list;
7100        }
7101
7102        // reader
7103        synchronized (mPackages) {
7104            String pkgName = intent.getPackage();
7105            if (pkgName == null) {
7106                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7107            }
7108            final PackageParser.Package pkg = mPackages.get(pkgName);
7109            if (pkg != null) {
7110                return mProviders.queryIntentForPackage(
7111                        intent, resolvedType, flags, pkg.providers, userId);
7112            }
7113            return Collections.emptyList();
7114        }
7115    }
7116
7117    @Override
7118    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7119        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7120        flags = updateFlagsForPackage(flags, userId, null);
7121        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7122        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7123                true /* requireFullPermission */, false /* checkShell */,
7124                "get installed packages");
7125
7126        // writer
7127        synchronized (mPackages) {
7128            ArrayList<PackageInfo> list;
7129            if (listUninstalled) {
7130                list = new ArrayList<>(mSettings.mPackages.size());
7131                for (PackageSetting ps : mSettings.mPackages.values()) {
7132                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7133                        continue;
7134                    }
7135                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7136                    if (pi != null) {
7137                        list.add(pi);
7138                    }
7139                }
7140            } else {
7141                list = new ArrayList<>(mPackages.size());
7142                for (PackageParser.Package p : mPackages.values()) {
7143                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7144                            Binder.getCallingUid(), userId)) {
7145                        continue;
7146                    }
7147                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7148                            p.mExtras, flags, userId);
7149                    if (pi != null) {
7150                        list.add(pi);
7151                    }
7152                }
7153            }
7154
7155            return new ParceledListSlice<>(list);
7156        }
7157    }
7158
7159    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7160            String[] permissions, boolean[] tmp, int flags, int userId) {
7161        int numMatch = 0;
7162        final PermissionsState permissionsState = ps.getPermissionsState();
7163        for (int i=0; i<permissions.length; i++) {
7164            final String permission = permissions[i];
7165            if (permissionsState.hasPermission(permission, userId)) {
7166                tmp[i] = true;
7167                numMatch++;
7168            } else {
7169                tmp[i] = false;
7170            }
7171        }
7172        if (numMatch == 0) {
7173            return;
7174        }
7175        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7176
7177        // The above might return null in cases of uninstalled apps or install-state
7178        // skew across users/profiles.
7179        if (pi != null) {
7180            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7181                if (numMatch == permissions.length) {
7182                    pi.requestedPermissions = permissions;
7183                } else {
7184                    pi.requestedPermissions = new String[numMatch];
7185                    numMatch = 0;
7186                    for (int i=0; i<permissions.length; i++) {
7187                        if (tmp[i]) {
7188                            pi.requestedPermissions[numMatch] = permissions[i];
7189                            numMatch++;
7190                        }
7191                    }
7192                }
7193            }
7194            list.add(pi);
7195        }
7196    }
7197
7198    @Override
7199    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7200            String[] permissions, int flags, int userId) {
7201        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7202        flags = updateFlagsForPackage(flags, userId, permissions);
7203        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7204                true /* requireFullPermission */, false /* checkShell */,
7205                "get packages holding permissions");
7206        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7207
7208        // writer
7209        synchronized (mPackages) {
7210            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7211            boolean[] tmpBools = new boolean[permissions.length];
7212            if (listUninstalled) {
7213                for (PackageSetting ps : mSettings.mPackages.values()) {
7214                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7215                            userId);
7216                }
7217            } else {
7218                for (PackageParser.Package pkg : mPackages.values()) {
7219                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7220                    if (ps != null) {
7221                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7222                                userId);
7223                    }
7224                }
7225            }
7226
7227            return new ParceledListSlice<PackageInfo>(list);
7228        }
7229    }
7230
7231    @Override
7232    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7233        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7234        flags = updateFlagsForApplication(flags, userId, null);
7235        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7236
7237        // writer
7238        synchronized (mPackages) {
7239            ArrayList<ApplicationInfo> list;
7240            if (listUninstalled) {
7241                list = new ArrayList<>(mSettings.mPackages.size());
7242                for (PackageSetting ps : mSettings.mPackages.values()) {
7243                    ApplicationInfo ai;
7244                    int effectiveFlags = flags;
7245                    if (ps.isSystem()) {
7246                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7247                    }
7248                    if (ps.pkg != null) {
7249                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7250                            continue;
7251                        }
7252                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7253                                ps.readUserState(userId), userId);
7254                        if (ai != null) {
7255                            rebaseEnabledOverlays(ai, userId);
7256                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7257                        }
7258                    } else {
7259                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7260                        // and already converts to externally visible package name
7261                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7262                                Binder.getCallingUid(), effectiveFlags, userId);
7263                    }
7264                    if (ai != null) {
7265                        list.add(ai);
7266                    }
7267                }
7268            } else {
7269                list = new ArrayList<>(mPackages.size());
7270                for (PackageParser.Package p : mPackages.values()) {
7271                    if (p.mExtras != null) {
7272                        PackageSetting ps = (PackageSetting) p.mExtras;
7273                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7274                            continue;
7275                        }
7276                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7277                                ps.readUserState(userId), userId);
7278                        if (ai != null) {
7279                            rebaseEnabledOverlays(ai, userId);
7280                            ai.packageName = resolveExternalPackageNameLPr(p);
7281                            list.add(ai);
7282                        }
7283                    }
7284                }
7285            }
7286
7287            return new ParceledListSlice<>(list);
7288        }
7289    }
7290
7291    @Override
7292    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7293        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7294            return null;
7295        }
7296
7297        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7298                "getEphemeralApplications");
7299        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7300                true /* requireFullPermission */, false /* checkShell */,
7301                "getEphemeralApplications");
7302        synchronized (mPackages) {
7303            List<InstantAppInfo> instantApps = mInstantAppRegistry
7304                    .getInstantAppsLPr(userId);
7305            if (instantApps != null) {
7306                return new ParceledListSlice<>(instantApps);
7307            }
7308        }
7309        return null;
7310    }
7311
7312    @Override
7313    public boolean isInstantApp(String packageName, int userId) {
7314        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7315                true /* requireFullPermission */, false /* checkShell */,
7316                "isInstantApp");
7317        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7318            return false;
7319        }
7320
7321        synchronized (mPackages) {
7322            final PackageSetting ps = mSettings.mPackages.get(packageName);
7323            final boolean returnAllowed =
7324                    ps != null
7325                    && (isCallerSameApp(packageName)
7326                            || mContext.checkCallingOrSelfPermission(
7327                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7328                                            == PERMISSION_GRANTED
7329                            || mInstantAppRegistry.isInstantAccessGranted(
7330                                    userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId));
7331            if (returnAllowed) {
7332                return ps.getInstantApp(userId);
7333            }
7334        }
7335        return false;
7336    }
7337
7338    @Override
7339    public byte[] getInstantAppCookie(String packageName, int userId) {
7340        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7341            return null;
7342        }
7343
7344        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7345                true /* requireFullPermission */, false /* checkShell */,
7346                "getInstantAppCookie");
7347        if (!isCallerSameApp(packageName)) {
7348            return null;
7349        }
7350        synchronized (mPackages) {
7351            return mInstantAppRegistry.getInstantAppCookieLPw(
7352                    packageName, userId);
7353        }
7354    }
7355
7356    @Override
7357    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7358        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7359            return true;
7360        }
7361
7362        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7363                true /* requireFullPermission */, true /* checkShell */,
7364                "setInstantAppCookie");
7365        if (!isCallerSameApp(packageName)) {
7366            return false;
7367        }
7368        synchronized (mPackages) {
7369            return mInstantAppRegistry.setInstantAppCookieLPw(
7370                    packageName, cookie, userId);
7371        }
7372    }
7373
7374    @Override
7375    public Bitmap getInstantAppIcon(String packageName, int userId) {
7376        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7377            return null;
7378        }
7379
7380        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7381                "getInstantAppIcon");
7382
7383        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7384                true /* requireFullPermission */, false /* checkShell */,
7385                "getInstantAppIcon");
7386
7387        synchronized (mPackages) {
7388            return mInstantAppRegistry.getInstantAppIconLPw(
7389                    packageName, userId);
7390        }
7391    }
7392
7393    private boolean isCallerSameApp(String packageName) {
7394        PackageParser.Package pkg = mPackages.get(packageName);
7395        return pkg != null
7396                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7397    }
7398
7399    @Override
7400    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7401        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7402    }
7403
7404    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7405        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7406
7407        // reader
7408        synchronized (mPackages) {
7409            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7410            final int userId = UserHandle.getCallingUserId();
7411            while (i.hasNext()) {
7412                final PackageParser.Package p = i.next();
7413                if (p.applicationInfo == null) continue;
7414
7415                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7416                        && !p.applicationInfo.isDirectBootAware();
7417                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7418                        && p.applicationInfo.isDirectBootAware();
7419
7420                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7421                        && (!mSafeMode || isSystemApp(p))
7422                        && (matchesUnaware || matchesAware)) {
7423                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7424                    if (ps != null) {
7425                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7426                                ps.readUserState(userId), userId);
7427                        if (ai != null) {
7428                            rebaseEnabledOverlays(ai, userId);
7429                            finalList.add(ai);
7430                        }
7431                    }
7432                }
7433            }
7434        }
7435
7436        return finalList;
7437    }
7438
7439    @Override
7440    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7441        if (!sUserManager.exists(userId)) return null;
7442        flags = updateFlagsForComponent(flags, userId, name);
7443        // reader
7444        synchronized (mPackages) {
7445            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7446            PackageSetting ps = provider != null
7447                    ? mSettings.mPackages.get(provider.owner.packageName)
7448                    : null;
7449            return ps != null
7450                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7451                    ? PackageParser.generateProviderInfo(provider, flags,
7452                            ps.readUserState(userId), userId)
7453                    : null;
7454        }
7455    }
7456
7457    /**
7458     * @deprecated
7459     */
7460    @Deprecated
7461    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7462        // reader
7463        synchronized (mPackages) {
7464            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7465                    .entrySet().iterator();
7466            final int userId = UserHandle.getCallingUserId();
7467            while (i.hasNext()) {
7468                Map.Entry<String, PackageParser.Provider> entry = i.next();
7469                PackageParser.Provider p = entry.getValue();
7470                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7471
7472                if (ps != null && p.syncable
7473                        && (!mSafeMode || (p.info.applicationInfo.flags
7474                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7475                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7476                            ps.readUserState(userId), userId);
7477                    if (info != null) {
7478                        outNames.add(entry.getKey());
7479                        outInfo.add(info);
7480                    }
7481                }
7482            }
7483        }
7484    }
7485
7486    @Override
7487    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7488            int uid, int flags, String metaDataKey) {
7489        final int userId = processName != null ? UserHandle.getUserId(uid)
7490                : UserHandle.getCallingUserId();
7491        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7492        flags = updateFlagsForComponent(flags, userId, processName);
7493
7494        ArrayList<ProviderInfo> finalList = null;
7495        // reader
7496        synchronized (mPackages) {
7497            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7498            while (i.hasNext()) {
7499                final PackageParser.Provider p = i.next();
7500                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7501                if (ps != null && p.info.authority != null
7502                        && (processName == null
7503                                || (p.info.processName.equals(processName)
7504                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7505                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7506
7507                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7508                    // parameter.
7509                    if (metaDataKey != null
7510                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7511                        continue;
7512                    }
7513
7514                    if (finalList == null) {
7515                        finalList = new ArrayList<ProviderInfo>(3);
7516                    }
7517                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7518                            ps.readUserState(userId), userId);
7519                    if (info != null) {
7520                        finalList.add(info);
7521                    }
7522                }
7523            }
7524        }
7525
7526        if (finalList != null) {
7527            Collections.sort(finalList, mProviderInitOrderSorter);
7528            return new ParceledListSlice<ProviderInfo>(finalList);
7529        }
7530
7531        return ParceledListSlice.emptyList();
7532    }
7533
7534    @Override
7535    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7536        // reader
7537        synchronized (mPackages) {
7538            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7539            return PackageParser.generateInstrumentationInfo(i, flags);
7540        }
7541    }
7542
7543    @Override
7544    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7545            String targetPackage, int flags) {
7546        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7547    }
7548
7549    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7550            int flags) {
7551        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7552
7553        // reader
7554        synchronized (mPackages) {
7555            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7556            while (i.hasNext()) {
7557                final PackageParser.Instrumentation p = i.next();
7558                if (targetPackage == null
7559                        || targetPackage.equals(p.info.targetPackage)) {
7560                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7561                            flags);
7562                    if (ii != null) {
7563                        finalList.add(ii);
7564                    }
7565                }
7566            }
7567        }
7568
7569        return finalList;
7570    }
7571
7572    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7573        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7574        try {
7575            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7576        } finally {
7577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7578        }
7579    }
7580
7581    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7582        final File[] files = dir.listFiles();
7583        if (ArrayUtils.isEmpty(files)) {
7584            Log.d(TAG, "No files in app dir " + dir);
7585            return;
7586        }
7587
7588        if (DEBUG_PACKAGE_SCANNING) {
7589            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7590                    + " flags=0x" + Integer.toHexString(parseFlags));
7591        }
7592        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7593                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7594
7595        // Submit files for parsing in parallel
7596        int fileCount = 0;
7597        for (File file : files) {
7598            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7599                    && !PackageInstallerService.isStageName(file.getName());
7600            if (!isPackage) {
7601                // Ignore entries which are not packages
7602                continue;
7603            }
7604            parallelPackageParser.submit(file, parseFlags);
7605            fileCount++;
7606        }
7607
7608        // Process results one by one
7609        for (; fileCount > 0; fileCount--) {
7610            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7611            Throwable throwable = parseResult.throwable;
7612            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7613
7614            if (throwable == null) {
7615                // Static shared libraries have synthetic package names
7616                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7617                    renameStaticSharedLibraryPackage(parseResult.pkg);
7618                }
7619                try {
7620                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7621                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7622                                currentTime, null);
7623                    }
7624                } catch (PackageManagerException e) {
7625                    errorCode = e.error;
7626                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7627                }
7628            } else if (throwable instanceof PackageParser.PackageParserException) {
7629                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7630                        throwable;
7631                errorCode = e.error;
7632                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7633            } else {
7634                throw new IllegalStateException("Unexpected exception occurred while parsing "
7635                        + parseResult.scanFile, throwable);
7636            }
7637
7638            // Delete invalid userdata apps
7639            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7640                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7641                logCriticalInfo(Log.WARN,
7642                        "Deleting invalid package at " + parseResult.scanFile);
7643                removeCodePathLI(parseResult.scanFile);
7644            }
7645        }
7646        parallelPackageParser.close();
7647    }
7648
7649    private static File getSettingsProblemFile() {
7650        File dataDir = Environment.getDataDirectory();
7651        File systemDir = new File(dataDir, "system");
7652        File fname = new File(systemDir, "uiderrors.txt");
7653        return fname;
7654    }
7655
7656    static void reportSettingsProblem(int priority, String msg) {
7657        logCriticalInfo(priority, msg);
7658    }
7659
7660    static void logCriticalInfo(int priority, String msg) {
7661        Slog.println(priority, TAG, msg);
7662        EventLogTags.writePmCriticalInfo(msg);
7663        try {
7664            File fname = getSettingsProblemFile();
7665            FileOutputStream out = new FileOutputStream(fname, true);
7666            PrintWriter pw = new FastPrintWriter(out);
7667            SimpleDateFormat formatter = new SimpleDateFormat();
7668            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7669            pw.println(dateString + ": " + msg);
7670            pw.close();
7671            FileUtils.setPermissions(
7672                    fname.toString(),
7673                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7674                    -1, -1);
7675        } catch (java.io.IOException e) {
7676        }
7677    }
7678
7679    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7680        if (srcFile.isDirectory()) {
7681            final File baseFile = new File(pkg.baseCodePath);
7682            long maxModifiedTime = baseFile.lastModified();
7683            if (pkg.splitCodePaths != null) {
7684                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7685                    final File splitFile = new File(pkg.splitCodePaths[i]);
7686                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7687                }
7688            }
7689            return maxModifiedTime;
7690        }
7691        return srcFile.lastModified();
7692    }
7693
7694    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7695            final int policyFlags) throws PackageManagerException {
7696        // When upgrading from pre-N MR1, verify the package time stamp using the package
7697        // directory and not the APK file.
7698        final long lastModifiedTime = mIsPreNMR1Upgrade
7699                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7700        if (ps != null
7701                && ps.codePath.equals(srcFile)
7702                && ps.timeStamp == lastModifiedTime
7703                && !isCompatSignatureUpdateNeeded(pkg)
7704                && !isRecoverSignatureUpdateNeeded(pkg)) {
7705            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7706            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7707            ArraySet<PublicKey> signingKs;
7708            synchronized (mPackages) {
7709                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7710            }
7711            if (ps.signatures.mSignatures != null
7712                    && ps.signatures.mSignatures.length != 0
7713                    && signingKs != null) {
7714                // Optimization: reuse the existing cached certificates
7715                // if the package appears to be unchanged.
7716                pkg.mSignatures = ps.signatures.mSignatures;
7717                pkg.mSigningKeys = signingKs;
7718                return;
7719            }
7720
7721            Slog.w(TAG, "PackageSetting for " + ps.name
7722                    + " is missing signatures.  Collecting certs again to recover them.");
7723        } else {
7724            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7725        }
7726
7727        try {
7728            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7729            PackageParser.collectCertificates(pkg, policyFlags);
7730        } catch (PackageParserException e) {
7731            throw PackageManagerException.from(e);
7732        } finally {
7733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7734        }
7735    }
7736
7737    /**
7738     *  Traces a package scan.
7739     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7740     */
7741    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7742            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7743        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7744        try {
7745            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7746        } finally {
7747            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7748        }
7749    }
7750
7751    /**
7752     *  Scans a package and returns the newly parsed package.
7753     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7754     */
7755    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7756            long currentTime, UserHandle user) throws PackageManagerException {
7757        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7758        PackageParser pp = new PackageParser();
7759        pp.setSeparateProcesses(mSeparateProcesses);
7760        pp.setOnlyCoreApps(mOnlyCore);
7761        pp.setDisplayMetrics(mMetrics);
7762        pp.setCallback(mPackageParserCallback);
7763
7764        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7765            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7766        }
7767
7768        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7769        final PackageParser.Package pkg;
7770        try {
7771            pkg = pp.parsePackage(scanFile, parseFlags);
7772        } catch (PackageParserException e) {
7773            throw PackageManagerException.from(e);
7774        } finally {
7775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7776        }
7777
7778        // Static shared libraries have synthetic package names
7779        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7780            renameStaticSharedLibraryPackage(pkg);
7781        }
7782
7783        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7784    }
7785
7786    /**
7787     *  Scans a package and returns the newly parsed package.
7788     *  @throws PackageManagerException on a parse error.
7789     */
7790    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7791            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7792            throws PackageManagerException {
7793        // If the package has children and this is the first dive in the function
7794        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7795        // packages (parent and children) would be successfully scanned before the
7796        // actual scan since scanning mutates internal state and we want to atomically
7797        // install the package and its children.
7798        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7799            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7800                scanFlags |= SCAN_CHECK_ONLY;
7801            }
7802        } else {
7803            scanFlags &= ~SCAN_CHECK_ONLY;
7804        }
7805
7806        // Scan the parent
7807        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7808                scanFlags, currentTime, user);
7809
7810        // Scan the children
7811        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7812        for (int i = 0; i < childCount; i++) {
7813            PackageParser.Package childPackage = pkg.childPackages.get(i);
7814            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7815                    currentTime, user);
7816        }
7817
7818
7819        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7820            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7821        }
7822
7823        return scannedPkg;
7824    }
7825
7826    /**
7827     *  Scans a package and returns the newly parsed package.
7828     *  @throws PackageManagerException on a parse error.
7829     */
7830    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7831            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7832            throws PackageManagerException {
7833        PackageSetting ps = null;
7834        PackageSetting updatedPkg;
7835        // reader
7836        synchronized (mPackages) {
7837            // Look to see if we already know about this package.
7838            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7839            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7840                // This package has been renamed to its original name.  Let's
7841                // use that.
7842                ps = mSettings.getPackageLPr(oldName);
7843            }
7844            // If there was no original package, see one for the real package name.
7845            if (ps == null) {
7846                ps = mSettings.getPackageLPr(pkg.packageName);
7847            }
7848            // Check to see if this package could be hiding/updating a system
7849            // package.  Must look for it either under the original or real
7850            // package name depending on our state.
7851            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7852            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7853
7854            // If this is a package we don't know about on the system partition, we
7855            // may need to remove disabled child packages on the system partition
7856            // or may need to not add child packages if the parent apk is updated
7857            // on the data partition and no longer defines this child package.
7858            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7859                // If this is a parent package for an updated system app and this system
7860                // app got an OTA update which no longer defines some of the child packages
7861                // we have to prune them from the disabled system packages.
7862                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7863                if (disabledPs != null) {
7864                    final int scannedChildCount = (pkg.childPackages != null)
7865                            ? pkg.childPackages.size() : 0;
7866                    final int disabledChildCount = disabledPs.childPackageNames != null
7867                            ? disabledPs.childPackageNames.size() : 0;
7868                    for (int i = 0; i < disabledChildCount; i++) {
7869                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7870                        boolean disabledPackageAvailable = false;
7871                        for (int j = 0; j < scannedChildCount; j++) {
7872                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7873                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7874                                disabledPackageAvailable = true;
7875                                break;
7876                            }
7877                         }
7878                         if (!disabledPackageAvailable) {
7879                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7880                         }
7881                    }
7882                }
7883            }
7884        }
7885
7886        boolean updatedPkgBetter = false;
7887        // First check if this is a system package that may involve an update
7888        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7889            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7890            // it needs to drop FLAG_PRIVILEGED.
7891            if (locationIsPrivileged(scanFile)) {
7892                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7893            } else {
7894                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7895            }
7896
7897            if (ps != null && !ps.codePath.equals(scanFile)) {
7898                // The path has changed from what was last scanned...  check the
7899                // version of the new path against what we have stored to determine
7900                // what to do.
7901                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7902                if (pkg.mVersionCode <= ps.versionCode) {
7903                    // The system package has been updated and the code path does not match
7904                    // Ignore entry. Skip it.
7905                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7906                            + " ignored: updated version " + ps.versionCode
7907                            + " better than this " + pkg.mVersionCode);
7908                    if (!updatedPkg.codePath.equals(scanFile)) {
7909                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7910                                + ps.name + " changing from " + updatedPkg.codePathString
7911                                + " to " + scanFile);
7912                        updatedPkg.codePath = scanFile;
7913                        updatedPkg.codePathString = scanFile.toString();
7914                        updatedPkg.resourcePath = scanFile;
7915                        updatedPkg.resourcePathString = scanFile.toString();
7916                    }
7917                    updatedPkg.pkg = pkg;
7918                    updatedPkg.versionCode = pkg.mVersionCode;
7919
7920                    // Update the disabled system child packages to point to the package too.
7921                    final int childCount = updatedPkg.childPackageNames != null
7922                            ? updatedPkg.childPackageNames.size() : 0;
7923                    for (int i = 0; i < childCount; i++) {
7924                        String childPackageName = updatedPkg.childPackageNames.get(i);
7925                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7926                                childPackageName);
7927                        if (updatedChildPkg != null) {
7928                            updatedChildPkg.pkg = pkg;
7929                            updatedChildPkg.versionCode = pkg.mVersionCode;
7930                        }
7931                    }
7932
7933                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7934                            + scanFile + " ignored: updated version " + ps.versionCode
7935                            + " better than this " + pkg.mVersionCode);
7936                } else {
7937                    // The current app on the system partition is better than
7938                    // what we have updated to on the data partition; switch
7939                    // back to the system partition version.
7940                    // At this point, its safely assumed that package installation for
7941                    // apps in system partition will go through. If not there won't be a working
7942                    // version of the app
7943                    // writer
7944                    synchronized (mPackages) {
7945                        // Just remove the loaded entries from package lists.
7946                        mPackages.remove(ps.name);
7947                    }
7948
7949                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7950                            + " reverting from " + ps.codePathString
7951                            + ": new version " + pkg.mVersionCode
7952                            + " better than installed " + ps.versionCode);
7953
7954                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7955                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7956                    synchronized (mInstallLock) {
7957                        args.cleanUpResourcesLI();
7958                    }
7959                    synchronized (mPackages) {
7960                        mSettings.enableSystemPackageLPw(ps.name);
7961                    }
7962                    updatedPkgBetter = true;
7963                }
7964            }
7965        }
7966
7967        if (updatedPkg != null) {
7968            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7969            // initially
7970            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7971
7972            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7973            // flag set initially
7974            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7975                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7976            }
7977        }
7978
7979        // Verify certificates against what was last scanned
7980        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7981
7982        /*
7983         * A new system app appeared, but we already had a non-system one of the
7984         * same name installed earlier.
7985         */
7986        boolean shouldHideSystemApp = false;
7987        if (updatedPkg == null && ps != null
7988                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7989            /*
7990             * Check to make sure the signatures match first. If they don't,
7991             * wipe the installed application and its data.
7992             */
7993            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7994                    != PackageManager.SIGNATURE_MATCH) {
7995                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7996                        + " signatures don't match existing userdata copy; removing");
7997                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7998                        "scanPackageInternalLI")) {
7999                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8000                }
8001                ps = null;
8002            } else {
8003                /*
8004                 * If the newly-added system app is an older version than the
8005                 * already installed version, hide it. It will be scanned later
8006                 * and re-added like an update.
8007                 */
8008                if (pkg.mVersionCode <= ps.versionCode) {
8009                    shouldHideSystemApp = true;
8010                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8011                            + " but new version " + pkg.mVersionCode + " better than installed "
8012                            + ps.versionCode + "; hiding system");
8013                } else {
8014                    /*
8015                     * The newly found system app is a newer version that the
8016                     * one previously installed. Simply remove the
8017                     * already-installed application and replace it with our own
8018                     * while keeping the application data.
8019                     */
8020                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8021                            + " reverting from " + ps.codePathString + ": new version "
8022                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8023                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8024                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8025                    synchronized (mInstallLock) {
8026                        args.cleanUpResourcesLI();
8027                    }
8028                }
8029            }
8030        }
8031
8032        // The apk is forward locked (not public) if its code and resources
8033        // are kept in different files. (except for app in either system or
8034        // vendor path).
8035        // TODO grab this value from PackageSettings
8036        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8037            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8038                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8039            }
8040        }
8041
8042        // TODO: extend to support forward-locked splits
8043        String resourcePath = null;
8044        String baseResourcePath = null;
8045        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8046            if (ps != null && ps.resourcePathString != null) {
8047                resourcePath = ps.resourcePathString;
8048                baseResourcePath = ps.resourcePathString;
8049            } else {
8050                // Should not happen at all. Just log an error.
8051                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8052            }
8053        } else {
8054            resourcePath = pkg.codePath;
8055            baseResourcePath = pkg.baseCodePath;
8056        }
8057
8058        // Set application objects path explicitly.
8059        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8060        pkg.setApplicationInfoCodePath(pkg.codePath);
8061        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8062        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8063        pkg.setApplicationInfoResourcePath(resourcePath);
8064        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8065        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8066
8067        final int userId = ((user == null) ? 0 : user.getIdentifier());
8068        if (ps != null && ps.getInstantApp(userId)) {
8069            scanFlags |= SCAN_AS_INSTANT_APP;
8070        }
8071
8072        // Note that we invoke the following method only if we are about to unpack an application
8073        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8074                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8075
8076        /*
8077         * If the system app should be overridden by a previously installed
8078         * data, hide the system app now and let the /data/app scan pick it up
8079         * again.
8080         */
8081        if (shouldHideSystemApp) {
8082            synchronized (mPackages) {
8083                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8084            }
8085        }
8086
8087        return scannedPkg;
8088    }
8089
8090    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8091        // Derive the new package synthetic package name
8092        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8093                + pkg.staticSharedLibVersion);
8094    }
8095
8096    private static String fixProcessName(String defProcessName,
8097            String processName) {
8098        if (processName == null) {
8099            return defProcessName;
8100        }
8101        return processName;
8102    }
8103
8104    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8105            throws PackageManagerException {
8106        if (pkgSetting.signatures.mSignatures != null) {
8107            // Already existing package. Make sure signatures match
8108            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8109                    == PackageManager.SIGNATURE_MATCH;
8110            if (!match) {
8111                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8112                        == PackageManager.SIGNATURE_MATCH;
8113            }
8114            if (!match) {
8115                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8116                        == PackageManager.SIGNATURE_MATCH;
8117            }
8118            if (!match) {
8119                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8120                        + pkg.packageName + " signatures do not match the "
8121                        + "previously installed version; ignoring!");
8122            }
8123        }
8124
8125        // Check for shared user signatures
8126        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8127            // Already existing package. Make sure signatures match
8128            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8129                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8130            if (!match) {
8131                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8132                        == PackageManager.SIGNATURE_MATCH;
8133            }
8134            if (!match) {
8135                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8136                        == PackageManager.SIGNATURE_MATCH;
8137            }
8138            if (!match) {
8139                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8140                        "Package " + pkg.packageName
8141                        + " has no signatures that match those in shared user "
8142                        + pkgSetting.sharedUser.name + "; ignoring!");
8143            }
8144        }
8145    }
8146
8147    /**
8148     * Enforces that only the system UID or root's UID can call a method exposed
8149     * via Binder.
8150     *
8151     * @param message used as message if SecurityException is thrown
8152     * @throws SecurityException if the caller is not system or root
8153     */
8154    private static final void enforceSystemOrRoot(String message) {
8155        final int uid = Binder.getCallingUid();
8156        if (uid != Process.SYSTEM_UID && uid != 0) {
8157            throw new SecurityException(message);
8158        }
8159    }
8160
8161    @Override
8162    public void performFstrimIfNeeded() {
8163        enforceSystemOrRoot("Only the system can request fstrim");
8164
8165        // Before everything else, see whether we need to fstrim.
8166        try {
8167            IStorageManager sm = PackageHelper.getStorageManager();
8168            if (sm != null) {
8169                boolean doTrim = false;
8170                final long interval = android.provider.Settings.Global.getLong(
8171                        mContext.getContentResolver(),
8172                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8173                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8174                if (interval > 0) {
8175                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8176                    if (timeSinceLast > interval) {
8177                        doTrim = true;
8178                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8179                                + "; running immediately");
8180                    }
8181                }
8182                if (doTrim) {
8183                    final boolean dexOptDialogShown;
8184                    synchronized (mPackages) {
8185                        dexOptDialogShown = mDexOptDialogShown;
8186                    }
8187                    if (!isFirstBoot() && dexOptDialogShown) {
8188                        try {
8189                            ActivityManager.getService().showBootMessage(
8190                                    mContext.getResources().getString(
8191                                            R.string.android_upgrading_fstrim), true);
8192                        } catch (RemoteException e) {
8193                        }
8194                    }
8195                    sm.runMaintenance();
8196                }
8197            } else {
8198                Slog.e(TAG, "storageManager service unavailable!");
8199            }
8200        } catch (RemoteException e) {
8201            // Can't happen; StorageManagerService is local
8202        }
8203    }
8204
8205    @Override
8206    public void updatePackagesIfNeeded() {
8207        enforceSystemOrRoot("Only the system can request package update");
8208
8209        // We need to re-extract after an OTA.
8210        boolean causeUpgrade = isUpgrade();
8211
8212        // First boot or factory reset.
8213        // Note: we also handle devices that are upgrading to N right now as if it is their
8214        //       first boot, as they do not have profile data.
8215        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8216
8217        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8218        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8219
8220        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8221            return;
8222        }
8223
8224        List<PackageParser.Package> pkgs;
8225        synchronized (mPackages) {
8226            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8227        }
8228
8229        final long startTime = System.nanoTime();
8230        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8231                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8232
8233        final int elapsedTimeSeconds =
8234                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8235
8236        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8237        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8238        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8239        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8240        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8241    }
8242
8243    /**
8244     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8245     * containing statistics about the invocation. The array consists of three elements,
8246     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8247     * and {@code numberOfPackagesFailed}.
8248     */
8249    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8250            String compilerFilter) {
8251
8252        int numberOfPackagesVisited = 0;
8253        int numberOfPackagesOptimized = 0;
8254        int numberOfPackagesSkipped = 0;
8255        int numberOfPackagesFailed = 0;
8256        final int numberOfPackagesToDexopt = pkgs.size();
8257
8258        for (PackageParser.Package pkg : pkgs) {
8259            numberOfPackagesVisited++;
8260
8261            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8262                if (DEBUG_DEXOPT) {
8263                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8264                }
8265                numberOfPackagesSkipped++;
8266                continue;
8267            }
8268
8269            if (DEBUG_DEXOPT) {
8270                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8271                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8272            }
8273
8274            if (showDialog) {
8275                try {
8276                    ActivityManager.getService().showBootMessage(
8277                            mContext.getResources().getString(R.string.android_upgrading_apk,
8278                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8279                } catch (RemoteException e) {
8280                }
8281                synchronized (mPackages) {
8282                    mDexOptDialogShown = true;
8283                }
8284            }
8285
8286            // If the OTA updates a system app which was previously preopted to a non-preopted state
8287            // the app might end up being verified at runtime. That's because by default the apps
8288            // are verify-profile but for preopted apps there's no profile.
8289            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8290            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8291            // filter (by default interpret-only).
8292            // Note that at this stage unused apps are already filtered.
8293            if (isSystemApp(pkg) &&
8294                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8295                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8296                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8297            }
8298
8299            // checkProfiles is false to avoid merging profiles during boot which
8300            // might interfere with background compilation (b/28612421).
8301            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8302            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8303            // trade-off worth doing to save boot time work.
8304            int dexOptStatus = performDexOptTraced(pkg.packageName,
8305                    false /* checkProfiles */,
8306                    compilerFilter,
8307                    false /* force */);
8308            switch (dexOptStatus) {
8309                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8310                    numberOfPackagesOptimized++;
8311                    break;
8312                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8313                    numberOfPackagesSkipped++;
8314                    break;
8315                case PackageDexOptimizer.DEX_OPT_FAILED:
8316                    numberOfPackagesFailed++;
8317                    break;
8318                default:
8319                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8320                    break;
8321            }
8322        }
8323
8324        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8325                numberOfPackagesFailed };
8326    }
8327
8328    @Override
8329    public void notifyPackageUse(String packageName, int reason) {
8330        synchronized (mPackages) {
8331            PackageParser.Package p = mPackages.get(packageName);
8332            if (p == null) {
8333                return;
8334            }
8335            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8336        }
8337    }
8338
8339    @Override
8340    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8341        int userId = UserHandle.getCallingUserId();
8342        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8343        if (ai == null) {
8344            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8345                + loadingPackageName + ", user=" + userId);
8346            return;
8347        }
8348        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8349    }
8350
8351    // TODO: this is not used nor needed. Delete it.
8352    @Override
8353    public boolean performDexOptIfNeeded(String packageName) {
8354        int dexOptStatus = performDexOptTraced(packageName,
8355                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8356        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8357    }
8358
8359    @Override
8360    public boolean performDexOpt(String packageName,
8361            boolean checkProfiles, int compileReason, boolean force) {
8362        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8363                getCompilerFilterForReason(compileReason), force);
8364        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8365    }
8366
8367    @Override
8368    public boolean performDexOptMode(String packageName,
8369            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8370        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8371                targetCompilerFilter, force);
8372        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8373    }
8374
8375    private int performDexOptTraced(String packageName,
8376                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8377        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8378        try {
8379            return performDexOptInternal(packageName, checkProfiles,
8380                    targetCompilerFilter, force);
8381        } finally {
8382            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8383        }
8384    }
8385
8386    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8387    // if the package can now be considered up to date for the given filter.
8388    private int performDexOptInternal(String packageName,
8389                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8390        PackageParser.Package p;
8391        synchronized (mPackages) {
8392            p = mPackages.get(packageName);
8393            if (p == null) {
8394                // Package could not be found. Report failure.
8395                return PackageDexOptimizer.DEX_OPT_FAILED;
8396            }
8397            mPackageUsage.maybeWriteAsync(mPackages);
8398            mCompilerStats.maybeWriteAsync();
8399        }
8400        long callingId = Binder.clearCallingIdentity();
8401        try {
8402            synchronized (mInstallLock) {
8403                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8404                        targetCompilerFilter, force);
8405            }
8406        } finally {
8407            Binder.restoreCallingIdentity(callingId);
8408        }
8409    }
8410
8411    public ArraySet<String> getOptimizablePackages() {
8412        ArraySet<String> pkgs = new ArraySet<String>();
8413        synchronized (mPackages) {
8414            for (PackageParser.Package p : mPackages.values()) {
8415                if (PackageDexOptimizer.canOptimizePackage(p)) {
8416                    pkgs.add(p.packageName);
8417                }
8418            }
8419        }
8420        return pkgs;
8421    }
8422
8423    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8424            boolean checkProfiles, String targetCompilerFilter,
8425            boolean force) {
8426        // Select the dex optimizer based on the force parameter.
8427        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8428        //       allocate an object here.
8429        PackageDexOptimizer pdo = force
8430                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8431                : mPackageDexOptimizer;
8432
8433        // Optimize all dependencies first. Note: we ignore the return value and march on
8434        // on errors.
8435        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8436        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8437        if (!deps.isEmpty()) {
8438            for (PackageParser.Package depPackage : deps) {
8439                // TODO: Analyze and investigate if we (should) profile libraries.
8440                // Currently this will do a full compilation of the library by default.
8441                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8442                        false /* checkProfiles */,
8443                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8444                        getOrCreateCompilerPackageStats(depPackage),
8445                        mDexManager.isUsedByOtherApps(p.packageName));
8446            }
8447        }
8448        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8449                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8450                mDexManager.isUsedByOtherApps(p.packageName));
8451    }
8452
8453    // Performs dexopt on the used secondary dex files belonging to the given package.
8454    // Returns true if all dex files were process successfully (which could mean either dexopt or
8455    // skip). Returns false if any of the files caused errors.
8456    @Override
8457    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8458            boolean force) {
8459        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8460    }
8461
8462    /**
8463     * Reconcile the information we have about the secondary dex files belonging to
8464     * {@code packagName} and the actual dex files. For all dex files that were
8465     * deleted, update the internal records and delete the generated oat files.
8466     */
8467    @Override
8468    public void reconcileSecondaryDexFiles(String packageName) {
8469        mDexManager.reconcileSecondaryDexFiles(packageName);
8470    }
8471
8472    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8473    // a reference there.
8474    /*package*/ DexManager getDexManager() {
8475        return mDexManager;
8476    }
8477
8478    /**
8479     * Execute the background dexopt job immediately.
8480     */
8481    @Override
8482    public boolean runBackgroundDexoptJob() {
8483        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8484    }
8485
8486    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8487        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8488                || p.usesStaticLibraries != null) {
8489            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8490            Set<String> collectedNames = new HashSet<>();
8491            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8492
8493            retValue.remove(p);
8494
8495            return retValue;
8496        } else {
8497            return Collections.emptyList();
8498        }
8499    }
8500
8501    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8502            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8503        if (!collectedNames.contains(p.packageName)) {
8504            collectedNames.add(p.packageName);
8505            collected.add(p);
8506
8507            if (p.usesLibraries != null) {
8508                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8509                        null, collected, collectedNames);
8510            }
8511            if (p.usesOptionalLibraries != null) {
8512                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8513                        null, collected, collectedNames);
8514            }
8515            if (p.usesStaticLibraries != null) {
8516                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8517                        p.usesStaticLibrariesVersions, collected, collectedNames);
8518            }
8519        }
8520    }
8521
8522    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8523            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8524        final int libNameCount = libs.size();
8525        for (int i = 0; i < libNameCount; i++) {
8526            String libName = libs.get(i);
8527            int version = (versions != null && versions.length == libNameCount)
8528                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8529            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8530            if (libPkg != null) {
8531                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8532            }
8533        }
8534    }
8535
8536    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8537        synchronized (mPackages) {
8538            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8539            if (libEntry != null) {
8540                return mPackages.get(libEntry.apk);
8541            }
8542            return null;
8543        }
8544    }
8545
8546    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8547        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8548        if (versionedLib == null) {
8549            return null;
8550        }
8551        return versionedLib.get(version);
8552    }
8553
8554    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8555        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8556                pkg.staticSharedLibName);
8557        if (versionedLib == null) {
8558            return null;
8559        }
8560        int previousLibVersion = -1;
8561        final int versionCount = versionedLib.size();
8562        for (int i = 0; i < versionCount; i++) {
8563            final int libVersion = versionedLib.keyAt(i);
8564            if (libVersion < pkg.staticSharedLibVersion) {
8565                previousLibVersion = Math.max(previousLibVersion, libVersion);
8566            }
8567        }
8568        if (previousLibVersion >= 0) {
8569            return versionedLib.get(previousLibVersion);
8570        }
8571        return null;
8572    }
8573
8574    public void shutdown() {
8575        mPackageUsage.writeNow(mPackages);
8576        mCompilerStats.writeNow();
8577    }
8578
8579    @Override
8580    public void dumpProfiles(String packageName) {
8581        PackageParser.Package pkg;
8582        synchronized (mPackages) {
8583            pkg = mPackages.get(packageName);
8584            if (pkg == null) {
8585                throw new IllegalArgumentException("Unknown package: " + packageName);
8586            }
8587        }
8588        /* Only the shell, root, or the app user should be able to dump profiles. */
8589        int callingUid = Binder.getCallingUid();
8590        if (callingUid != Process.SHELL_UID &&
8591            callingUid != Process.ROOT_UID &&
8592            callingUid != pkg.applicationInfo.uid) {
8593            throw new SecurityException("dumpProfiles");
8594        }
8595
8596        synchronized (mInstallLock) {
8597            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8598            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8599            try {
8600                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8601                String codePaths = TextUtils.join(";", allCodePaths);
8602                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8603            } catch (InstallerException e) {
8604                Slog.w(TAG, "Failed to dump profiles", e);
8605            }
8606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8607        }
8608    }
8609
8610    @Override
8611    public void forceDexOpt(String packageName) {
8612        enforceSystemOrRoot("forceDexOpt");
8613
8614        PackageParser.Package pkg;
8615        synchronized (mPackages) {
8616            pkg = mPackages.get(packageName);
8617            if (pkg == null) {
8618                throw new IllegalArgumentException("Unknown package: " + packageName);
8619            }
8620        }
8621
8622        synchronized (mInstallLock) {
8623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8624
8625            // Whoever is calling forceDexOpt wants a fully compiled package.
8626            // Don't use profiles since that may cause compilation to be skipped.
8627            final int res = performDexOptInternalWithDependenciesLI(pkg,
8628                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8629                    true /* force */);
8630
8631            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8632            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8633                throw new IllegalStateException("Failed to dexopt: " + res);
8634            }
8635        }
8636    }
8637
8638    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8639        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8640            Slog.w(TAG, "Unable to update from " + oldPkg.name
8641                    + " to " + newPkg.packageName
8642                    + ": old package not in system partition");
8643            return false;
8644        } else if (mPackages.get(oldPkg.name) != null) {
8645            Slog.w(TAG, "Unable to update from " + oldPkg.name
8646                    + " to " + newPkg.packageName
8647                    + ": old package still exists");
8648            return false;
8649        }
8650        return true;
8651    }
8652
8653    void removeCodePathLI(File codePath) {
8654        if (codePath.isDirectory()) {
8655            try {
8656                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8657            } catch (InstallerException e) {
8658                Slog.w(TAG, "Failed to remove code path", e);
8659            }
8660        } else {
8661            codePath.delete();
8662        }
8663    }
8664
8665    private int[] resolveUserIds(int userId) {
8666        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8667    }
8668
8669    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8670        if (pkg == null) {
8671            Slog.wtf(TAG, "Package was null!", new Throwable());
8672            return;
8673        }
8674        clearAppDataLeafLIF(pkg, userId, flags);
8675        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8676        for (int i = 0; i < childCount; i++) {
8677            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8678        }
8679    }
8680
8681    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8682        final PackageSetting ps;
8683        synchronized (mPackages) {
8684            ps = mSettings.mPackages.get(pkg.packageName);
8685        }
8686        for (int realUserId : resolveUserIds(userId)) {
8687            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8688            try {
8689                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8690                        ceDataInode);
8691            } catch (InstallerException e) {
8692                Slog.w(TAG, String.valueOf(e));
8693            }
8694        }
8695    }
8696
8697    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8698        if (pkg == null) {
8699            Slog.wtf(TAG, "Package was null!", new Throwable());
8700            return;
8701        }
8702        destroyAppDataLeafLIF(pkg, userId, flags);
8703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8704        for (int i = 0; i < childCount; i++) {
8705            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8706        }
8707    }
8708
8709    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8710        final PackageSetting ps;
8711        synchronized (mPackages) {
8712            ps = mSettings.mPackages.get(pkg.packageName);
8713        }
8714        for (int realUserId : resolveUserIds(userId)) {
8715            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8716            try {
8717                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8718                        ceDataInode);
8719            } catch (InstallerException e) {
8720                Slog.w(TAG, String.valueOf(e));
8721            }
8722            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8723        }
8724    }
8725
8726    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8727        if (pkg == null) {
8728            Slog.wtf(TAG, "Package was null!", new Throwable());
8729            return;
8730        }
8731        destroyAppProfilesLeafLIF(pkg);
8732        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8733        for (int i = 0; i < childCount; i++) {
8734            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8735        }
8736    }
8737
8738    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8739        try {
8740            mInstaller.destroyAppProfiles(pkg.packageName);
8741        } catch (InstallerException e) {
8742            Slog.w(TAG, String.valueOf(e));
8743        }
8744    }
8745
8746    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8747        if (pkg == null) {
8748            Slog.wtf(TAG, "Package was null!", new Throwable());
8749            return;
8750        }
8751        clearAppProfilesLeafLIF(pkg);
8752        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8753        for (int i = 0; i < childCount; i++) {
8754            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8755        }
8756    }
8757
8758    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8759        try {
8760            mInstaller.clearAppProfiles(pkg.packageName);
8761        } catch (InstallerException e) {
8762            Slog.w(TAG, String.valueOf(e));
8763        }
8764    }
8765
8766    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8767            long lastUpdateTime) {
8768        // Set parent install/update time
8769        PackageSetting ps = (PackageSetting) pkg.mExtras;
8770        if (ps != null) {
8771            ps.firstInstallTime = firstInstallTime;
8772            ps.lastUpdateTime = lastUpdateTime;
8773        }
8774        // Set children install/update time
8775        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8776        for (int i = 0; i < childCount; i++) {
8777            PackageParser.Package childPkg = pkg.childPackages.get(i);
8778            ps = (PackageSetting) childPkg.mExtras;
8779            if (ps != null) {
8780                ps.firstInstallTime = firstInstallTime;
8781                ps.lastUpdateTime = lastUpdateTime;
8782            }
8783        }
8784    }
8785
8786    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8787            PackageParser.Package changingLib) {
8788        if (file.path != null) {
8789            usesLibraryFiles.add(file.path);
8790            return;
8791        }
8792        PackageParser.Package p = mPackages.get(file.apk);
8793        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8794            // If we are doing this while in the middle of updating a library apk,
8795            // then we need to make sure to use that new apk for determining the
8796            // dependencies here.  (We haven't yet finished committing the new apk
8797            // to the package manager state.)
8798            if (p == null || p.packageName.equals(changingLib.packageName)) {
8799                p = changingLib;
8800            }
8801        }
8802        if (p != null) {
8803            usesLibraryFiles.addAll(p.getAllCodePaths());
8804        }
8805    }
8806
8807    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8808            PackageParser.Package changingLib) throws PackageManagerException {
8809        if (pkg == null) {
8810            return;
8811        }
8812        ArraySet<String> usesLibraryFiles = null;
8813        if (pkg.usesLibraries != null) {
8814            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8815                    null, null, pkg.packageName, changingLib, true, null);
8816        }
8817        if (pkg.usesStaticLibraries != null) {
8818            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8819                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8820                    pkg.packageName, changingLib, true, usesLibraryFiles);
8821        }
8822        if (pkg.usesOptionalLibraries != null) {
8823            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8824                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8825        }
8826        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8827            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8828        } else {
8829            pkg.usesLibraryFiles = null;
8830        }
8831    }
8832
8833    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8834            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8835            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8836            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8837            throws PackageManagerException {
8838        final int libCount = requestedLibraries.size();
8839        for (int i = 0; i < libCount; i++) {
8840            final String libName = requestedLibraries.get(i);
8841            final int libVersion = requiredVersions != null ? requiredVersions[i]
8842                    : SharedLibraryInfo.VERSION_UNDEFINED;
8843            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8844            if (libEntry == null) {
8845                if (required) {
8846                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8847                            "Package " + packageName + " requires unavailable shared library "
8848                                    + libName + "; failing!");
8849                } else {
8850                    Slog.w(TAG, "Package " + packageName
8851                            + " desires unavailable shared library "
8852                            + libName + "; ignoring!");
8853                }
8854            } else {
8855                if (requiredVersions != null && requiredCertDigests != null) {
8856                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8857                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8858                            "Package " + packageName + " requires unavailable static shared"
8859                                    + " library " + libName + " version "
8860                                    + libEntry.info.getVersion() + "; failing!");
8861                    }
8862
8863                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8864                    if (libPkg == null) {
8865                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8866                                "Package " + packageName + " requires unavailable static shared"
8867                                        + " library; failing!");
8868                    }
8869
8870                    String expectedCertDigest = requiredCertDigests[i];
8871                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8872                                libPkg.mSignatures[0]);
8873                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8874                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8875                                "Package " + packageName + " requires differently signed" +
8876                                        " static shared library; failing!");
8877                    }
8878                }
8879
8880                if (outUsedLibraries == null) {
8881                    outUsedLibraries = new ArraySet<>();
8882                }
8883                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8884            }
8885        }
8886        return outUsedLibraries;
8887    }
8888
8889    private static boolean hasString(List<String> list, List<String> which) {
8890        if (list == null) {
8891            return false;
8892        }
8893        for (int i=list.size()-1; i>=0; i--) {
8894            for (int j=which.size()-1; j>=0; j--) {
8895                if (which.get(j).equals(list.get(i))) {
8896                    return true;
8897                }
8898            }
8899        }
8900        return false;
8901    }
8902
8903    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8904            PackageParser.Package changingPkg) {
8905        ArrayList<PackageParser.Package> res = null;
8906        for (PackageParser.Package pkg : mPackages.values()) {
8907            if (changingPkg != null
8908                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8909                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8910                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8911                            changingPkg.staticSharedLibName)) {
8912                return null;
8913            }
8914            if (res == null) {
8915                res = new ArrayList<>();
8916            }
8917            res.add(pkg);
8918            try {
8919                updateSharedLibrariesLPr(pkg, changingPkg);
8920            } catch (PackageManagerException e) {
8921                // If a system app update or an app and a required lib missing we
8922                // delete the package and for updated system apps keep the data as
8923                // it is better for the user to reinstall than to be in an limbo
8924                // state. Also libs disappearing under an app should never happen
8925                // - just in case.
8926                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8927                    final int flags = pkg.isUpdatedSystemApp()
8928                            ? PackageManager.DELETE_KEEP_DATA : 0;
8929                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8930                            flags , null, true, null);
8931                }
8932                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8933            }
8934        }
8935        return res;
8936    }
8937
8938    /**
8939     * Derive the value of the {@code cpuAbiOverride} based on the provided
8940     * value and an optional stored value from the package settings.
8941     */
8942    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8943        String cpuAbiOverride = null;
8944
8945        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8946            cpuAbiOverride = null;
8947        } else if (abiOverride != null) {
8948            cpuAbiOverride = abiOverride;
8949        } else if (settings != null) {
8950            cpuAbiOverride = settings.cpuAbiOverrideString;
8951        }
8952
8953        return cpuAbiOverride;
8954    }
8955
8956    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8957            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8958                    throws PackageManagerException {
8959        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8960        // If the package has children and this is the first dive in the function
8961        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8962        // whether all packages (parent and children) would be successfully scanned
8963        // before the actual scan since scanning mutates internal state and we want
8964        // to atomically install the package and its children.
8965        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8966            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8967                scanFlags |= SCAN_CHECK_ONLY;
8968            }
8969        } else {
8970            scanFlags &= ~SCAN_CHECK_ONLY;
8971        }
8972
8973        final PackageParser.Package scannedPkg;
8974        try {
8975            // Scan the parent
8976            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8977            // Scan the children
8978            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8979            for (int i = 0; i < childCount; i++) {
8980                PackageParser.Package childPkg = pkg.childPackages.get(i);
8981                scanPackageLI(childPkg, policyFlags,
8982                        scanFlags, currentTime, user);
8983            }
8984        } finally {
8985            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8986        }
8987
8988        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8989            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8990        }
8991
8992        return scannedPkg;
8993    }
8994
8995    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8996            int scanFlags, long currentTime, @Nullable UserHandle user)
8997                    throws PackageManagerException {
8998        boolean success = false;
8999        try {
9000            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9001                    currentTime, user);
9002            success = true;
9003            return res;
9004        } finally {
9005            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9006                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9007                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9008                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9009                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9010            }
9011        }
9012    }
9013
9014    /**
9015     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9016     */
9017    private static boolean apkHasCode(String fileName) {
9018        StrictJarFile jarFile = null;
9019        try {
9020            jarFile = new StrictJarFile(fileName,
9021                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9022            return jarFile.findEntry("classes.dex") != null;
9023        } catch (IOException ignore) {
9024        } finally {
9025            try {
9026                if (jarFile != null) {
9027                    jarFile.close();
9028                }
9029            } catch (IOException ignore) {}
9030        }
9031        return false;
9032    }
9033
9034    /**
9035     * Enforces code policy for the package. This ensures that if an APK has
9036     * declared hasCode="true" in its manifest that the APK actually contains
9037     * code.
9038     *
9039     * @throws PackageManagerException If bytecode could not be found when it should exist
9040     */
9041    private static void assertCodePolicy(PackageParser.Package pkg)
9042            throws PackageManagerException {
9043        final boolean shouldHaveCode =
9044                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9045        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9046            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9047                    "Package " + pkg.baseCodePath + " code is missing");
9048        }
9049
9050        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9051            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9052                final boolean splitShouldHaveCode =
9053                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9054                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9055                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9056                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9057                }
9058            }
9059        }
9060    }
9061
9062    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9063            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9064                    throws PackageManagerException {
9065        if (DEBUG_PACKAGE_SCANNING) {
9066            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9067                Log.d(TAG, "Scanning package " + pkg.packageName);
9068        }
9069
9070        applyPolicy(pkg, policyFlags);
9071
9072        assertPackageIsValid(pkg, policyFlags, scanFlags);
9073
9074        // Initialize package source and resource directories
9075        final File scanFile = new File(pkg.codePath);
9076        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9077        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9078
9079        SharedUserSetting suid = null;
9080        PackageSetting pkgSetting = null;
9081
9082        // Getting the package setting may have a side-effect, so if we
9083        // are only checking if scan would succeed, stash a copy of the
9084        // old setting to restore at the end.
9085        PackageSetting nonMutatedPs = null;
9086
9087        // We keep references to the derived CPU Abis from settings in oder to reuse
9088        // them in the case where we're not upgrading or booting for the first time.
9089        String primaryCpuAbiFromSettings = null;
9090        String secondaryCpuAbiFromSettings = null;
9091
9092        // writer
9093        synchronized (mPackages) {
9094            if (pkg.mSharedUserId != null) {
9095                // SIDE EFFECTS; may potentially allocate a new shared user
9096                suid = mSettings.getSharedUserLPw(
9097                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9098                if (DEBUG_PACKAGE_SCANNING) {
9099                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9100                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9101                                + "): packages=" + suid.packages);
9102                }
9103            }
9104
9105            // Check if we are renaming from an original package name.
9106            PackageSetting origPackage = null;
9107            String realName = null;
9108            if (pkg.mOriginalPackages != null) {
9109                // This package may need to be renamed to a previously
9110                // installed name.  Let's check on that...
9111                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9112                if (pkg.mOriginalPackages.contains(renamed)) {
9113                    // This package had originally been installed as the
9114                    // original name, and we have already taken care of
9115                    // transitioning to the new one.  Just update the new
9116                    // one to continue using the old name.
9117                    realName = pkg.mRealPackage;
9118                    if (!pkg.packageName.equals(renamed)) {
9119                        // Callers into this function may have already taken
9120                        // care of renaming the package; only do it here if
9121                        // it is not already done.
9122                        pkg.setPackageName(renamed);
9123                    }
9124                } else {
9125                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9126                        if ((origPackage = mSettings.getPackageLPr(
9127                                pkg.mOriginalPackages.get(i))) != null) {
9128                            // We do have the package already installed under its
9129                            // original name...  should we use it?
9130                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9131                                // New package is not compatible with original.
9132                                origPackage = null;
9133                                continue;
9134                            } else if (origPackage.sharedUser != null) {
9135                                // Make sure uid is compatible between packages.
9136                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9137                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9138                                            + " to " + pkg.packageName + ": old uid "
9139                                            + origPackage.sharedUser.name
9140                                            + " differs from " + pkg.mSharedUserId);
9141                                    origPackage = null;
9142                                    continue;
9143                                }
9144                                // TODO: Add case when shared user id is added [b/28144775]
9145                            } else {
9146                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9147                                        + pkg.packageName + " to old name " + origPackage.name);
9148                            }
9149                            break;
9150                        }
9151                    }
9152                }
9153            }
9154
9155            if (mTransferedPackages.contains(pkg.packageName)) {
9156                Slog.w(TAG, "Package " + pkg.packageName
9157                        + " was transferred to another, but its .apk remains");
9158            }
9159
9160            // See comments in nonMutatedPs declaration
9161            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9162                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9163                if (foundPs != null) {
9164                    nonMutatedPs = new PackageSetting(foundPs);
9165                }
9166            }
9167
9168            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9169                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9170                if (foundPs != null) {
9171                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9172                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9173                }
9174            }
9175
9176            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9177            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9178                PackageManagerService.reportSettingsProblem(Log.WARN,
9179                        "Package " + pkg.packageName + " shared user changed from "
9180                                + (pkgSetting.sharedUser != null
9181                                        ? pkgSetting.sharedUser.name : "<nothing>")
9182                                + " to "
9183                                + (suid != null ? suid.name : "<nothing>")
9184                                + "; replacing with new");
9185                pkgSetting = null;
9186            }
9187            final PackageSetting oldPkgSetting =
9188                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9189            final PackageSetting disabledPkgSetting =
9190                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9191
9192            String[] usesStaticLibraries = null;
9193            if (pkg.usesStaticLibraries != null) {
9194                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9195                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9196            }
9197
9198            if (pkgSetting == null) {
9199                final String parentPackageName = (pkg.parentPackage != null)
9200                        ? pkg.parentPackage.packageName : null;
9201                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9202                // REMOVE SharedUserSetting from method; update in a separate call
9203                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9204                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9205                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9206                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9207                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9208                        true /*allowInstall*/, instantApp, parentPackageName,
9209                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9210                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9211                // SIDE EFFECTS; updates system state; move elsewhere
9212                if (origPackage != null) {
9213                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9214                }
9215                mSettings.addUserToSettingLPw(pkgSetting);
9216            } else {
9217                // REMOVE SharedUserSetting from method; update in a separate call.
9218                //
9219                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9220                // secondaryCpuAbi are not known at this point so we always update them
9221                // to null here, only to reset them at a later point.
9222                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9223                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9224                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9225                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9226                        UserManagerService.getInstance(), usesStaticLibraries,
9227                        pkg.usesStaticLibrariesVersions);
9228            }
9229            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9230            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9231
9232            // SIDE EFFECTS; modifies system state; move elsewhere
9233            if (pkgSetting.origPackage != null) {
9234                // If we are first transitioning from an original package,
9235                // fix up the new package's name now.  We need to do this after
9236                // looking up the package under its new name, so getPackageLP
9237                // can take care of fiddling things correctly.
9238                pkg.setPackageName(origPackage.name);
9239
9240                // File a report about this.
9241                String msg = "New package " + pkgSetting.realName
9242                        + " renamed to replace old package " + pkgSetting.name;
9243                reportSettingsProblem(Log.WARN, msg);
9244
9245                // Make a note of it.
9246                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9247                    mTransferedPackages.add(origPackage.name);
9248                }
9249
9250                // No longer need to retain this.
9251                pkgSetting.origPackage = null;
9252            }
9253
9254            // SIDE EFFECTS; modifies system state; move elsewhere
9255            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9256                // Make a note of it.
9257                mTransferedPackages.add(pkg.packageName);
9258            }
9259
9260            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9261                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9262            }
9263
9264            if ((scanFlags & SCAN_BOOTING) == 0
9265                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9266                // Check all shared libraries and map to their actual file path.
9267                // We only do this here for apps not on a system dir, because those
9268                // are the only ones that can fail an install due to this.  We
9269                // will take care of the system apps by updating all of their
9270                // library paths after the scan is done. Also during the initial
9271                // scan don't update any libs as we do this wholesale after all
9272                // apps are scanned to avoid dependency based scanning.
9273                updateSharedLibrariesLPr(pkg, null);
9274            }
9275
9276            if (mFoundPolicyFile) {
9277                SELinuxMMAC.assignSeInfoValue(pkg);
9278            }
9279            pkg.applicationInfo.uid = pkgSetting.appId;
9280            pkg.mExtras = pkgSetting;
9281
9282
9283            // Static shared libs have same package with different versions where
9284            // we internally use a synthetic package name to allow multiple versions
9285            // of the same package, therefore we need to compare signatures against
9286            // the package setting for the latest library version.
9287            PackageSetting signatureCheckPs = pkgSetting;
9288            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9289                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9290                if (libraryEntry != null) {
9291                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9292                }
9293            }
9294
9295            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9296                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9297                    // We just determined the app is signed correctly, so bring
9298                    // over the latest parsed certs.
9299                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9300                } else {
9301                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9302                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9303                                "Package " + pkg.packageName + " upgrade keys do not match the "
9304                                + "previously installed version");
9305                    } else {
9306                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9307                        String msg = "System package " + pkg.packageName
9308                                + " signature changed; retaining data.";
9309                        reportSettingsProblem(Log.WARN, msg);
9310                    }
9311                }
9312            } else {
9313                try {
9314                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9315                    verifySignaturesLP(signatureCheckPs, pkg);
9316                    // We just determined the app is signed correctly, so bring
9317                    // over the latest parsed certs.
9318                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9319                } catch (PackageManagerException e) {
9320                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9321                        throw e;
9322                    }
9323                    // The signature has changed, but this package is in the system
9324                    // image...  let's recover!
9325                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9326                    // However...  if this package is part of a shared user, but it
9327                    // doesn't match the signature of the shared user, let's fail.
9328                    // What this means is that you can't change the signatures
9329                    // associated with an overall shared user, which doesn't seem all
9330                    // that unreasonable.
9331                    if (signatureCheckPs.sharedUser != null) {
9332                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9333                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9334                            throw new PackageManagerException(
9335                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9336                                    "Signature mismatch for shared user: "
9337                                            + pkgSetting.sharedUser);
9338                        }
9339                    }
9340                    // File a report about this.
9341                    String msg = "System package " + pkg.packageName
9342                            + " signature changed; retaining data.";
9343                    reportSettingsProblem(Log.WARN, msg);
9344                }
9345            }
9346
9347            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9348                // This package wants to adopt ownership of permissions from
9349                // another package.
9350                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9351                    final String origName = pkg.mAdoptPermissions.get(i);
9352                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9353                    if (orig != null) {
9354                        if (verifyPackageUpdateLPr(orig, pkg)) {
9355                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9356                                    + pkg.packageName);
9357                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9358                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9359                        }
9360                    }
9361                }
9362            }
9363        }
9364
9365        pkg.applicationInfo.processName = fixProcessName(
9366                pkg.applicationInfo.packageName,
9367                pkg.applicationInfo.processName);
9368
9369        if (pkg != mPlatformPackage) {
9370            // Get all of our default paths setup
9371            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9372        }
9373
9374        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9375
9376        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9377            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9378                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9379                derivePackageAbi(
9380                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9381                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9382
9383                // Some system apps still use directory structure for native libraries
9384                // in which case we might end up not detecting abi solely based on apk
9385                // structure. Try to detect abi based on directory structure.
9386                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9387                        pkg.applicationInfo.primaryCpuAbi == null) {
9388                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9389                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9390                }
9391            } else {
9392                // This is not a first boot or an upgrade, don't bother deriving the
9393                // ABI during the scan. Instead, trust the value that was stored in the
9394                // package setting.
9395                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9396                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9397
9398                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9399
9400                if (DEBUG_ABI_SELECTION) {
9401                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9402                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9403                        pkg.applicationInfo.secondaryCpuAbi);
9404                }
9405            }
9406        } else {
9407            if ((scanFlags & SCAN_MOVE) != 0) {
9408                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9409                // but we already have this packages package info in the PackageSetting. We just
9410                // use that and derive the native library path based on the new codepath.
9411                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9412                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9413            }
9414
9415            // Set native library paths again. For moves, the path will be updated based on the
9416            // ABIs we've determined above. For non-moves, the path will be updated based on the
9417            // ABIs we determined during compilation, but the path will depend on the final
9418            // package path (after the rename away from the stage path).
9419            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9420        }
9421
9422        // This is a special case for the "system" package, where the ABI is
9423        // dictated by the zygote configuration (and init.rc). We should keep track
9424        // of this ABI so that we can deal with "normal" applications that run under
9425        // the same UID correctly.
9426        if (mPlatformPackage == pkg) {
9427            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9428                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9429        }
9430
9431        // If there's a mismatch between the abi-override in the package setting
9432        // and the abiOverride specified for the install. Warn about this because we
9433        // would've already compiled the app without taking the package setting into
9434        // account.
9435        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9436            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9437                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9438                        " for package " + pkg.packageName);
9439            }
9440        }
9441
9442        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9443        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9444        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9445
9446        // Copy the derived override back to the parsed package, so that we can
9447        // update the package settings accordingly.
9448        pkg.cpuAbiOverride = cpuAbiOverride;
9449
9450        if (DEBUG_ABI_SELECTION) {
9451            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9452                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9453                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9454        }
9455
9456        // Push the derived path down into PackageSettings so we know what to
9457        // clean up at uninstall time.
9458        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9459
9460        if (DEBUG_ABI_SELECTION) {
9461            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9462                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9463                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9464        }
9465
9466        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9467        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9468            // We don't do this here during boot because we can do it all
9469            // at once after scanning all existing packages.
9470            //
9471            // We also do this *before* we perform dexopt on this package, so that
9472            // we can avoid redundant dexopts, and also to make sure we've got the
9473            // code and package path correct.
9474            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9475        }
9476
9477        if (mFactoryTest && pkg.requestedPermissions.contains(
9478                android.Manifest.permission.FACTORY_TEST)) {
9479            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9480        }
9481
9482        if (isSystemApp(pkg)) {
9483            pkgSetting.isOrphaned = true;
9484        }
9485
9486        // Take care of first install / last update times.
9487        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9488        if (currentTime != 0) {
9489            if (pkgSetting.firstInstallTime == 0) {
9490                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9491            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9492                pkgSetting.lastUpdateTime = currentTime;
9493            }
9494        } else if (pkgSetting.firstInstallTime == 0) {
9495            // We need *something*.  Take time time stamp of the file.
9496            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9497        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9498            if (scanFileTime != pkgSetting.timeStamp) {
9499                // A package on the system image has changed; consider this
9500                // to be an update.
9501                pkgSetting.lastUpdateTime = scanFileTime;
9502            }
9503        }
9504        pkgSetting.setTimeStamp(scanFileTime);
9505
9506        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9507            if (nonMutatedPs != null) {
9508                synchronized (mPackages) {
9509                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9510                }
9511            }
9512        } else {
9513            final int userId = user == null ? 0 : user.getIdentifier();
9514            // Modify state for the given package setting
9515            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9516                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9517            if (pkgSetting.getInstantApp(userId)) {
9518                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9519            }
9520        }
9521        return pkg;
9522    }
9523
9524    /**
9525     * Applies policy to the parsed package based upon the given policy flags.
9526     * Ensures the package is in a good state.
9527     * <p>
9528     * Implementation detail: This method must NOT have any side effect. It would
9529     * ideally be static, but, it requires locks to read system state.
9530     */
9531    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9532        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9533            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9534            if (pkg.applicationInfo.isDirectBootAware()) {
9535                // we're direct boot aware; set for all components
9536                for (PackageParser.Service s : pkg.services) {
9537                    s.info.encryptionAware = s.info.directBootAware = true;
9538                }
9539                for (PackageParser.Provider p : pkg.providers) {
9540                    p.info.encryptionAware = p.info.directBootAware = true;
9541                }
9542                for (PackageParser.Activity a : pkg.activities) {
9543                    a.info.encryptionAware = a.info.directBootAware = true;
9544                }
9545                for (PackageParser.Activity r : pkg.receivers) {
9546                    r.info.encryptionAware = r.info.directBootAware = true;
9547                }
9548            }
9549        } else {
9550            // Only allow system apps to be flagged as core apps.
9551            pkg.coreApp = false;
9552            // clear flags not applicable to regular apps
9553            pkg.applicationInfo.privateFlags &=
9554                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9555            pkg.applicationInfo.privateFlags &=
9556                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9557        }
9558        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9559
9560        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9561            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9562        }
9563
9564        if (!isSystemApp(pkg)) {
9565            // Only system apps can use these features.
9566            pkg.mOriginalPackages = null;
9567            pkg.mRealPackage = null;
9568            pkg.mAdoptPermissions = null;
9569        }
9570    }
9571
9572    /**
9573     * Asserts the parsed package is valid according to the given policy. If the
9574     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9575     * <p>
9576     * Implementation detail: This method must NOT have any side effects. It would
9577     * ideally be static, but, it requires locks to read system state.
9578     *
9579     * @throws PackageManagerException If the package fails any of the validation checks
9580     */
9581    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9582            throws PackageManagerException {
9583        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9584            assertCodePolicy(pkg);
9585        }
9586
9587        if (pkg.applicationInfo.getCodePath() == null ||
9588                pkg.applicationInfo.getResourcePath() == null) {
9589            // Bail out. The resource and code paths haven't been set.
9590            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9591                    "Code and resource paths haven't been set correctly");
9592        }
9593
9594        // Make sure we're not adding any bogus keyset info
9595        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9596        ksms.assertScannedPackageValid(pkg);
9597
9598        synchronized (mPackages) {
9599            // The special "android" package can only be defined once
9600            if (pkg.packageName.equals("android")) {
9601                if (mAndroidApplication != null) {
9602                    Slog.w(TAG, "*************************************************");
9603                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9604                    Slog.w(TAG, " codePath=" + pkg.codePath);
9605                    Slog.w(TAG, "*************************************************");
9606                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9607                            "Core android package being redefined.  Skipping.");
9608                }
9609            }
9610
9611            // A package name must be unique; don't allow duplicates
9612            if (mPackages.containsKey(pkg.packageName)) {
9613                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9614                        "Application package " + pkg.packageName
9615                        + " already installed.  Skipping duplicate.");
9616            }
9617
9618            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9619                // Static libs have a synthetic package name containing the version
9620                // but we still want the base name to be unique.
9621                if (mPackages.containsKey(pkg.manifestPackageName)) {
9622                    throw new PackageManagerException(
9623                            "Duplicate static shared lib provider package");
9624                }
9625
9626                // Static shared libraries should have at least O target SDK
9627                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9628                    throw new PackageManagerException(
9629                            "Packages declaring static-shared libs must target O SDK or higher");
9630                }
9631
9632                // Package declaring static a shared lib cannot be instant apps
9633                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9634                    throw new PackageManagerException(
9635                            "Packages declaring static-shared libs cannot be instant apps");
9636                }
9637
9638                // Package declaring static a shared lib cannot be renamed since the package
9639                // name is synthetic and apps can't code around package manager internals.
9640                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9641                    throw new PackageManagerException(
9642                            "Packages declaring static-shared libs cannot be renamed");
9643                }
9644
9645                // Package declaring static a shared lib cannot declare child packages
9646                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9647                    throw new PackageManagerException(
9648                            "Packages declaring static-shared libs cannot have child packages");
9649                }
9650
9651                // Package declaring static a shared lib cannot declare dynamic libs
9652                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9653                    throw new PackageManagerException(
9654                            "Packages declaring static-shared libs cannot declare dynamic libs");
9655                }
9656
9657                // Package declaring static a shared lib cannot declare shared users
9658                if (pkg.mSharedUserId != null) {
9659                    throw new PackageManagerException(
9660                            "Packages declaring static-shared libs cannot declare shared users");
9661                }
9662
9663                // Static shared libs cannot declare activities
9664                if (!pkg.activities.isEmpty()) {
9665                    throw new PackageManagerException(
9666                            "Static shared libs cannot declare activities");
9667                }
9668
9669                // Static shared libs cannot declare services
9670                if (!pkg.services.isEmpty()) {
9671                    throw new PackageManagerException(
9672                            "Static shared libs cannot declare services");
9673                }
9674
9675                // Static shared libs cannot declare providers
9676                if (!pkg.providers.isEmpty()) {
9677                    throw new PackageManagerException(
9678                            "Static shared libs cannot declare content providers");
9679                }
9680
9681                // Static shared libs cannot declare receivers
9682                if (!pkg.receivers.isEmpty()) {
9683                    throw new PackageManagerException(
9684                            "Static shared libs cannot declare broadcast receivers");
9685                }
9686
9687                // Static shared libs cannot declare permission groups
9688                if (!pkg.permissionGroups.isEmpty()) {
9689                    throw new PackageManagerException(
9690                            "Static shared libs cannot declare permission groups");
9691                }
9692
9693                // Static shared libs cannot declare permissions
9694                if (!pkg.permissions.isEmpty()) {
9695                    throw new PackageManagerException(
9696                            "Static shared libs cannot declare permissions");
9697                }
9698
9699                // Static shared libs cannot declare protected broadcasts
9700                if (pkg.protectedBroadcasts != null) {
9701                    throw new PackageManagerException(
9702                            "Static shared libs cannot declare protected broadcasts");
9703                }
9704
9705                // Static shared libs cannot be overlay targets
9706                if (pkg.mOverlayTarget != null) {
9707                    throw new PackageManagerException(
9708                            "Static shared libs cannot be overlay targets");
9709                }
9710
9711                // The version codes must be ordered as lib versions
9712                int minVersionCode = Integer.MIN_VALUE;
9713                int maxVersionCode = Integer.MAX_VALUE;
9714
9715                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9716                        pkg.staticSharedLibName);
9717                if (versionedLib != null) {
9718                    final int versionCount = versionedLib.size();
9719                    for (int i = 0; i < versionCount; i++) {
9720                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9721                        // TODO: We will change version code to long, so in the new API it is long
9722                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9723                                .getVersionCode();
9724                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9725                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9726                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9727                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9728                        } else {
9729                            minVersionCode = maxVersionCode = libVersionCode;
9730                            break;
9731                        }
9732                    }
9733                }
9734                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9735                    throw new PackageManagerException("Static shared"
9736                            + " lib version codes must be ordered as lib versions");
9737                }
9738            }
9739
9740            // Only privileged apps and updated privileged apps can add child packages.
9741            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9742                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9743                    throw new PackageManagerException("Only privileged apps can add child "
9744                            + "packages. Ignoring package " + pkg.packageName);
9745                }
9746                final int childCount = pkg.childPackages.size();
9747                for (int i = 0; i < childCount; i++) {
9748                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9749                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9750                            childPkg.packageName)) {
9751                        throw new PackageManagerException("Can't override child of "
9752                                + "another disabled app. Ignoring package " + pkg.packageName);
9753                    }
9754                }
9755            }
9756
9757            // If we're only installing presumed-existing packages, require that the
9758            // scanned APK is both already known and at the path previously established
9759            // for it.  Previously unknown packages we pick up normally, but if we have an
9760            // a priori expectation about this package's install presence, enforce it.
9761            // With a singular exception for new system packages. When an OTA contains
9762            // a new system package, we allow the codepath to change from a system location
9763            // to the user-installed location. If we don't allow this change, any newer,
9764            // user-installed version of the application will be ignored.
9765            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9766                if (mExpectingBetter.containsKey(pkg.packageName)) {
9767                    logCriticalInfo(Log.WARN,
9768                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9769                } else {
9770                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9771                    if (known != null) {
9772                        if (DEBUG_PACKAGE_SCANNING) {
9773                            Log.d(TAG, "Examining " + pkg.codePath
9774                                    + " and requiring known paths " + known.codePathString
9775                                    + " & " + known.resourcePathString);
9776                        }
9777                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9778                                || !pkg.applicationInfo.getResourcePath().equals(
9779                                        known.resourcePathString)) {
9780                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9781                                    "Application package " + pkg.packageName
9782                                    + " found at " + pkg.applicationInfo.getCodePath()
9783                                    + " but expected at " + known.codePathString
9784                                    + "; ignoring.");
9785                        }
9786                    }
9787                }
9788            }
9789
9790            // Verify that this new package doesn't have any content providers
9791            // that conflict with existing packages.  Only do this if the
9792            // package isn't already installed, since we don't want to break
9793            // things that are installed.
9794            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9795                final int N = pkg.providers.size();
9796                int i;
9797                for (i=0; i<N; i++) {
9798                    PackageParser.Provider p = pkg.providers.get(i);
9799                    if (p.info.authority != null) {
9800                        String names[] = p.info.authority.split(";");
9801                        for (int j = 0; j < names.length; j++) {
9802                            if (mProvidersByAuthority.containsKey(names[j])) {
9803                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9804                                final String otherPackageName =
9805                                        ((other != null && other.getComponentName() != null) ?
9806                                                other.getComponentName().getPackageName() : "?");
9807                                throw new PackageManagerException(
9808                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9809                                        "Can't install because provider name " + names[j]
9810                                                + " (in package " + pkg.applicationInfo.packageName
9811                                                + ") is already used by " + otherPackageName);
9812                            }
9813                        }
9814                    }
9815                }
9816            }
9817        }
9818    }
9819
9820    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9821            int type, String declaringPackageName, int declaringVersionCode) {
9822        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9823        if (versionedLib == null) {
9824            versionedLib = new SparseArray<>();
9825            mSharedLibraries.put(name, versionedLib);
9826            if (type == SharedLibraryInfo.TYPE_STATIC) {
9827                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9828            }
9829        } else if (versionedLib.indexOfKey(version) >= 0) {
9830            return false;
9831        }
9832        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9833                version, type, declaringPackageName, declaringVersionCode);
9834        versionedLib.put(version, libEntry);
9835        return true;
9836    }
9837
9838    private boolean removeSharedLibraryLPw(String name, int version) {
9839        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9840        if (versionedLib == null) {
9841            return false;
9842        }
9843        final int libIdx = versionedLib.indexOfKey(version);
9844        if (libIdx < 0) {
9845            return false;
9846        }
9847        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9848        versionedLib.remove(version);
9849        if (versionedLib.size() <= 0) {
9850            mSharedLibraries.remove(name);
9851            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9852                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9853                        .getPackageName());
9854            }
9855        }
9856        return true;
9857    }
9858
9859    /**
9860     * Adds a scanned package to the system. When this method is finished, the package will
9861     * be available for query, resolution, etc...
9862     */
9863    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9864            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9865        final String pkgName = pkg.packageName;
9866        if (mCustomResolverComponentName != null &&
9867                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9868            setUpCustomResolverActivity(pkg);
9869        }
9870
9871        if (pkg.packageName.equals("android")) {
9872            synchronized (mPackages) {
9873                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9874                    // Set up information for our fall-back user intent resolution activity.
9875                    mPlatformPackage = pkg;
9876                    pkg.mVersionCode = mSdkVersion;
9877                    mAndroidApplication = pkg.applicationInfo;
9878                    if (!mResolverReplaced) {
9879                        mResolveActivity.applicationInfo = mAndroidApplication;
9880                        mResolveActivity.name = ResolverActivity.class.getName();
9881                        mResolveActivity.packageName = mAndroidApplication.packageName;
9882                        mResolveActivity.processName = "system:ui";
9883                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9884                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9885                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9886                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9887                        mResolveActivity.exported = true;
9888                        mResolveActivity.enabled = true;
9889                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9890                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9891                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9892                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9893                                | ActivityInfo.CONFIG_ORIENTATION
9894                                | ActivityInfo.CONFIG_KEYBOARD
9895                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9896                        mResolveInfo.activityInfo = mResolveActivity;
9897                        mResolveInfo.priority = 0;
9898                        mResolveInfo.preferredOrder = 0;
9899                        mResolveInfo.match = 0;
9900                        mResolveComponentName = new ComponentName(
9901                                mAndroidApplication.packageName, mResolveActivity.name);
9902                    }
9903                }
9904            }
9905        }
9906
9907        ArrayList<PackageParser.Package> clientLibPkgs = null;
9908        // writer
9909        synchronized (mPackages) {
9910            boolean hasStaticSharedLibs = false;
9911
9912            // Any app can add new static shared libraries
9913            if (pkg.staticSharedLibName != null) {
9914                // Static shared libs don't allow renaming as they have synthetic package
9915                // names to allow install of multiple versions, so use name from manifest.
9916                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9917                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9918                        pkg.manifestPackageName, pkg.mVersionCode)) {
9919                    hasStaticSharedLibs = true;
9920                } else {
9921                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9922                                + pkg.staticSharedLibName + " already exists; skipping");
9923                }
9924                // Static shared libs cannot be updated once installed since they
9925                // use synthetic package name which includes the version code, so
9926                // not need to update other packages's shared lib dependencies.
9927            }
9928
9929            if (!hasStaticSharedLibs
9930                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9931                // Only system apps can add new dynamic shared libraries.
9932                if (pkg.libraryNames != null) {
9933                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9934                        String name = pkg.libraryNames.get(i);
9935                        boolean allowed = false;
9936                        if (pkg.isUpdatedSystemApp()) {
9937                            // New library entries can only be added through the
9938                            // system image.  This is important to get rid of a lot
9939                            // of nasty edge cases: for example if we allowed a non-
9940                            // system update of the app to add a library, then uninstalling
9941                            // the update would make the library go away, and assumptions
9942                            // we made such as through app install filtering would now
9943                            // have allowed apps on the device which aren't compatible
9944                            // with it.  Better to just have the restriction here, be
9945                            // conservative, and create many fewer cases that can negatively
9946                            // impact the user experience.
9947                            final PackageSetting sysPs = mSettings
9948                                    .getDisabledSystemPkgLPr(pkg.packageName);
9949                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9950                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9951                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9952                                        allowed = true;
9953                                        break;
9954                                    }
9955                                }
9956                            }
9957                        } else {
9958                            allowed = true;
9959                        }
9960                        if (allowed) {
9961                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9962                                    SharedLibraryInfo.VERSION_UNDEFINED,
9963                                    SharedLibraryInfo.TYPE_DYNAMIC,
9964                                    pkg.packageName, pkg.mVersionCode)) {
9965                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9966                                        + name + " already exists; skipping");
9967                            }
9968                        } else {
9969                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9970                                    + name + " that is not declared on system image; skipping");
9971                        }
9972                    }
9973
9974                    if ((scanFlags & SCAN_BOOTING) == 0) {
9975                        // If we are not booting, we need to update any applications
9976                        // that are clients of our shared library.  If we are booting,
9977                        // this will all be done once the scan is complete.
9978                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9979                    }
9980                }
9981            }
9982        }
9983
9984        if ((scanFlags & SCAN_BOOTING) != 0) {
9985            // No apps can run during boot scan, so they don't need to be frozen
9986        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9987            // Caller asked to not kill app, so it's probably not frozen
9988        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9989            // Caller asked us to ignore frozen check for some reason; they
9990            // probably didn't know the package name
9991        } else {
9992            // We're doing major surgery on this package, so it better be frozen
9993            // right now to keep it from launching
9994            checkPackageFrozen(pkgName);
9995        }
9996
9997        // Also need to kill any apps that are dependent on the library.
9998        if (clientLibPkgs != null) {
9999            for (int i=0; i<clientLibPkgs.size(); i++) {
10000                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10001                killApplication(clientPkg.applicationInfo.packageName,
10002                        clientPkg.applicationInfo.uid, "update lib");
10003            }
10004        }
10005
10006        // writer
10007        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10008
10009        synchronized (mPackages) {
10010            // We don't expect installation to fail beyond this point
10011
10012            // Add the new setting to mSettings
10013            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10014            // Add the new setting to mPackages
10015            mPackages.put(pkg.applicationInfo.packageName, pkg);
10016            // Make sure we don't accidentally delete its data.
10017            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10018            while (iter.hasNext()) {
10019                PackageCleanItem item = iter.next();
10020                if (pkgName.equals(item.packageName)) {
10021                    iter.remove();
10022                }
10023            }
10024
10025            // Add the package's KeySets to the global KeySetManagerService
10026            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10027            ksms.addScannedPackageLPw(pkg);
10028
10029            int N = pkg.providers.size();
10030            StringBuilder r = null;
10031            int i;
10032            for (i=0; i<N; i++) {
10033                PackageParser.Provider p = pkg.providers.get(i);
10034                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10035                        p.info.processName);
10036                mProviders.addProvider(p);
10037                p.syncable = p.info.isSyncable;
10038                if (p.info.authority != null) {
10039                    String names[] = p.info.authority.split(";");
10040                    p.info.authority = null;
10041                    for (int j = 0; j < names.length; j++) {
10042                        if (j == 1 && p.syncable) {
10043                            // We only want the first authority for a provider to possibly be
10044                            // syncable, so if we already added this provider using a different
10045                            // authority clear the syncable flag. We copy the provider before
10046                            // changing it because the mProviders object contains a reference
10047                            // to a provider that we don't want to change.
10048                            // Only do this for the second authority since the resulting provider
10049                            // object can be the same for all future authorities for this provider.
10050                            p = new PackageParser.Provider(p);
10051                            p.syncable = false;
10052                        }
10053                        if (!mProvidersByAuthority.containsKey(names[j])) {
10054                            mProvidersByAuthority.put(names[j], p);
10055                            if (p.info.authority == null) {
10056                                p.info.authority = names[j];
10057                            } else {
10058                                p.info.authority = p.info.authority + ";" + names[j];
10059                            }
10060                            if (DEBUG_PACKAGE_SCANNING) {
10061                                if (chatty)
10062                                    Log.d(TAG, "Registered content provider: " + names[j]
10063                                            + ", className = " + p.info.name + ", isSyncable = "
10064                                            + p.info.isSyncable);
10065                            }
10066                        } else {
10067                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10068                            Slog.w(TAG, "Skipping provider name " + names[j] +
10069                                    " (in package " + pkg.applicationInfo.packageName +
10070                                    "): name already used by "
10071                                    + ((other != null && other.getComponentName() != null)
10072                                            ? other.getComponentName().getPackageName() : "?"));
10073                        }
10074                    }
10075                }
10076                if (chatty) {
10077                    if (r == null) {
10078                        r = new StringBuilder(256);
10079                    } else {
10080                        r.append(' ');
10081                    }
10082                    r.append(p.info.name);
10083                }
10084            }
10085            if (r != null) {
10086                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10087            }
10088
10089            N = pkg.services.size();
10090            r = null;
10091            for (i=0; i<N; i++) {
10092                PackageParser.Service s = pkg.services.get(i);
10093                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10094                        s.info.processName);
10095                mServices.addService(s);
10096                if (chatty) {
10097                    if (r == null) {
10098                        r = new StringBuilder(256);
10099                    } else {
10100                        r.append(' ');
10101                    }
10102                    r.append(s.info.name);
10103                }
10104            }
10105            if (r != null) {
10106                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10107            }
10108
10109            N = pkg.receivers.size();
10110            r = null;
10111            for (i=0; i<N; i++) {
10112                PackageParser.Activity a = pkg.receivers.get(i);
10113                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10114                        a.info.processName);
10115                mReceivers.addActivity(a, "receiver");
10116                if (chatty) {
10117                    if (r == null) {
10118                        r = new StringBuilder(256);
10119                    } else {
10120                        r.append(' ');
10121                    }
10122                    r.append(a.info.name);
10123                }
10124            }
10125            if (r != null) {
10126                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10127            }
10128
10129            N = pkg.activities.size();
10130            r = null;
10131            for (i=0; i<N; i++) {
10132                PackageParser.Activity a = pkg.activities.get(i);
10133                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10134                        a.info.processName);
10135                mActivities.addActivity(a, "activity");
10136                if (chatty) {
10137                    if (r == null) {
10138                        r = new StringBuilder(256);
10139                    } else {
10140                        r.append(' ');
10141                    }
10142                    r.append(a.info.name);
10143                }
10144            }
10145            if (r != null) {
10146                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10147            }
10148
10149            N = pkg.permissionGroups.size();
10150            r = null;
10151            for (i=0; i<N; i++) {
10152                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10153                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10154                final String curPackageName = cur == null ? null : cur.info.packageName;
10155                // Dont allow ephemeral apps to define new permission groups.
10156                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10157                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10158                            + pg.info.packageName
10159                            + " ignored: instant apps cannot define new permission groups.");
10160                    continue;
10161                }
10162                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10163                if (cur == null || isPackageUpdate) {
10164                    mPermissionGroups.put(pg.info.name, pg);
10165                    if (chatty) {
10166                        if (r == null) {
10167                            r = new StringBuilder(256);
10168                        } else {
10169                            r.append(' ');
10170                        }
10171                        if (isPackageUpdate) {
10172                            r.append("UPD:");
10173                        }
10174                        r.append(pg.info.name);
10175                    }
10176                } else {
10177                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10178                            + pg.info.packageName + " ignored: original from "
10179                            + cur.info.packageName);
10180                    if (chatty) {
10181                        if (r == null) {
10182                            r = new StringBuilder(256);
10183                        } else {
10184                            r.append(' ');
10185                        }
10186                        r.append("DUP:");
10187                        r.append(pg.info.name);
10188                    }
10189                }
10190            }
10191            if (r != null) {
10192                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10193            }
10194
10195            N = pkg.permissions.size();
10196            r = null;
10197            for (i=0; i<N; i++) {
10198                PackageParser.Permission p = pkg.permissions.get(i);
10199
10200                // Dont allow ephemeral apps to define new permissions.
10201                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10202                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10203                            + p.info.packageName
10204                            + " ignored: instant apps cannot define new permissions.");
10205                    continue;
10206                }
10207
10208                // Assume by default that we did not install this permission into the system.
10209                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10210
10211                // Now that permission groups have a special meaning, we ignore permission
10212                // groups for legacy apps to prevent unexpected behavior. In particular,
10213                // permissions for one app being granted to someone just becase they happen
10214                // to be in a group defined by another app (before this had no implications).
10215                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10216                    p.group = mPermissionGroups.get(p.info.group);
10217                    // Warn for a permission in an unknown group.
10218                    if (p.info.group != null && p.group == null) {
10219                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10220                                + p.info.packageName + " in an unknown group " + p.info.group);
10221                    }
10222                }
10223
10224                ArrayMap<String, BasePermission> permissionMap =
10225                        p.tree ? mSettings.mPermissionTrees
10226                                : mSettings.mPermissions;
10227                BasePermission bp = permissionMap.get(p.info.name);
10228
10229                // Allow system apps to redefine non-system permissions
10230                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10231                    final boolean currentOwnerIsSystem = (bp.perm != null
10232                            && isSystemApp(bp.perm.owner));
10233                    if (isSystemApp(p.owner)) {
10234                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10235                            // It's a built-in permission and no owner, take ownership now
10236                            bp.packageSetting = pkgSetting;
10237                            bp.perm = p;
10238                            bp.uid = pkg.applicationInfo.uid;
10239                            bp.sourcePackage = p.info.packageName;
10240                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10241                        } else if (!currentOwnerIsSystem) {
10242                            String msg = "New decl " + p.owner + " of permission  "
10243                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10244                            reportSettingsProblem(Log.WARN, msg);
10245                            bp = null;
10246                        }
10247                    }
10248                }
10249
10250                if (bp == null) {
10251                    bp = new BasePermission(p.info.name, p.info.packageName,
10252                            BasePermission.TYPE_NORMAL);
10253                    permissionMap.put(p.info.name, bp);
10254                }
10255
10256                if (bp.perm == null) {
10257                    if (bp.sourcePackage == null
10258                            || bp.sourcePackage.equals(p.info.packageName)) {
10259                        BasePermission tree = findPermissionTreeLP(p.info.name);
10260                        if (tree == null
10261                                || tree.sourcePackage.equals(p.info.packageName)) {
10262                            bp.packageSetting = pkgSetting;
10263                            bp.perm = p;
10264                            bp.uid = pkg.applicationInfo.uid;
10265                            bp.sourcePackage = p.info.packageName;
10266                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10267                            if (chatty) {
10268                                if (r == null) {
10269                                    r = new StringBuilder(256);
10270                                } else {
10271                                    r.append(' ');
10272                                }
10273                                r.append(p.info.name);
10274                            }
10275                        } else {
10276                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10277                                    + p.info.packageName + " ignored: base tree "
10278                                    + tree.name + " is from package "
10279                                    + tree.sourcePackage);
10280                        }
10281                    } else {
10282                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10283                                + p.info.packageName + " ignored: original from "
10284                                + bp.sourcePackage);
10285                    }
10286                } else if (chatty) {
10287                    if (r == null) {
10288                        r = new StringBuilder(256);
10289                    } else {
10290                        r.append(' ');
10291                    }
10292                    r.append("DUP:");
10293                    r.append(p.info.name);
10294                }
10295                if (bp.perm == p) {
10296                    bp.protectionLevel = p.info.protectionLevel;
10297                }
10298            }
10299
10300            if (r != null) {
10301                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10302            }
10303
10304            N = pkg.instrumentation.size();
10305            r = null;
10306            for (i=0; i<N; i++) {
10307                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10308                a.info.packageName = pkg.applicationInfo.packageName;
10309                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10310                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10311                a.info.splitNames = pkg.splitNames;
10312                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10313                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10314                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10315                a.info.dataDir = pkg.applicationInfo.dataDir;
10316                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10317                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10318                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10319                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10320                mInstrumentation.put(a.getComponentName(), a);
10321                if (chatty) {
10322                    if (r == null) {
10323                        r = new StringBuilder(256);
10324                    } else {
10325                        r.append(' ');
10326                    }
10327                    r.append(a.info.name);
10328                }
10329            }
10330            if (r != null) {
10331                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10332            }
10333
10334            if (pkg.protectedBroadcasts != null) {
10335                N = pkg.protectedBroadcasts.size();
10336                for (i=0; i<N; i++) {
10337                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10338                }
10339            }
10340        }
10341
10342        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10343    }
10344
10345    /**
10346     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10347     * is derived purely on the basis of the contents of {@code scanFile} and
10348     * {@code cpuAbiOverride}.
10349     *
10350     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10351     */
10352    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10353                                 String cpuAbiOverride, boolean extractLibs,
10354                                 File appLib32InstallDir)
10355            throws PackageManagerException {
10356        // Give ourselves some initial paths; we'll come back for another
10357        // pass once we've determined ABI below.
10358        setNativeLibraryPaths(pkg, appLib32InstallDir);
10359
10360        // We would never need to extract libs for forward-locked and external packages,
10361        // since the container service will do it for us. We shouldn't attempt to
10362        // extract libs from system app when it was not updated.
10363        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10364                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10365            extractLibs = false;
10366        }
10367
10368        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10369        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10370
10371        NativeLibraryHelper.Handle handle = null;
10372        try {
10373            handle = NativeLibraryHelper.Handle.create(pkg);
10374            // TODO(multiArch): This can be null for apps that didn't go through the
10375            // usual installation process. We can calculate it again, like we
10376            // do during install time.
10377            //
10378            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10379            // unnecessary.
10380            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10381
10382            // Null out the abis so that they can be recalculated.
10383            pkg.applicationInfo.primaryCpuAbi = null;
10384            pkg.applicationInfo.secondaryCpuAbi = null;
10385            if (isMultiArch(pkg.applicationInfo)) {
10386                // Warn if we've set an abiOverride for multi-lib packages..
10387                // By definition, we need to copy both 32 and 64 bit libraries for
10388                // such packages.
10389                if (pkg.cpuAbiOverride != null
10390                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10391                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10392                }
10393
10394                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10395                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10396                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10397                    if (extractLibs) {
10398                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10399                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10400                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10401                                useIsaSpecificSubdirs);
10402                    } else {
10403                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10404                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10405                    }
10406                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10407                }
10408
10409                maybeThrowExceptionForMultiArchCopy(
10410                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10411
10412                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10413                    if (extractLibs) {
10414                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10415                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10416                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10417                                useIsaSpecificSubdirs);
10418                    } else {
10419                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10420                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10421                    }
10422                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10423                }
10424
10425                maybeThrowExceptionForMultiArchCopy(
10426                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10427
10428                if (abi64 >= 0) {
10429                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10430                }
10431
10432                if (abi32 >= 0) {
10433                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10434                    if (abi64 >= 0) {
10435                        if (pkg.use32bitAbi) {
10436                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10437                            pkg.applicationInfo.primaryCpuAbi = abi;
10438                        } else {
10439                            pkg.applicationInfo.secondaryCpuAbi = abi;
10440                        }
10441                    } else {
10442                        pkg.applicationInfo.primaryCpuAbi = abi;
10443                    }
10444                }
10445
10446            } else {
10447                String[] abiList = (cpuAbiOverride != null) ?
10448                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10449
10450                // Enable gross and lame hacks for apps that are built with old
10451                // SDK tools. We must scan their APKs for renderscript bitcode and
10452                // not launch them if it's present. Don't bother checking on devices
10453                // that don't have 64 bit support.
10454                boolean needsRenderScriptOverride = false;
10455                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10456                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10457                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10458                    needsRenderScriptOverride = true;
10459                }
10460
10461                final int copyRet;
10462                if (extractLibs) {
10463                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10464                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10465                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10466                } else {
10467                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10468                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10469                }
10470                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10471
10472                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10473                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10474                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10475                }
10476
10477                if (copyRet >= 0) {
10478                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10479                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10480                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10481                } else if (needsRenderScriptOverride) {
10482                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10483                }
10484            }
10485        } catch (IOException ioe) {
10486            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10487        } finally {
10488            IoUtils.closeQuietly(handle);
10489        }
10490
10491        // Now that we've calculated the ABIs and determined if it's an internal app,
10492        // we will go ahead and populate the nativeLibraryPath.
10493        setNativeLibraryPaths(pkg, appLib32InstallDir);
10494    }
10495
10496    /**
10497     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10498     * i.e, so that all packages can be run inside a single process if required.
10499     *
10500     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10501     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10502     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10503     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10504     * updating a package that belongs to a shared user.
10505     *
10506     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10507     * adds unnecessary complexity.
10508     */
10509    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10510            PackageParser.Package scannedPackage) {
10511        String requiredInstructionSet = null;
10512        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10513            requiredInstructionSet = VMRuntime.getInstructionSet(
10514                     scannedPackage.applicationInfo.primaryCpuAbi);
10515        }
10516
10517        PackageSetting requirer = null;
10518        for (PackageSetting ps : packagesForUser) {
10519            // If packagesForUser contains scannedPackage, we skip it. This will happen
10520            // when scannedPackage is an update of an existing package. Without this check,
10521            // we will never be able to change the ABI of any package belonging to a shared
10522            // user, even if it's compatible with other packages.
10523            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10524                if (ps.primaryCpuAbiString == null) {
10525                    continue;
10526                }
10527
10528                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10529                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10530                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10531                    // this but there's not much we can do.
10532                    String errorMessage = "Instruction set mismatch, "
10533                            + ((requirer == null) ? "[caller]" : requirer)
10534                            + " requires " + requiredInstructionSet + " whereas " + ps
10535                            + " requires " + instructionSet;
10536                    Slog.w(TAG, errorMessage);
10537                }
10538
10539                if (requiredInstructionSet == null) {
10540                    requiredInstructionSet = instructionSet;
10541                    requirer = ps;
10542                }
10543            }
10544        }
10545
10546        if (requiredInstructionSet != null) {
10547            String adjustedAbi;
10548            if (requirer != null) {
10549                // requirer != null implies that either scannedPackage was null or that scannedPackage
10550                // did not require an ABI, in which case we have to adjust scannedPackage to match
10551                // the ABI of the set (which is the same as requirer's ABI)
10552                adjustedAbi = requirer.primaryCpuAbiString;
10553                if (scannedPackage != null) {
10554                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10555                }
10556            } else {
10557                // requirer == null implies that we're updating all ABIs in the set to
10558                // match scannedPackage.
10559                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10560            }
10561
10562            for (PackageSetting ps : packagesForUser) {
10563                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10564                    if (ps.primaryCpuAbiString != null) {
10565                        continue;
10566                    }
10567
10568                    ps.primaryCpuAbiString = adjustedAbi;
10569                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10570                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10571                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10572                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10573                                + " (requirer="
10574                                + (requirer == null ? "null" : requirer.pkg.packageName)
10575                                + ", scannedPackage="
10576                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10577                                + ")");
10578                        try {
10579                            mInstaller.rmdex(ps.codePathString,
10580                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10581                        } catch (InstallerException ignored) {
10582                        }
10583                    }
10584                }
10585            }
10586        }
10587    }
10588
10589    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10590        synchronized (mPackages) {
10591            mResolverReplaced = true;
10592            // Set up information for custom user intent resolution activity.
10593            mResolveActivity.applicationInfo = pkg.applicationInfo;
10594            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10595            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10596            mResolveActivity.processName = pkg.applicationInfo.packageName;
10597            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10598            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10599                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10600            mResolveActivity.theme = 0;
10601            mResolveActivity.exported = true;
10602            mResolveActivity.enabled = true;
10603            mResolveInfo.activityInfo = mResolveActivity;
10604            mResolveInfo.priority = 0;
10605            mResolveInfo.preferredOrder = 0;
10606            mResolveInfo.match = 0;
10607            mResolveComponentName = mCustomResolverComponentName;
10608            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10609                    mResolveComponentName);
10610        }
10611    }
10612
10613    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10614        if (installerComponent == null) {
10615            if (DEBUG_EPHEMERAL) {
10616                Slog.d(TAG, "Clear ephemeral installer activity");
10617            }
10618            mInstantAppInstallerActivity.applicationInfo = null;
10619            return;
10620        }
10621
10622        if (DEBUG_EPHEMERAL) {
10623            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10624        }
10625        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10626        // Set up information for ephemeral installer activity
10627        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10628        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10629        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10630        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10631        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10632        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10633                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10634        mInstantAppInstallerActivity.theme = 0;
10635        mInstantAppInstallerActivity.exported = true;
10636        mInstantAppInstallerActivity.enabled = true;
10637        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10638        mInstantAppInstallerInfo.priority = 0;
10639        mInstantAppInstallerInfo.preferredOrder = 1;
10640        mInstantAppInstallerInfo.isDefault = true;
10641        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10642                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10643    }
10644
10645    private static String calculateBundledApkRoot(final String codePathString) {
10646        final File codePath = new File(codePathString);
10647        final File codeRoot;
10648        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10649            codeRoot = Environment.getRootDirectory();
10650        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10651            codeRoot = Environment.getOemDirectory();
10652        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10653            codeRoot = Environment.getVendorDirectory();
10654        } else {
10655            // Unrecognized code path; take its top real segment as the apk root:
10656            // e.g. /something/app/blah.apk => /something
10657            try {
10658                File f = codePath.getCanonicalFile();
10659                File parent = f.getParentFile();    // non-null because codePath is a file
10660                File tmp;
10661                while ((tmp = parent.getParentFile()) != null) {
10662                    f = parent;
10663                    parent = tmp;
10664                }
10665                codeRoot = f;
10666                Slog.w(TAG, "Unrecognized code path "
10667                        + codePath + " - using " + codeRoot);
10668            } catch (IOException e) {
10669                // Can't canonicalize the code path -- shenanigans?
10670                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10671                return Environment.getRootDirectory().getPath();
10672            }
10673        }
10674        return codeRoot.getPath();
10675    }
10676
10677    /**
10678     * Derive and set the location of native libraries for the given package,
10679     * which varies depending on where and how the package was installed.
10680     */
10681    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10682        final ApplicationInfo info = pkg.applicationInfo;
10683        final String codePath = pkg.codePath;
10684        final File codeFile = new File(codePath);
10685        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10686        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10687
10688        info.nativeLibraryRootDir = null;
10689        info.nativeLibraryRootRequiresIsa = false;
10690        info.nativeLibraryDir = null;
10691        info.secondaryNativeLibraryDir = null;
10692
10693        if (isApkFile(codeFile)) {
10694            // Monolithic install
10695            if (bundledApp) {
10696                // If "/system/lib64/apkname" exists, assume that is the per-package
10697                // native library directory to use; otherwise use "/system/lib/apkname".
10698                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10699                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10700                        getPrimaryInstructionSet(info));
10701
10702                // This is a bundled system app so choose the path based on the ABI.
10703                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10704                // is just the default path.
10705                final String apkName = deriveCodePathName(codePath);
10706                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10707                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10708                        apkName).getAbsolutePath();
10709
10710                if (info.secondaryCpuAbi != null) {
10711                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10712                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10713                            secondaryLibDir, apkName).getAbsolutePath();
10714                }
10715            } else if (asecApp) {
10716                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10717                        .getAbsolutePath();
10718            } else {
10719                final String apkName = deriveCodePathName(codePath);
10720                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10721                        .getAbsolutePath();
10722            }
10723
10724            info.nativeLibraryRootRequiresIsa = false;
10725            info.nativeLibraryDir = info.nativeLibraryRootDir;
10726        } else {
10727            // Cluster install
10728            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10729            info.nativeLibraryRootRequiresIsa = true;
10730
10731            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10732                    getPrimaryInstructionSet(info)).getAbsolutePath();
10733
10734            if (info.secondaryCpuAbi != null) {
10735                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10736                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10737            }
10738        }
10739    }
10740
10741    /**
10742     * Calculate the abis and roots for a bundled app. These can uniquely
10743     * be determined from the contents of the system partition, i.e whether
10744     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10745     * of this information, and instead assume that the system was built
10746     * sensibly.
10747     */
10748    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10749                                           PackageSetting pkgSetting) {
10750        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10751
10752        // If "/system/lib64/apkname" exists, assume that is the per-package
10753        // native library directory to use; otherwise use "/system/lib/apkname".
10754        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10755        setBundledAppAbi(pkg, apkRoot, apkName);
10756        // pkgSetting might be null during rescan following uninstall of updates
10757        // to a bundled app, so accommodate that possibility.  The settings in
10758        // that case will be established later from the parsed package.
10759        //
10760        // If the settings aren't null, sync them up with what we've just derived.
10761        // note that apkRoot isn't stored in the package settings.
10762        if (pkgSetting != null) {
10763            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10764            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10765        }
10766    }
10767
10768    /**
10769     * Deduces the ABI of a bundled app and sets the relevant fields on the
10770     * parsed pkg object.
10771     *
10772     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10773     *        under which system libraries are installed.
10774     * @param apkName the name of the installed package.
10775     */
10776    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10777        final File codeFile = new File(pkg.codePath);
10778
10779        final boolean has64BitLibs;
10780        final boolean has32BitLibs;
10781        if (isApkFile(codeFile)) {
10782            // Monolithic install
10783            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10784            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10785        } else {
10786            // Cluster install
10787            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10788            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10789                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10790                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10791                has64BitLibs = (new File(rootDir, isa)).exists();
10792            } else {
10793                has64BitLibs = false;
10794            }
10795            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10796                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10797                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10798                has32BitLibs = (new File(rootDir, isa)).exists();
10799            } else {
10800                has32BitLibs = false;
10801            }
10802        }
10803
10804        if (has64BitLibs && !has32BitLibs) {
10805            // The package has 64 bit libs, but not 32 bit libs. Its primary
10806            // ABI should be 64 bit. We can safely assume here that the bundled
10807            // native libraries correspond to the most preferred ABI in the list.
10808
10809            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10810            pkg.applicationInfo.secondaryCpuAbi = null;
10811        } else if (has32BitLibs && !has64BitLibs) {
10812            // The package has 32 bit libs but not 64 bit libs. Its primary
10813            // ABI should be 32 bit.
10814
10815            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10816            pkg.applicationInfo.secondaryCpuAbi = null;
10817        } else if (has32BitLibs && has64BitLibs) {
10818            // The application has both 64 and 32 bit bundled libraries. We check
10819            // here that the app declares multiArch support, and warn if it doesn't.
10820            //
10821            // We will be lenient here and record both ABIs. The primary will be the
10822            // ABI that's higher on the list, i.e, a device that's configured to prefer
10823            // 64 bit apps will see a 64 bit primary ABI,
10824
10825            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10826                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10827            }
10828
10829            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10830                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10831                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10832            } else {
10833                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10834                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10835            }
10836        } else {
10837            pkg.applicationInfo.primaryCpuAbi = null;
10838            pkg.applicationInfo.secondaryCpuAbi = null;
10839        }
10840    }
10841
10842    private void killApplication(String pkgName, int appId, String reason) {
10843        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10844    }
10845
10846    private void killApplication(String pkgName, int appId, int userId, String reason) {
10847        // Request the ActivityManager to kill the process(only for existing packages)
10848        // so that we do not end up in a confused state while the user is still using the older
10849        // version of the application while the new one gets installed.
10850        final long token = Binder.clearCallingIdentity();
10851        try {
10852            IActivityManager am = ActivityManager.getService();
10853            if (am != null) {
10854                try {
10855                    am.killApplication(pkgName, appId, userId, reason);
10856                } catch (RemoteException e) {
10857                }
10858            }
10859        } finally {
10860            Binder.restoreCallingIdentity(token);
10861        }
10862    }
10863
10864    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10865        // Remove the parent package setting
10866        PackageSetting ps = (PackageSetting) pkg.mExtras;
10867        if (ps != null) {
10868            removePackageLI(ps, chatty);
10869        }
10870        // Remove the child package setting
10871        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10872        for (int i = 0; i < childCount; i++) {
10873            PackageParser.Package childPkg = pkg.childPackages.get(i);
10874            ps = (PackageSetting) childPkg.mExtras;
10875            if (ps != null) {
10876                removePackageLI(ps, chatty);
10877            }
10878        }
10879    }
10880
10881    void removePackageLI(PackageSetting ps, boolean chatty) {
10882        if (DEBUG_INSTALL) {
10883            if (chatty)
10884                Log.d(TAG, "Removing package " + ps.name);
10885        }
10886
10887        // writer
10888        synchronized (mPackages) {
10889            mPackages.remove(ps.name);
10890            final PackageParser.Package pkg = ps.pkg;
10891            if (pkg != null) {
10892                cleanPackageDataStructuresLILPw(pkg, chatty);
10893            }
10894        }
10895    }
10896
10897    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10898        if (DEBUG_INSTALL) {
10899            if (chatty)
10900                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10901        }
10902
10903        // writer
10904        synchronized (mPackages) {
10905            // Remove the parent package
10906            mPackages.remove(pkg.applicationInfo.packageName);
10907            cleanPackageDataStructuresLILPw(pkg, chatty);
10908
10909            // Remove the child packages
10910            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10911            for (int i = 0; i < childCount; i++) {
10912                PackageParser.Package childPkg = pkg.childPackages.get(i);
10913                mPackages.remove(childPkg.applicationInfo.packageName);
10914                cleanPackageDataStructuresLILPw(childPkg, chatty);
10915            }
10916        }
10917    }
10918
10919    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10920        int N = pkg.providers.size();
10921        StringBuilder r = null;
10922        int i;
10923        for (i=0; i<N; i++) {
10924            PackageParser.Provider p = pkg.providers.get(i);
10925            mProviders.removeProvider(p);
10926            if (p.info.authority == null) {
10927
10928                /* There was another ContentProvider with this authority when
10929                 * this app was installed so this authority is null,
10930                 * Ignore it as we don't have to unregister the provider.
10931                 */
10932                continue;
10933            }
10934            String names[] = p.info.authority.split(";");
10935            for (int j = 0; j < names.length; j++) {
10936                if (mProvidersByAuthority.get(names[j]) == p) {
10937                    mProvidersByAuthority.remove(names[j]);
10938                    if (DEBUG_REMOVE) {
10939                        if (chatty)
10940                            Log.d(TAG, "Unregistered content provider: " + names[j]
10941                                    + ", className = " + p.info.name + ", isSyncable = "
10942                                    + p.info.isSyncable);
10943                    }
10944                }
10945            }
10946            if (DEBUG_REMOVE && chatty) {
10947                if (r == null) {
10948                    r = new StringBuilder(256);
10949                } else {
10950                    r.append(' ');
10951                }
10952                r.append(p.info.name);
10953            }
10954        }
10955        if (r != null) {
10956            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10957        }
10958
10959        N = pkg.services.size();
10960        r = null;
10961        for (i=0; i<N; i++) {
10962            PackageParser.Service s = pkg.services.get(i);
10963            mServices.removeService(s);
10964            if (chatty) {
10965                if (r == null) {
10966                    r = new StringBuilder(256);
10967                } else {
10968                    r.append(' ');
10969                }
10970                r.append(s.info.name);
10971            }
10972        }
10973        if (r != null) {
10974            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10975        }
10976
10977        N = pkg.receivers.size();
10978        r = null;
10979        for (i=0; i<N; i++) {
10980            PackageParser.Activity a = pkg.receivers.get(i);
10981            mReceivers.removeActivity(a, "receiver");
10982            if (DEBUG_REMOVE && chatty) {
10983                if (r == null) {
10984                    r = new StringBuilder(256);
10985                } else {
10986                    r.append(' ');
10987                }
10988                r.append(a.info.name);
10989            }
10990        }
10991        if (r != null) {
10992            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10993        }
10994
10995        N = pkg.activities.size();
10996        r = null;
10997        for (i=0; i<N; i++) {
10998            PackageParser.Activity a = pkg.activities.get(i);
10999            mActivities.removeActivity(a, "activity");
11000            if (DEBUG_REMOVE && chatty) {
11001                if (r == null) {
11002                    r = new StringBuilder(256);
11003                } else {
11004                    r.append(' ');
11005                }
11006                r.append(a.info.name);
11007            }
11008        }
11009        if (r != null) {
11010            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11011        }
11012
11013        N = pkg.permissions.size();
11014        r = null;
11015        for (i=0; i<N; i++) {
11016            PackageParser.Permission p = pkg.permissions.get(i);
11017            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11018            if (bp == null) {
11019                bp = mSettings.mPermissionTrees.get(p.info.name);
11020            }
11021            if (bp != null && bp.perm == p) {
11022                bp.perm = null;
11023                if (DEBUG_REMOVE && chatty) {
11024                    if (r == null) {
11025                        r = new StringBuilder(256);
11026                    } else {
11027                        r.append(' ');
11028                    }
11029                    r.append(p.info.name);
11030                }
11031            }
11032            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11033                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11034                if (appOpPkgs != null) {
11035                    appOpPkgs.remove(pkg.packageName);
11036                }
11037            }
11038        }
11039        if (r != null) {
11040            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11041        }
11042
11043        N = pkg.requestedPermissions.size();
11044        r = null;
11045        for (i=0; i<N; i++) {
11046            String perm = pkg.requestedPermissions.get(i);
11047            BasePermission bp = mSettings.mPermissions.get(perm);
11048            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11049                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11050                if (appOpPkgs != null) {
11051                    appOpPkgs.remove(pkg.packageName);
11052                    if (appOpPkgs.isEmpty()) {
11053                        mAppOpPermissionPackages.remove(perm);
11054                    }
11055                }
11056            }
11057        }
11058        if (r != null) {
11059            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11060        }
11061
11062        N = pkg.instrumentation.size();
11063        r = null;
11064        for (i=0; i<N; i++) {
11065            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11066            mInstrumentation.remove(a.getComponentName());
11067            if (DEBUG_REMOVE && chatty) {
11068                if (r == null) {
11069                    r = new StringBuilder(256);
11070                } else {
11071                    r.append(' ');
11072                }
11073                r.append(a.info.name);
11074            }
11075        }
11076        if (r != null) {
11077            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11078        }
11079
11080        r = null;
11081        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11082            // Only system apps can hold shared libraries.
11083            if (pkg.libraryNames != null) {
11084                for (i = 0; i < pkg.libraryNames.size(); i++) {
11085                    String name = pkg.libraryNames.get(i);
11086                    if (removeSharedLibraryLPw(name, 0)) {
11087                        if (DEBUG_REMOVE && chatty) {
11088                            if (r == null) {
11089                                r = new StringBuilder(256);
11090                            } else {
11091                                r.append(' ');
11092                            }
11093                            r.append(name);
11094                        }
11095                    }
11096                }
11097            }
11098        }
11099
11100        r = null;
11101
11102        // Any package can hold static shared libraries.
11103        if (pkg.staticSharedLibName != null) {
11104            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11105                if (DEBUG_REMOVE && chatty) {
11106                    if (r == null) {
11107                        r = new StringBuilder(256);
11108                    } else {
11109                        r.append(' ');
11110                    }
11111                    r.append(pkg.staticSharedLibName);
11112                }
11113            }
11114        }
11115
11116        if (r != null) {
11117            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11118        }
11119    }
11120
11121    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11122        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11123            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11124                return true;
11125            }
11126        }
11127        return false;
11128    }
11129
11130    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11131    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11132    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11133
11134    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11135        // Update the parent permissions
11136        updatePermissionsLPw(pkg.packageName, pkg, flags);
11137        // Update the child permissions
11138        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11139        for (int i = 0; i < childCount; i++) {
11140            PackageParser.Package childPkg = pkg.childPackages.get(i);
11141            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11142        }
11143    }
11144
11145    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11146            int flags) {
11147        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11148        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11149    }
11150
11151    private void updatePermissionsLPw(String changingPkg,
11152            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11153        // Make sure there are no dangling permission trees.
11154        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11155        while (it.hasNext()) {
11156            final BasePermission bp = it.next();
11157            if (bp.packageSetting == null) {
11158                // We may not yet have parsed the package, so just see if
11159                // we still know about its settings.
11160                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11161            }
11162            if (bp.packageSetting == null) {
11163                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11164                        + " from package " + bp.sourcePackage);
11165                it.remove();
11166            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11167                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11168                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11169                            + " from package " + bp.sourcePackage);
11170                    flags |= UPDATE_PERMISSIONS_ALL;
11171                    it.remove();
11172                }
11173            }
11174        }
11175
11176        // Make sure all dynamic permissions have been assigned to a package,
11177        // and make sure there are no dangling permissions.
11178        it = mSettings.mPermissions.values().iterator();
11179        while (it.hasNext()) {
11180            final BasePermission bp = it.next();
11181            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11182                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11183                        + bp.name + " pkg=" + bp.sourcePackage
11184                        + " info=" + bp.pendingInfo);
11185                if (bp.packageSetting == null && bp.pendingInfo != null) {
11186                    final BasePermission tree = findPermissionTreeLP(bp.name);
11187                    if (tree != null && tree.perm != null) {
11188                        bp.packageSetting = tree.packageSetting;
11189                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11190                                new PermissionInfo(bp.pendingInfo));
11191                        bp.perm.info.packageName = tree.perm.info.packageName;
11192                        bp.perm.info.name = bp.name;
11193                        bp.uid = tree.uid;
11194                    }
11195                }
11196            }
11197            if (bp.packageSetting == null) {
11198                // We may not yet have parsed the package, so just see if
11199                // we still know about its settings.
11200                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11201            }
11202            if (bp.packageSetting == null) {
11203                Slog.w(TAG, "Removing dangling permission: " + bp.name
11204                        + " from package " + bp.sourcePackage);
11205                it.remove();
11206            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11207                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11208                    Slog.i(TAG, "Removing old permission: " + bp.name
11209                            + " from package " + bp.sourcePackage);
11210                    flags |= UPDATE_PERMISSIONS_ALL;
11211                    it.remove();
11212                }
11213            }
11214        }
11215
11216        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11217        // Now update the permissions for all packages, in particular
11218        // replace the granted permissions of the system packages.
11219        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11220            for (PackageParser.Package pkg : mPackages.values()) {
11221                if (pkg != pkgInfo) {
11222                    // Only replace for packages on requested volume
11223                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11224                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11225                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11226                    grantPermissionsLPw(pkg, replace, changingPkg);
11227                }
11228            }
11229        }
11230
11231        if (pkgInfo != null) {
11232            // Only replace for packages on requested volume
11233            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11234            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11235                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11236            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11237        }
11238        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11239    }
11240
11241    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11242            String packageOfInterest) {
11243        // IMPORTANT: There are two types of permissions: install and runtime.
11244        // Install time permissions are granted when the app is installed to
11245        // all device users and users added in the future. Runtime permissions
11246        // are granted at runtime explicitly to specific users. Normal and signature
11247        // protected permissions are install time permissions. Dangerous permissions
11248        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11249        // otherwise they are runtime permissions. This function does not manage
11250        // runtime permissions except for the case an app targeting Lollipop MR1
11251        // being upgraded to target a newer SDK, in which case dangerous permissions
11252        // are transformed from install time to runtime ones.
11253
11254        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11255        if (ps == null) {
11256            return;
11257        }
11258
11259        PermissionsState permissionsState = ps.getPermissionsState();
11260        PermissionsState origPermissions = permissionsState;
11261
11262        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11263
11264        boolean runtimePermissionsRevoked = false;
11265        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11266
11267        boolean changedInstallPermission = false;
11268
11269        if (replace) {
11270            ps.installPermissionsFixed = false;
11271            if (!ps.isSharedUser()) {
11272                origPermissions = new PermissionsState(permissionsState);
11273                permissionsState.reset();
11274            } else {
11275                // We need to know only about runtime permission changes since the
11276                // calling code always writes the install permissions state but
11277                // the runtime ones are written only if changed. The only cases of
11278                // changed runtime permissions here are promotion of an install to
11279                // runtime and revocation of a runtime from a shared user.
11280                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11281                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11282                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11283                    runtimePermissionsRevoked = true;
11284                }
11285            }
11286        }
11287
11288        permissionsState.setGlobalGids(mGlobalGids);
11289
11290        final int N = pkg.requestedPermissions.size();
11291        for (int i=0; i<N; i++) {
11292            final String name = pkg.requestedPermissions.get(i);
11293            final BasePermission bp = mSettings.mPermissions.get(name);
11294
11295            if (DEBUG_INSTALL) {
11296                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11297            }
11298
11299            if (bp == null || bp.packageSetting == null) {
11300                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11301                    Slog.w(TAG, "Unknown permission " + name
11302                            + " in package " + pkg.packageName);
11303                }
11304                continue;
11305            }
11306
11307
11308            // Limit ephemeral apps to ephemeral allowed permissions.
11309            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11310                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11311                        + pkg.packageName);
11312                continue;
11313            }
11314
11315            final String perm = bp.name;
11316            boolean allowedSig = false;
11317            int grant = GRANT_DENIED;
11318
11319            // Keep track of app op permissions.
11320            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11321                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11322                if (pkgs == null) {
11323                    pkgs = new ArraySet<>();
11324                    mAppOpPermissionPackages.put(bp.name, pkgs);
11325                }
11326                pkgs.add(pkg.packageName);
11327            }
11328
11329            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11330            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11331                    >= Build.VERSION_CODES.M;
11332            switch (level) {
11333                case PermissionInfo.PROTECTION_NORMAL: {
11334                    // For all apps normal permissions are install time ones.
11335                    grant = GRANT_INSTALL;
11336                } break;
11337
11338                case PermissionInfo.PROTECTION_DANGEROUS: {
11339                    // If a permission review is required for legacy apps we represent
11340                    // their permissions as always granted runtime ones since we need
11341                    // to keep the review required permission flag per user while an
11342                    // install permission's state is shared across all users.
11343                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11344                        // For legacy apps dangerous permissions are install time ones.
11345                        grant = GRANT_INSTALL;
11346                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11347                        // For legacy apps that became modern, install becomes runtime.
11348                        grant = GRANT_UPGRADE;
11349                    } else if (mPromoteSystemApps
11350                            && isSystemApp(ps)
11351                            && mExistingSystemPackages.contains(ps.name)) {
11352                        // For legacy system apps, install becomes runtime.
11353                        // We cannot check hasInstallPermission() for system apps since those
11354                        // permissions were granted implicitly and not persisted pre-M.
11355                        grant = GRANT_UPGRADE;
11356                    } else {
11357                        // For modern apps keep runtime permissions unchanged.
11358                        grant = GRANT_RUNTIME;
11359                    }
11360                } break;
11361
11362                case PermissionInfo.PROTECTION_SIGNATURE: {
11363                    // For all apps signature permissions are install time ones.
11364                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11365                    if (allowedSig) {
11366                        grant = GRANT_INSTALL;
11367                    }
11368                } break;
11369            }
11370
11371            if (DEBUG_INSTALL) {
11372                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11373            }
11374
11375            if (grant != GRANT_DENIED) {
11376                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11377                    // If this is an existing, non-system package, then
11378                    // we can't add any new permissions to it.
11379                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11380                        // Except...  if this is a permission that was added
11381                        // to the platform (note: need to only do this when
11382                        // updating the platform).
11383                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11384                            grant = GRANT_DENIED;
11385                        }
11386                    }
11387                }
11388
11389                switch (grant) {
11390                    case GRANT_INSTALL: {
11391                        // Revoke this as runtime permission to handle the case of
11392                        // a runtime permission being downgraded to an install one.
11393                        // Also in permission review mode we keep dangerous permissions
11394                        // for legacy apps
11395                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11396                            if (origPermissions.getRuntimePermissionState(
11397                                    bp.name, userId) != null) {
11398                                // Revoke the runtime permission and clear the flags.
11399                                origPermissions.revokeRuntimePermission(bp, userId);
11400                                origPermissions.updatePermissionFlags(bp, userId,
11401                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11402                                // If we revoked a permission permission, we have to write.
11403                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11404                                        changedRuntimePermissionUserIds, userId);
11405                            }
11406                        }
11407                        // Grant an install permission.
11408                        if (permissionsState.grantInstallPermission(bp) !=
11409                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11410                            changedInstallPermission = true;
11411                        }
11412                    } break;
11413
11414                    case GRANT_RUNTIME: {
11415                        // Grant previously granted runtime permissions.
11416                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11417                            PermissionState permissionState = origPermissions
11418                                    .getRuntimePermissionState(bp.name, userId);
11419                            int flags = permissionState != null
11420                                    ? permissionState.getFlags() : 0;
11421                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11422                                // Don't propagate the permission in a permission review mode if
11423                                // the former was revoked, i.e. marked to not propagate on upgrade.
11424                                // Note that in a permission review mode install permissions are
11425                                // represented as constantly granted runtime ones since we need to
11426                                // keep a per user state associated with the permission. Also the
11427                                // revoke on upgrade flag is no longer applicable and is reset.
11428                                final boolean revokeOnUpgrade = (flags & PackageManager
11429                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11430                                if (revokeOnUpgrade) {
11431                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11432                                    // Since we changed the flags, we have to write.
11433                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11434                                            changedRuntimePermissionUserIds, userId);
11435                                }
11436                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11437                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11438                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11439                                        // If we cannot put the permission as it was,
11440                                        // we have to write.
11441                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11442                                                changedRuntimePermissionUserIds, userId);
11443                                    }
11444                                }
11445
11446                                // If the app supports runtime permissions no need for a review.
11447                                if (mPermissionReviewRequired
11448                                        && appSupportsRuntimePermissions
11449                                        && (flags & PackageManager
11450                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11451                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11452                                    // Since we changed the flags, we have to write.
11453                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11454                                            changedRuntimePermissionUserIds, userId);
11455                                }
11456                            } else if (mPermissionReviewRequired
11457                                    && !appSupportsRuntimePermissions) {
11458                                // For legacy apps that need a permission review, every new
11459                                // runtime permission is granted but it is pending a review.
11460                                // We also need to review only platform defined runtime
11461                                // permissions as these are the only ones the platform knows
11462                                // how to disable the API to simulate revocation as legacy
11463                                // apps don't expect to run with revoked permissions.
11464                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11465                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11466                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11467                                        // We changed the flags, hence have to write.
11468                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11469                                                changedRuntimePermissionUserIds, userId);
11470                                    }
11471                                }
11472                                if (permissionsState.grantRuntimePermission(bp, userId)
11473                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11474                                    // We changed the permission, hence have to write.
11475                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11476                                            changedRuntimePermissionUserIds, userId);
11477                                }
11478                            }
11479                            // Propagate the permission flags.
11480                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11481                        }
11482                    } break;
11483
11484                    case GRANT_UPGRADE: {
11485                        // Grant runtime permissions for a previously held install permission.
11486                        PermissionState permissionState = origPermissions
11487                                .getInstallPermissionState(bp.name);
11488                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11489
11490                        if (origPermissions.revokeInstallPermission(bp)
11491                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11492                            // We will be transferring the permission flags, so clear them.
11493                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11494                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11495                            changedInstallPermission = true;
11496                        }
11497
11498                        // If the permission is not to be promoted to runtime we ignore it and
11499                        // also its other flags as they are not applicable to install permissions.
11500                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11501                            for (int userId : currentUserIds) {
11502                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11503                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11504                                    // Transfer the permission flags.
11505                                    permissionsState.updatePermissionFlags(bp, userId,
11506                                            flags, flags);
11507                                    // If we granted the permission, we have to write.
11508                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11509                                            changedRuntimePermissionUserIds, userId);
11510                                }
11511                            }
11512                        }
11513                    } break;
11514
11515                    default: {
11516                        if (packageOfInterest == null
11517                                || packageOfInterest.equals(pkg.packageName)) {
11518                            Slog.w(TAG, "Not granting permission " + perm
11519                                    + " to package " + pkg.packageName
11520                                    + " because it was previously installed without");
11521                        }
11522                    } break;
11523                }
11524            } else {
11525                if (permissionsState.revokeInstallPermission(bp) !=
11526                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11527                    // Also drop the permission flags.
11528                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11529                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11530                    changedInstallPermission = true;
11531                    Slog.i(TAG, "Un-granting permission " + perm
11532                            + " from package " + pkg.packageName
11533                            + " (protectionLevel=" + bp.protectionLevel
11534                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11535                            + ")");
11536                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11537                    // Don't print warning for app op permissions, since it is fine for them
11538                    // not to be granted, there is a UI for the user to decide.
11539                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11540                        Slog.w(TAG, "Not granting permission " + perm
11541                                + " to package " + pkg.packageName
11542                                + " (protectionLevel=" + bp.protectionLevel
11543                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11544                                + ")");
11545                    }
11546                }
11547            }
11548        }
11549
11550        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11551                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11552            // This is the first that we have heard about this package, so the
11553            // permissions we have now selected are fixed until explicitly
11554            // changed.
11555            ps.installPermissionsFixed = true;
11556        }
11557
11558        // Persist the runtime permissions state for users with changes. If permissions
11559        // were revoked because no app in the shared user declares them we have to
11560        // write synchronously to avoid losing runtime permissions state.
11561        for (int userId : changedRuntimePermissionUserIds) {
11562            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11563        }
11564    }
11565
11566    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11567        boolean allowed = false;
11568        final int NP = PackageParser.NEW_PERMISSIONS.length;
11569        for (int ip=0; ip<NP; ip++) {
11570            final PackageParser.NewPermissionInfo npi
11571                    = PackageParser.NEW_PERMISSIONS[ip];
11572            if (npi.name.equals(perm)
11573                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11574                allowed = true;
11575                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11576                        + pkg.packageName);
11577                break;
11578            }
11579        }
11580        return allowed;
11581    }
11582
11583    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11584            BasePermission bp, PermissionsState origPermissions) {
11585        boolean privilegedPermission = (bp.protectionLevel
11586                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11587        boolean privappPermissionsDisable =
11588                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11589        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11590        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11591        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11592                && !platformPackage && platformPermission) {
11593            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11594                    .getPrivAppPermissions(pkg.packageName);
11595            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11596            if (!whitelisted) {
11597                Slog.w(TAG, "Privileged permission " + perm + " for package "
11598                        + pkg.packageName + " - not in privapp-permissions whitelist");
11599                // Only report violations for apps on system image
11600                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11601                    if (mPrivappPermissionsViolations == null) {
11602                        mPrivappPermissionsViolations = new ArraySet<>();
11603                    }
11604                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11605                }
11606                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11607                    return false;
11608                }
11609            }
11610        }
11611        boolean allowed = (compareSignatures(
11612                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11613                        == PackageManager.SIGNATURE_MATCH)
11614                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11615                        == PackageManager.SIGNATURE_MATCH);
11616        if (!allowed && privilegedPermission) {
11617            if (isSystemApp(pkg)) {
11618                // For updated system applications, a system permission
11619                // is granted only if it had been defined by the original application.
11620                if (pkg.isUpdatedSystemApp()) {
11621                    final PackageSetting sysPs = mSettings
11622                            .getDisabledSystemPkgLPr(pkg.packageName);
11623                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11624                        // If the original was granted this permission, we take
11625                        // that grant decision as read and propagate it to the
11626                        // update.
11627                        if (sysPs.isPrivileged()) {
11628                            allowed = true;
11629                        }
11630                    } else {
11631                        // The system apk may have been updated with an older
11632                        // version of the one on the data partition, but which
11633                        // granted a new system permission that it didn't have
11634                        // before.  In this case we do want to allow the app to
11635                        // now get the new permission if the ancestral apk is
11636                        // privileged to get it.
11637                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11638                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11639                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11640                                    allowed = true;
11641                                    break;
11642                                }
11643                            }
11644                        }
11645                        // Also if a privileged parent package on the system image or any of
11646                        // its children requested a privileged permission, the updated child
11647                        // packages can also get the permission.
11648                        if (pkg.parentPackage != null) {
11649                            final PackageSetting disabledSysParentPs = mSettings
11650                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11651                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11652                                    && disabledSysParentPs.isPrivileged()) {
11653                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11654                                    allowed = true;
11655                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11656                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11657                                    for (int i = 0; i < count; i++) {
11658                                        PackageParser.Package disabledSysChildPkg =
11659                                                disabledSysParentPs.pkg.childPackages.get(i);
11660                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11661                                                perm)) {
11662                                            allowed = true;
11663                                            break;
11664                                        }
11665                                    }
11666                                }
11667                            }
11668                        }
11669                    }
11670                } else {
11671                    allowed = isPrivilegedApp(pkg);
11672                }
11673            }
11674        }
11675        if (!allowed) {
11676            if (!allowed && (bp.protectionLevel
11677                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11678                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11679                // If this was a previously normal/dangerous permission that got moved
11680                // to a system permission as part of the runtime permission redesign, then
11681                // we still want to blindly grant it to old apps.
11682                allowed = true;
11683            }
11684            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11685                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11686                // If this permission is to be granted to the system installer and
11687                // this app is an installer, then it gets the permission.
11688                allowed = true;
11689            }
11690            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11691                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11692                // If this permission is to be granted to the system verifier and
11693                // this app is a verifier, then it gets the permission.
11694                allowed = true;
11695            }
11696            if (!allowed && (bp.protectionLevel
11697                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11698                    && isSystemApp(pkg)) {
11699                // Any pre-installed system app is allowed to get this permission.
11700                allowed = true;
11701            }
11702            if (!allowed && (bp.protectionLevel
11703                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11704                // For development permissions, a development permission
11705                // is granted only if it was already granted.
11706                allowed = origPermissions.hasInstallPermission(perm);
11707            }
11708            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11709                    && pkg.packageName.equals(mSetupWizardPackage)) {
11710                // If this permission is to be granted to the system setup wizard and
11711                // this app is a setup wizard, then it gets the permission.
11712                allowed = true;
11713            }
11714        }
11715        return allowed;
11716    }
11717
11718    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11719        final int permCount = pkg.requestedPermissions.size();
11720        for (int j = 0; j < permCount; j++) {
11721            String requestedPermission = pkg.requestedPermissions.get(j);
11722            if (permission.equals(requestedPermission)) {
11723                return true;
11724            }
11725        }
11726        return false;
11727    }
11728
11729    final class ActivityIntentResolver
11730            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11732                boolean defaultOnly, int userId) {
11733            if (!sUserManager.exists(userId)) return null;
11734            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11735            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11736        }
11737
11738        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11739                int userId) {
11740            if (!sUserManager.exists(userId)) return null;
11741            mFlags = flags;
11742            return super.queryIntent(intent, resolvedType,
11743                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11744                    userId);
11745        }
11746
11747        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11748                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11749            if (!sUserManager.exists(userId)) return null;
11750            if (packageActivities == null) {
11751                return null;
11752            }
11753            mFlags = flags;
11754            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11755            final int N = packageActivities.size();
11756            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11757                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11758
11759            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11760            for (int i = 0; i < N; ++i) {
11761                intentFilters = packageActivities.get(i).intents;
11762                if (intentFilters != null && intentFilters.size() > 0) {
11763                    PackageParser.ActivityIntentInfo[] array =
11764                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11765                    intentFilters.toArray(array);
11766                    listCut.add(array);
11767                }
11768            }
11769            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11770        }
11771
11772        /**
11773         * Finds a privileged activity that matches the specified activity names.
11774         */
11775        private PackageParser.Activity findMatchingActivity(
11776                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11777            for (PackageParser.Activity sysActivity : activityList) {
11778                if (sysActivity.info.name.equals(activityInfo.name)) {
11779                    return sysActivity;
11780                }
11781                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11782                    return sysActivity;
11783                }
11784                if (sysActivity.info.targetActivity != null) {
11785                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11786                        return sysActivity;
11787                    }
11788                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11789                        return sysActivity;
11790                    }
11791                }
11792            }
11793            return null;
11794        }
11795
11796        public class IterGenerator<E> {
11797            public Iterator<E> generate(ActivityIntentInfo info) {
11798                return null;
11799            }
11800        }
11801
11802        public class ActionIterGenerator extends IterGenerator<String> {
11803            @Override
11804            public Iterator<String> generate(ActivityIntentInfo info) {
11805                return info.actionsIterator();
11806            }
11807        }
11808
11809        public class CategoriesIterGenerator extends IterGenerator<String> {
11810            @Override
11811            public Iterator<String> generate(ActivityIntentInfo info) {
11812                return info.categoriesIterator();
11813            }
11814        }
11815
11816        public class SchemesIterGenerator extends IterGenerator<String> {
11817            @Override
11818            public Iterator<String> generate(ActivityIntentInfo info) {
11819                return info.schemesIterator();
11820            }
11821        }
11822
11823        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11824            @Override
11825            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11826                return info.authoritiesIterator();
11827            }
11828        }
11829
11830        /**
11831         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11832         * MODIFIED. Do not pass in a list that should not be changed.
11833         */
11834        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11835                IterGenerator<T> generator, Iterator<T> searchIterator) {
11836            // loop through the set of actions; every one must be found in the intent filter
11837            while (searchIterator.hasNext()) {
11838                // we must have at least one filter in the list to consider a match
11839                if (intentList.size() == 0) {
11840                    break;
11841                }
11842
11843                final T searchAction = searchIterator.next();
11844
11845                // loop through the set of intent filters
11846                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11847                while (intentIter.hasNext()) {
11848                    final ActivityIntentInfo intentInfo = intentIter.next();
11849                    boolean selectionFound = false;
11850
11851                    // loop through the intent filter's selection criteria; at least one
11852                    // of them must match the searched criteria
11853                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11854                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11855                        final T intentSelection = intentSelectionIter.next();
11856                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11857                            selectionFound = true;
11858                            break;
11859                        }
11860                    }
11861
11862                    // the selection criteria wasn't found in this filter's set; this filter
11863                    // is not a potential match
11864                    if (!selectionFound) {
11865                        intentIter.remove();
11866                    }
11867                }
11868            }
11869        }
11870
11871        private boolean isProtectedAction(ActivityIntentInfo filter) {
11872            final Iterator<String> actionsIter = filter.actionsIterator();
11873            while (actionsIter != null && actionsIter.hasNext()) {
11874                final String filterAction = actionsIter.next();
11875                if (PROTECTED_ACTIONS.contains(filterAction)) {
11876                    return true;
11877                }
11878            }
11879            return false;
11880        }
11881
11882        /**
11883         * Adjusts the priority of the given intent filter according to policy.
11884         * <p>
11885         * <ul>
11886         * <li>The priority for non privileged applications is capped to '0'</li>
11887         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11888         * <li>The priority for unbundled updates to privileged applications is capped to the
11889         *      priority defined on the system partition</li>
11890         * </ul>
11891         * <p>
11892         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11893         * allowed to obtain any priority on any action.
11894         */
11895        private void adjustPriority(
11896                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11897            // nothing to do; priority is fine as-is
11898            if (intent.getPriority() <= 0) {
11899                return;
11900            }
11901
11902            final ActivityInfo activityInfo = intent.activity.info;
11903            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11904
11905            final boolean privilegedApp =
11906                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11907            if (!privilegedApp) {
11908                // non-privileged applications can never define a priority >0
11909                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11910                        + " package: " + applicationInfo.packageName
11911                        + " activity: " + intent.activity.className
11912                        + " origPrio: " + intent.getPriority());
11913                intent.setPriority(0);
11914                return;
11915            }
11916
11917            if (systemActivities == null) {
11918                // the system package is not disabled; we're parsing the system partition
11919                if (isProtectedAction(intent)) {
11920                    if (mDeferProtectedFilters) {
11921                        // We can't deal with these just yet. No component should ever obtain a
11922                        // >0 priority for a protected actions, with ONE exception -- the setup
11923                        // wizard. The setup wizard, however, cannot be known until we're able to
11924                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11925                        // until all intent filters have been processed. Chicken, meet egg.
11926                        // Let the filter temporarily have a high priority and rectify the
11927                        // priorities after all system packages have been scanned.
11928                        mProtectedFilters.add(intent);
11929                        if (DEBUG_FILTERS) {
11930                            Slog.i(TAG, "Protected action; save for later;"
11931                                    + " package: " + applicationInfo.packageName
11932                                    + " activity: " + intent.activity.className
11933                                    + " origPrio: " + intent.getPriority());
11934                        }
11935                        return;
11936                    } else {
11937                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11938                            Slog.i(TAG, "No setup wizard;"
11939                                + " All protected intents capped to priority 0");
11940                        }
11941                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11942                            if (DEBUG_FILTERS) {
11943                                Slog.i(TAG, "Found setup wizard;"
11944                                    + " allow priority " + intent.getPriority() + ";"
11945                                    + " package: " + intent.activity.info.packageName
11946                                    + " activity: " + intent.activity.className
11947                                    + " priority: " + intent.getPriority());
11948                            }
11949                            // setup wizard gets whatever it wants
11950                            return;
11951                        }
11952                        Slog.w(TAG, "Protected action; cap priority to 0;"
11953                                + " package: " + intent.activity.info.packageName
11954                                + " activity: " + intent.activity.className
11955                                + " origPrio: " + intent.getPriority());
11956                        intent.setPriority(0);
11957                        return;
11958                    }
11959                }
11960                // privileged apps on the system image get whatever priority they request
11961                return;
11962            }
11963
11964            // privileged app unbundled update ... try to find the same activity
11965            final PackageParser.Activity foundActivity =
11966                    findMatchingActivity(systemActivities, activityInfo);
11967            if (foundActivity == null) {
11968                // this is a new activity; it cannot obtain >0 priority
11969                if (DEBUG_FILTERS) {
11970                    Slog.i(TAG, "New activity; cap priority to 0;"
11971                            + " package: " + applicationInfo.packageName
11972                            + " activity: " + intent.activity.className
11973                            + " origPrio: " + intent.getPriority());
11974                }
11975                intent.setPriority(0);
11976                return;
11977            }
11978
11979            // found activity, now check for filter equivalence
11980
11981            // a shallow copy is enough; we modify the list, not its contents
11982            final List<ActivityIntentInfo> intentListCopy =
11983                    new ArrayList<>(foundActivity.intents);
11984            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11985
11986            // find matching action subsets
11987            final Iterator<String> actionsIterator = intent.actionsIterator();
11988            if (actionsIterator != null) {
11989                getIntentListSubset(
11990                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11991                if (intentListCopy.size() == 0) {
11992                    // no more intents to match; we're not equivalent
11993                    if (DEBUG_FILTERS) {
11994                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11995                                + " package: " + applicationInfo.packageName
11996                                + " activity: " + intent.activity.className
11997                                + " origPrio: " + intent.getPriority());
11998                    }
11999                    intent.setPriority(0);
12000                    return;
12001                }
12002            }
12003
12004            // find matching category subsets
12005            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12006            if (categoriesIterator != null) {
12007                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12008                        categoriesIterator);
12009                if (intentListCopy.size() == 0) {
12010                    // no more intents to match; we're not equivalent
12011                    if (DEBUG_FILTERS) {
12012                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12013                                + " package: " + applicationInfo.packageName
12014                                + " activity: " + intent.activity.className
12015                                + " origPrio: " + intent.getPriority());
12016                    }
12017                    intent.setPriority(0);
12018                    return;
12019                }
12020            }
12021
12022            // find matching schemes subsets
12023            final Iterator<String> schemesIterator = intent.schemesIterator();
12024            if (schemesIterator != null) {
12025                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12026                        schemesIterator);
12027                if (intentListCopy.size() == 0) {
12028                    // no more intents to match; we're not equivalent
12029                    if (DEBUG_FILTERS) {
12030                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12031                                + " package: " + applicationInfo.packageName
12032                                + " activity: " + intent.activity.className
12033                                + " origPrio: " + intent.getPriority());
12034                    }
12035                    intent.setPriority(0);
12036                    return;
12037                }
12038            }
12039
12040            // find matching authorities subsets
12041            final Iterator<IntentFilter.AuthorityEntry>
12042                    authoritiesIterator = intent.authoritiesIterator();
12043            if (authoritiesIterator != null) {
12044                getIntentListSubset(intentListCopy,
12045                        new AuthoritiesIterGenerator(),
12046                        authoritiesIterator);
12047                if (intentListCopy.size() == 0) {
12048                    // no more intents to match; we're not equivalent
12049                    if (DEBUG_FILTERS) {
12050                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12051                                + " package: " + applicationInfo.packageName
12052                                + " activity: " + intent.activity.className
12053                                + " origPrio: " + intent.getPriority());
12054                    }
12055                    intent.setPriority(0);
12056                    return;
12057                }
12058            }
12059
12060            // we found matching filter(s); app gets the max priority of all intents
12061            int cappedPriority = 0;
12062            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12063                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12064            }
12065            if (intent.getPriority() > cappedPriority) {
12066                if (DEBUG_FILTERS) {
12067                    Slog.i(TAG, "Found matching filter(s);"
12068                            + " cap priority to " + cappedPriority + ";"
12069                            + " package: " + applicationInfo.packageName
12070                            + " activity: " + intent.activity.className
12071                            + " origPrio: " + intent.getPriority());
12072                }
12073                intent.setPriority(cappedPriority);
12074                return;
12075            }
12076            // all this for nothing; the requested priority was <= what was on the system
12077        }
12078
12079        public final void addActivity(PackageParser.Activity a, String type) {
12080            mActivities.put(a.getComponentName(), a);
12081            if (DEBUG_SHOW_INFO)
12082                Log.v(
12083                TAG, "  " + type + " " +
12084                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12085            if (DEBUG_SHOW_INFO)
12086                Log.v(TAG, "    Class=" + a.info.name);
12087            final int NI = a.intents.size();
12088            for (int j=0; j<NI; j++) {
12089                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12090                if ("activity".equals(type)) {
12091                    final PackageSetting ps =
12092                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12093                    final List<PackageParser.Activity> systemActivities =
12094                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12095                    adjustPriority(systemActivities, intent);
12096                }
12097                if (DEBUG_SHOW_INFO) {
12098                    Log.v(TAG, "    IntentFilter:");
12099                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12100                }
12101                if (!intent.debugCheck()) {
12102                    Log.w(TAG, "==> For Activity " + a.info.name);
12103                }
12104                addFilter(intent);
12105            }
12106        }
12107
12108        public final void removeActivity(PackageParser.Activity a, String type) {
12109            mActivities.remove(a.getComponentName());
12110            if (DEBUG_SHOW_INFO) {
12111                Log.v(TAG, "  " + type + " "
12112                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12113                                : a.info.name) + ":");
12114                Log.v(TAG, "    Class=" + a.info.name);
12115            }
12116            final int NI = a.intents.size();
12117            for (int j=0; j<NI; j++) {
12118                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12119                if (DEBUG_SHOW_INFO) {
12120                    Log.v(TAG, "    IntentFilter:");
12121                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12122                }
12123                removeFilter(intent);
12124            }
12125        }
12126
12127        @Override
12128        protected boolean allowFilterResult(
12129                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12130            ActivityInfo filterAi = filter.activity.info;
12131            for (int i=dest.size()-1; i>=0; i--) {
12132                ActivityInfo destAi = dest.get(i).activityInfo;
12133                if (destAi.name == filterAi.name
12134                        && destAi.packageName == filterAi.packageName) {
12135                    return false;
12136                }
12137            }
12138            return true;
12139        }
12140
12141        @Override
12142        protected ActivityIntentInfo[] newArray(int size) {
12143            return new ActivityIntentInfo[size];
12144        }
12145
12146        @Override
12147        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12148            if (!sUserManager.exists(userId)) return true;
12149            PackageParser.Package p = filter.activity.owner;
12150            if (p != null) {
12151                PackageSetting ps = (PackageSetting)p.mExtras;
12152                if (ps != null) {
12153                    // System apps are never considered stopped for purposes of
12154                    // filtering, because there may be no way for the user to
12155                    // actually re-launch them.
12156                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12157                            && ps.getStopped(userId);
12158                }
12159            }
12160            return false;
12161        }
12162
12163        @Override
12164        protected boolean isPackageForFilter(String packageName,
12165                PackageParser.ActivityIntentInfo info) {
12166            return packageName.equals(info.activity.owner.packageName);
12167        }
12168
12169        @Override
12170        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12171                int match, int userId) {
12172            if (!sUserManager.exists(userId)) return null;
12173            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12174                return null;
12175            }
12176            final PackageParser.Activity activity = info.activity;
12177            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12178            if (ps == null) {
12179                return null;
12180            }
12181            final PackageUserState userState = ps.readUserState(userId);
12182            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12183                    userState, userId);
12184            if (ai == null) {
12185                return null;
12186            }
12187            final boolean matchVisibleToInstantApp =
12188                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12189            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12190            // throw out filters that aren't visible to ephemeral apps
12191            if (matchVisibleToInstantApp
12192                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12193                return null;
12194            }
12195            // throw out ephemeral filters if we're not explicitly requesting them
12196            if (!isInstantApp && userState.instantApp) {
12197                return null;
12198            }
12199            final ResolveInfo res = new ResolveInfo();
12200            res.activityInfo = ai;
12201            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12202                res.filter = info;
12203            }
12204            if (info != null) {
12205                res.handleAllWebDataURI = info.handleAllWebDataURI();
12206            }
12207            res.priority = info.getPriority();
12208            res.preferredOrder = activity.owner.mPreferredOrder;
12209            //System.out.println("Result: " + res.activityInfo.className +
12210            //                   " = " + res.priority);
12211            res.match = match;
12212            res.isDefault = info.hasDefault;
12213            res.labelRes = info.labelRes;
12214            res.nonLocalizedLabel = info.nonLocalizedLabel;
12215            if (userNeedsBadging(userId)) {
12216                res.noResourceId = true;
12217            } else {
12218                res.icon = info.icon;
12219            }
12220            res.iconResourceId = info.icon;
12221            res.system = res.activityInfo.applicationInfo.isSystemApp();
12222            res.instantAppAvailable = userState.instantApp;
12223            return res;
12224        }
12225
12226        @Override
12227        protected void sortResults(List<ResolveInfo> results) {
12228            Collections.sort(results, mResolvePrioritySorter);
12229        }
12230
12231        @Override
12232        protected void dumpFilter(PrintWriter out, String prefix,
12233                PackageParser.ActivityIntentInfo filter) {
12234            out.print(prefix); out.print(
12235                    Integer.toHexString(System.identityHashCode(filter.activity)));
12236                    out.print(' ');
12237                    filter.activity.printComponentShortName(out);
12238                    out.print(" filter ");
12239                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12240        }
12241
12242        @Override
12243        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12244            return filter.activity;
12245        }
12246
12247        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12248            PackageParser.Activity activity = (PackageParser.Activity)label;
12249            out.print(prefix); out.print(
12250                    Integer.toHexString(System.identityHashCode(activity)));
12251                    out.print(' ');
12252                    activity.printComponentShortName(out);
12253            if (count > 1) {
12254                out.print(" ("); out.print(count); out.print(" filters)");
12255            }
12256            out.println();
12257        }
12258
12259        // Keys are String (activity class name), values are Activity.
12260        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12261                = new ArrayMap<ComponentName, PackageParser.Activity>();
12262        private int mFlags;
12263    }
12264
12265    private final class ServiceIntentResolver
12266            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12267        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12268                boolean defaultOnly, int userId) {
12269            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12270            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12271        }
12272
12273        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12274                int userId) {
12275            if (!sUserManager.exists(userId)) return null;
12276            mFlags = flags;
12277            return super.queryIntent(intent, resolvedType,
12278                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12279                    userId);
12280        }
12281
12282        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12283                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12284            if (!sUserManager.exists(userId)) return null;
12285            if (packageServices == null) {
12286                return null;
12287            }
12288            mFlags = flags;
12289            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12290            final int N = packageServices.size();
12291            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12292                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12293
12294            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12295            for (int i = 0; i < N; ++i) {
12296                intentFilters = packageServices.get(i).intents;
12297                if (intentFilters != null && intentFilters.size() > 0) {
12298                    PackageParser.ServiceIntentInfo[] array =
12299                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12300                    intentFilters.toArray(array);
12301                    listCut.add(array);
12302                }
12303            }
12304            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12305        }
12306
12307        public final void addService(PackageParser.Service s) {
12308            mServices.put(s.getComponentName(), s);
12309            if (DEBUG_SHOW_INFO) {
12310                Log.v(TAG, "  "
12311                        + (s.info.nonLocalizedLabel != null
12312                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12313                Log.v(TAG, "    Class=" + s.info.name);
12314            }
12315            final int NI = s.intents.size();
12316            int j;
12317            for (j=0; j<NI; j++) {
12318                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12319                if (DEBUG_SHOW_INFO) {
12320                    Log.v(TAG, "    IntentFilter:");
12321                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12322                }
12323                if (!intent.debugCheck()) {
12324                    Log.w(TAG, "==> For Service " + s.info.name);
12325                }
12326                addFilter(intent);
12327            }
12328        }
12329
12330        public final void removeService(PackageParser.Service s) {
12331            mServices.remove(s.getComponentName());
12332            if (DEBUG_SHOW_INFO) {
12333                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12334                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12335                Log.v(TAG, "    Class=" + s.info.name);
12336            }
12337            final int NI = s.intents.size();
12338            int j;
12339            for (j=0; j<NI; j++) {
12340                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12341                if (DEBUG_SHOW_INFO) {
12342                    Log.v(TAG, "    IntentFilter:");
12343                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12344                }
12345                removeFilter(intent);
12346            }
12347        }
12348
12349        @Override
12350        protected boolean allowFilterResult(
12351                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12352            ServiceInfo filterSi = filter.service.info;
12353            for (int i=dest.size()-1; i>=0; i--) {
12354                ServiceInfo destAi = dest.get(i).serviceInfo;
12355                if (destAi.name == filterSi.name
12356                        && destAi.packageName == filterSi.packageName) {
12357                    return false;
12358                }
12359            }
12360            return true;
12361        }
12362
12363        @Override
12364        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12365            return new PackageParser.ServiceIntentInfo[size];
12366        }
12367
12368        @Override
12369        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12370            if (!sUserManager.exists(userId)) return true;
12371            PackageParser.Package p = filter.service.owner;
12372            if (p != null) {
12373                PackageSetting ps = (PackageSetting)p.mExtras;
12374                if (ps != null) {
12375                    // System apps are never considered stopped for purposes of
12376                    // filtering, because there may be no way for the user to
12377                    // actually re-launch them.
12378                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12379                            && ps.getStopped(userId);
12380                }
12381            }
12382            return false;
12383        }
12384
12385        @Override
12386        protected boolean isPackageForFilter(String packageName,
12387                PackageParser.ServiceIntentInfo info) {
12388            return packageName.equals(info.service.owner.packageName);
12389        }
12390
12391        @Override
12392        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12393                int match, int userId) {
12394            if (!sUserManager.exists(userId)) return null;
12395            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12396            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12397                return null;
12398            }
12399            final PackageParser.Service service = info.service;
12400            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12401            if (ps == null) {
12402                return null;
12403            }
12404            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12405                    ps.readUserState(userId), userId);
12406            if (si == null) {
12407                return null;
12408            }
12409            final ResolveInfo res = new ResolveInfo();
12410            res.serviceInfo = si;
12411            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12412                res.filter = filter;
12413            }
12414            res.priority = info.getPriority();
12415            res.preferredOrder = service.owner.mPreferredOrder;
12416            res.match = match;
12417            res.isDefault = info.hasDefault;
12418            res.labelRes = info.labelRes;
12419            res.nonLocalizedLabel = info.nonLocalizedLabel;
12420            res.icon = info.icon;
12421            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12422            return res;
12423        }
12424
12425        @Override
12426        protected void sortResults(List<ResolveInfo> results) {
12427            Collections.sort(results, mResolvePrioritySorter);
12428        }
12429
12430        @Override
12431        protected void dumpFilter(PrintWriter out, String prefix,
12432                PackageParser.ServiceIntentInfo filter) {
12433            out.print(prefix); out.print(
12434                    Integer.toHexString(System.identityHashCode(filter.service)));
12435                    out.print(' ');
12436                    filter.service.printComponentShortName(out);
12437                    out.print(" filter ");
12438                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12439        }
12440
12441        @Override
12442        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12443            return filter.service;
12444        }
12445
12446        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12447            PackageParser.Service service = (PackageParser.Service)label;
12448            out.print(prefix); out.print(
12449                    Integer.toHexString(System.identityHashCode(service)));
12450                    out.print(' ');
12451                    service.printComponentShortName(out);
12452            if (count > 1) {
12453                out.print(" ("); out.print(count); out.print(" filters)");
12454            }
12455            out.println();
12456        }
12457
12458//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12459//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12460//            final List<ResolveInfo> retList = Lists.newArrayList();
12461//            while (i.hasNext()) {
12462//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12463//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12464//                    retList.add(resolveInfo);
12465//                }
12466//            }
12467//            return retList;
12468//        }
12469
12470        // Keys are String (activity class name), values are Activity.
12471        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12472                = new ArrayMap<ComponentName, PackageParser.Service>();
12473        private int mFlags;
12474    }
12475
12476    private final class ProviderIntentResolver
12477            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12478        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12479                boolean defaultOnly, int userId) {
12480            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12481            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12482        }
12483
12484        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12485                int userId) {
12486            if (!sUserManager.exists(userId))
12487                return null;
12488            mFlags = flags;
12489            return super.queryIntent(intent, resolvedType,
12490                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12491                    userId);
12492        }
12493
12494        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12495                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12496            if (!sUserManager.exists(userId))
12497                return null;
12498            if (packageProviders == null) {
12499                return null;
12500            }
12501            mFlags = flags;
12502            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12503            final int N = packageProviders.size();
12504            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12505                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12506
12507            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12508            for (int i = 0; i < N; ++i) {
12509                intentFilters = packageProviders.get(i).intents;
12510                if (intentFilters != null && intentFilters.size() > 0) {
12511                    PackageParser.ProviderIntentInfo[] array =
12512                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12513                    intentFilters.toArray(array);
12514                    listCut.add(array);
12515                }
12516            }
12517            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12518        }
12519
12520        public final void addProvider(PackageParser.Provider p) {
12521            if (mProviders.containsKey(p.getComponentName())) {
12522                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12523                return;
12524            }
12525
12526            mProviders.put(p.getComponentName(), p);
12527            if (DEBUG_SHOW_INFO) {
12528                Log.v(TAG, "  "
12529                        + (p.info.nonLocalizedLabel != null
12530                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12531                Log.v(TAG, "    Class=" + p.info.name);
12532            }
12533            final int NI = p.intents.size();
12534            int j;
12535            for (j = 0; j < NI; j++) {
12536                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12537                if (DEBUG_SHOW_INFO) {
12538                    Log.v(TAG, "    IntentFilter:");
12539                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12540                }
12541                if (!intent.debugCheck()) {
12542                    Log.w(TAG, "==> For Provider " + p.info.name);
12543                }
12544                addFilter(intent);
12545            }
12546        }
12547
12548        public final void removeProvider(PackageParser.Provider p) {
12549            mProviders.remove(p.getComponentName());
12550            if (DEBUG_SHOW_INFO) {
12551                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12552                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12553                Log.v(TAG, "    Class=" + p.info.name);
12554            }
12555            final int NI = p.intents.size();
12556            int j;
12557            for (j = 0; j < NI; j++) {
12558                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12559                if (DEBUG_SHOW_INFO) {
12560                    Log.v(TAG, "    IntentFilter:");
12561                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12562                }
12563                removeFilter(intent);
12564            }
12565        }
12566
12567        @Override
12568        protected boolean allowFilterResult(
12569                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12570            ProviderInfo filterPi = filter.provider.info;
12571            for (int i = dest.size() - 1; i >= 0; i--) {
12572                ProviderInfo destPi = dest.get(i).providerInfo;
12573                if (destPi.name == filterPi.name
12574                        && destPi.packageName == filterPi.packageName) {
12575                    return false;
12576                }
12577            }
12578            return true;
12579        }
12580
12581        @Override
12582        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12583            return new PackageParser.ProviderIntentInfo[size];
12584        }
12585
12586        @Override
12587        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12588            if (!sUserManager.exists(userId))
12589                return true;
12590            PackageParser.Package p = filter.provider.owner;
12591            if (p != null) {
12592                PackageSetting ps = (PackageSetting) p.mExtras;
12593                if (ps != null) {
12594                    // System apps are never considered stopped for purposes of
12595                    // filtering, because there may be no way for the user to
12596                    // actually re-launch them.
12597                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12598                            && ps.getStopped(userId);
12599                }
12600            }
12601            return false;
12602        }
12603
12604        @Override
12605        protected boolean isPackageForFilter(String packageName,
12606                PackageParser.ProviderIntentInfo info) {
12607            return packageName.equals(info.provider.owner.packageName);
12608        }
12609
12610        @Override
12611        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12612                int match, int userId) {
12613            if (!sUserManager.exists(userId))
12614                return null;
12615            final PackageParser.ProviderIntentInfo info = filter;
12616            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12617                return null;
12618            }
12619            final PackageParser.Provider provider = info.provider;
12620            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12621            if (ps == null) {
12622                return null;
12623            }
12624            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12625                    ps.readUserState(userId), userId);
12626            if (pi == null) {
12627                return null;
12628            }
12629            final ResolveInfo res = new ResolveInfo();
12630            res.providerInfo = pi;
12631            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12632                res.filter = filter;
12633            }
12634            res.priority = info.getPriority();
12635            res.preferredOrder = provider.owner.mPreferredOrder;
12636            res.match = match;
12637            res.isDefault = info.hasDefault;
12638            res.labelRes = info.labelRes;
12639            res.nonLocalizedLabel = info.nonLocalizedLabel;
12640            res.icon = info.icon;
12641            res.system = res.providerInfo.applicationInfo.isSystemApp();
12642            return res;
12643        }
12644
12645        @Override
12646        protected void sortResults(List<ResolveInfo> results) {
12647            Collections.sort(results, mResolvePrioritySorter);
12648        }
12649
12650        @Override
12651        protected void dumpFilter(PrintWriter out, String prefix,
12652                PackageParser.ProviderIntentInfo filter) {
12653            out.print(prefix);
12654            out.print(
12655                    Integer.toHexString(System.identityHashCode(filter.provider)));
12656            out.print(' ');
12657            filter.provider.printComponentShortName(out);
12658            out.print(" filter ");
12659            out.println(Integer.toHexString(System.identityHashCode(filter)));
12660        }
12661
12662        @Override
12663        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12664            return filter.provider;
12665        }
12666
12667        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12668            PackageParser.Provider provider = (PackageParser.Provider)label;
12669            out.print(prefix); out.print(
12670                    Integer.toHexString(System.identityHashCode(provider)));
12671                    out.print(' ');
12672                    provider.printComponentShortName(out);
12673            if (count > 1) {
12674                out.print(" ("); out.print(count); out.print(" filters)");
12675            }
12676            out.println();
12677        }
12678
12679        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12680                = new ArrayMap<ComponentName, PackageParser.Provider>();
12681        private int mFlags;
12682    }
12683
12684    static final class EphemeralIntentResolver
12685            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12686        /**
12687         * The result that has the highest defined order. Ordering applies on a
12688         * per-package basis. Mapping is from package name to Pair of order and
12689         * EphemeralResolveInfo.
12690         * <p>
12691         * NOTE: This is implemented as a field variable for convenience and efficiency.
12692         * By having a field variable, we're able to track filter ordering as soon as
12693         * a non-zero order is defined. Otherwise, multiple loops across the result set
12694         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12695         * this needs to be contained entirely within {@link #filterResults}.
12696         */
12697        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12698
12699        @Override
12700        protected AuxiliaryResolveInfo[] newArray(int size) {
12701            return new AuxiliaryResolveInfo[size];
12702        }
12703
12704        @Override
12705        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12706            return true;
12707        }
12708
12709        @Override
12710        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12711                int userId) {
12712            if (!sUserManager.exists(userId)) {
12713                return null;
12714            }
12715            final String packageName = responseObj.resolveInfo.getPackageName();
12716            final Integer order = responseObj.getOrder();
12717            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12718                    mOrderResult.get(packageName);
12719            // ordering is enabled and this item's order isn't high enough
12720            if (lastOrderResult != null && lastOrderResult.first >= order) {
12721                return null;
12722            }
12723            final EphemeralResolveInfo res = responseObj.resolveInfo;
12724            if (order > 0) {
12725                // non-zero order, enable ordering
12726                mOrderResult.put(packageName, new Pair<>(order, res));
12727            }
12728            return responseObj;
12729        }
12730
12731        @Override
12732        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12733            // only do work if ordering is enabled [most of the time it won't be]
12734            if (mOrderResult.size() == 0) {
12735                return;
12736            }
12737            int resultSize = results.size();
12738            for (int i = 0; i < resultSize; i++) {
12739                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12740                final String packageName = info.getPackageName();
12741                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12742                if (savedInfo == null) {
12743                    // package doesn't having ordering
12744                    continue;
12745                }
12746                if (savedInfo.second == info) {
12747                    // circled back to the highest ordered item; remove from order list
12748                    mOrderResult.remove(savedInfo);
12749                    if (mOrderResult.size() == 0) {
12750                        // no more ordered items
12751                        break;
12752                    }
12753                    continue;
12754                }
12755                // item has a worse order, remove it from the result list
12756                results.remove(i);
12757                resultSize--;
12758                i--;
12759            }
12760        }
12761    }
12762
12763    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12764            new Comparator<ResolveInfo>() {
12765        public int compare(ResolveInfo r1, ResolveInfo r2) {
12766            int v1 = r1.priority;
12767            int v2 = r2.priority;
12768            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12769            if (v1 != v2) {
12770                return (v1 > v2) ? -1 : 1;
12771            }
12772            v1 = r1.preferredOrder;
12773            v2 = r2.preferredOrder;
12774            if (v1 != v2) {
12775                return (v1 > v2) ? -1 : 1;
12776            }
12777            if (r1.isDefault != r2.isDefault) {
12778                return r1.isDefault ? -1 : 1;
12779            }
12780            v1 = r1.match;
12781            v2 = r2.match;
12782            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12783            if (v1 != v2) {
12784                return (v1 > v2) ? -1 : 1;
12785            }
12786            if (r1.system != r2.system) {
12787                return r1.system ? -1 : 1;
12788            }
12789            if (r1.activityInfo != null) {
12790                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12791            }
12792            if (r1.serviceInfo != null) {
12793                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12794            }
12795            if (r1.providerInfo != null) {
12796                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12797            }
12798            return 0;
12799        }
12800    };
12801
12802    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12803            new Comparator<ProviderInfo>() {
12804        public int compare(ProviderInfo p1, ProviderInfo p2) {
12805            final int v1 = p1.initOrder;
12806            final int v2 = p2.initOrder;
12807            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12808        }
12809    };
12810
12811    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12812            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12813            final int[] userIds) {
12814        mHandler.post(new Runnable() {
12815            @Override
12816            public void run() {
12817                try {
12818                    final IActivityManager am = ActivityManager.getService();
12819                    if (am == null) return;
12820                    final int[] resolvedUserIds;
12821                    if (userIds == null) {
12822                        resolvedUserIds = am.getRunningUserIds();
12823                    } else {
12824                        resolvedUserIds = userIds;
12825                    }
12826                    for (int id : resolvedUserIds) {
12827                        final Intent intent = new Intent(action,
12828                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12829                        if (extras != null) {
12830                            intent.putExtras(extras);
12831                        }
12832                        if (targetPkg != null) {
12833                            intent.setPackage(targetPkg);
12834                        }
12835                        // Modify the UID when posting to other users
12836                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12837                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12838                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12839                            intent.putExtra(Intent.EXTRA_UID, uid);
12840                        }
12841                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12842                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12843                        if (DEBUG_BROADCASTS) {
12844                            RuntimeException here = new RuntimeException("here");
12845                            here.fillInStackTrace();
12846                            Slog.d(TAG, "Sending to user " + id + ": "
12847                                    + intent.toShortString(false, true, false, false)
12848                                    + " " + intent.getExtras(), here);
12849                        }
12850                        am.broadcastIntent(null, intent, null, finishedReceiver,
12851                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12852                                null, finishedReceiver != null, false, id);
12853                    }
12854                } catch (RemoteException ex) {
12855                }
12856            }
12857        });
12858    }
12859
12860    /**
12861     * Check if the external storage media is available. This is true if there
12862     * is a mounted external storage medium or if the external storage is
12863     * emulated.
12864     */
12865    private boolean isExternalMediaAvailable() {
12866        return mMediaMounted || Environment.isExternalStorageEmulated();
12867    }
12868
12869    @Override
12870    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12871        // writer
12872        synchronized (mPackages) {
12873            if (!isExternalMediaAvailable()) {
12874                // If the external storage is no longer mounted at this point,
12875                // the caller may not have been able to delete all of this
12876                // packages files and can not delete any more.  Bail.
12877                return null;
12878            }
12879            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12880            if (lastPackage != null) {
12881                pkgs.remove(lastPackage);
12882            }
12883            if (pkgs.size() > 0) {
12884                return pkgs.get(0);
12885            }
12886        }
12887        return null;
12888    }
12889
12890    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12891        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12892                userId, andCode ? 1 : 0, packageName);
12893        if (mSystemReady) {
12894            msg.sendToTarget();
12895        } else {
12896            if (mPostSystemReadyMessages == null) {
12897                mPostSystemReadyMessages = new ArrayList<>();
12898            }
12899            mPostSystemReadyMessages.add(msg);
12900        }
12901    }
12902
12903    void startCleaningPackages() {
12904        // reader
12905        if (!isExternalMediaAvailable()) {
12906            return;
12907        }
12908        synchronized (mPackages) {
12909            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12910                return;
12911            }
12912        }
12913        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12914        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12915        IActivityManager am = ActivityManager.getService();
12916        if (am != null) {
12917            try {
12918                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12919                        UserHandle.USER_SYSTEM);
12920            } catch (RemoteException e) {
12921            }
12922        }
12923    }
12924
12925    @Override
12926    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12927            int installFlags, String installerPackageName, int userId) {
12928        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12929
12930        final int callingUid = Binder.getCallingUid();
12931        enforceCrossUserPermission(callingUid, userId,
12932                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12933
12934        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12935            try {
12936                if (observer != null) {
12937                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12938                }
12939            } catch (RemoteException re) {
12940            }
12941            return;
12942        }
12943
12944        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12945            installFlags |= PackageManager.INSTALL_FROM_ADB;
12946
12947        } else {
12948            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12949            // about installerPackageName.
12950
12951            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12952            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12953        }
12954
12955        UserHandle user;
12956        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12957            user = UserHandle.ALL;
12958        } else {
12959            user = new UserHandle(userId);
12960        }
12961
12962        // Only system components can circumvent runtime permissions when installing.
12963        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12964                && mContext.checkCallingOrSelfPermission(Manifest.permission
12965                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12966            throw new SecurityException("You need the "
12967                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12968                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12969        }
12970
12971        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12972                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12973            throw new IllegalArgumentException(
12974                    "New installs into ASEC containers no longer supported");
12975        }
12976
12977        final File originFile = new File(originPath);
12978        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12979
12980        final Message msg = mHandler.obtainMessage(INIT_COPY);
12981        final VerificationInfo verificationInfo = new VerificationInfo(
12982                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12983        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12984                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12985                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12986                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12987        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12988        msg.obj = params;
12989
12990        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12991                System.identityHashCode(msg.obj));
12992        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12993                System.identityHashCode(msg.obj));
12994
12995        mHandler.sendMessage(msg);
12996    }
12997
12998
12999    /**
13000     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13001     * it is acting on behalf on an enterprise or the user).
13002     *
13003     * Note that the ordering of the conditionals in this method is important. The checks we perform
13004     * are as follows, in this order:
13005     *
13006     * 1) If the install is being performed by a system app, we can trust the app to have set the
13007     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13008     *    what it is.
13009     * 2) If the install is being performed by a device or profile owner app, the install reason
13010     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13011     *    set the install reason correctly. If the app targets an older SDK version where install
13012     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13013     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13014     * 3) In all other cases, the install is being performed by a regular app that is neither part
13015     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13016     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13017     *    set to enterprise policy and if so, change it to unknown instead.
13018     */
13019    private int fixUpInstallReason(String installerPackageName, int installerUid,
13020            int installReason) {
13021        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13022                == PERMISSION_GRANTED) {
13023            // If the install is being performed by a system app, we trust that app to have set the
13024            // install reason correctly.
13025            return installReason;
13026        }
13027
13028        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13029            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13030        if (dpm != null) {
13031            ComponentName owner = null;
13032            try {
13033                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13034                if (owner == null) {
13035                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13036                }
13037            } catch (RemoteException e) {
13038            }
13039            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13040                // If the install is being performed by a device or profile owner, the install
13041                // reason should be enterprise policy.
13042                return PackageManager.INSTALL_REASON_POLICY;
13043            }
13044        }
13045
13046        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13047            // If the install is being performed by a regular app (i.e. neither system app nor
13048            // device or profile owner), we have no reason to believe that the app is acting on
13049            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13050            // change it to unknown instead.
13051            return PackageManager.INSTALL_REASON_UNKNOWN;
13052        }
13053
13054        // If the install is being performed by a regular app and the install reason was set to any
13055        // value but enterprise policy, leave the install reason unchanged.
13056        return installReason;
13057    }
13058
13059    void installStage(String packageName, File stagedDir, String stagedCid,
13060            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13061            String installerPackageName, int installerUid, UserHandle user,
13062            Certificate[][] certificates) {
13063        if (DEBUG_EPHEMERAL) {
13064            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13065                Slog.d(TAG, "Ephemeral install of " + packageName);
13066            }
13067        }
13068        final VerificationInfo verificationInfo = new VerificationInfo(
13069                sessionParams.originatingUri, sessionParams.referrerUri,
13070                sessionParams.originatingUid, installerUid);
13071
13072        final OriginInfo origin;
13073        if (stagedDir != null) {
13074            origin = OriginInfo.fromStagedFile(stagedDir);
13075        } else {
13076            origin = OriginInfo.fromStagedContainer(stagedCid);
13077        }
13078
13079        final Message msg = mHandler.obtainMessage(INIT_COPY);
13080        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13081                sessionParams.installReason);
13082        final InstallParams params = new InstallParams(origin, null, observer,
13083                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13084                verificationInfo, user, sessionParams.abiOverride,
13085                sessionParams.grantedRuntimePermissions, certificates, installReason);
13086        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13087        msg.obj = params;
13088
13089        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13090                System.identityHashCode(msg.obj));
13091        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13092                System.identityHashCode(msg.obj));
13093
13094        mHandler.sendMessage(msg);
13095    }
13096
13097    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13098            int userId) {
13099        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13100        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13101    }
13102
13103    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13104            int appId, int... userIds) {
13105        if (ArrayUtils.isEmpty(userIds)) {
13106            return;
13107        }
13108        Bundle extras = new Bundle(1);
13109        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13110        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13111
13112        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13113                packageName, extras, 0, null, null, userIds);
13114        if (isSystem) {
13115            mHandler.post(() -> {
13116                        for (int userId : userIds) {
13117                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13118                        }
13119                    }
13120            );
13121        }
13122    }
13123
13124    /**
13125     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13126     * automatically without needing an explicit launch.
13127     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13128     */
13129    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13130        // If user is not running, the app didn't miss any broadcast
13131        if (!mUserManagerInternal.isUserRunning(userId)) {
13132            return;
13133        }
13134        final IActivityManager am = ActivityManager.getService();
13135        try {
13136            // Deliver LOCKED_BOOT_COMPLETED first
13137            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13138                    .setPackage(packageName);
13139            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13140            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13141                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13142
13143            // Deliver BOOT_COMPLETED only if user is unlocked
13144            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13145                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13146                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13147                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13148            }
13149        } catch (RemoteException e) {
13150            throw e.rethrowFromSystemServer();
13151        }
13152    }
13153
13154    @Override
13155    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13156            int userId) {
13157        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13158        PackageSetting pkgSetting;
13159        final int uid = Binder.getCallingUid();
13160        enforceCrossUserPermission(uid, userId,
13161                true /* requireFullPermission */, true /* checkShell */,
13162                "setApplicationHiddenSetting for user " + userId);
13163
13164        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13165            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13166            return false;
13167        }
13168
13169        long callingId = Binder.clearCallingIdentity();
13170        try {
13171            boolean sendAdded = false;
13172            boolean sendRemoved = false;
13173            // writer
13174            synchronized (mPackages) {
13175                pkgSetting = mSettings.mPackages.get(packageName);
13176                if (pkgSetting == null) {
13177                    return false;
13178                }
13179                // Do not allow "android" is being disabled
13180                if ("android".equals(packageName)) {
13181                    Slog.w(TAG, "Cannot hide package: android");
13182                    return false;
13183                }
13184                // Cannot hide static shared libs as they are considered
13185                // a part of the using app (emulating static linking). Also
13186                // static libs are installed always on internal storage.
13187                PackageParser.Package pkg = mPackages.get(packageName);
13188                if (pkg != null && pkg.staticSharedLibName != null) {
13189                    Slog.w(TAG, "Cannot hide package: " + packageName
13190                            + " providing static shared library: "
13191                            + pkg.staticSharedLibName);
13192                    return false;
13193                }
13194                // Only allow protected packages to hide themselves.
13195                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13196                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13197                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13198                    return false;
13199                }
13200
13201                if (pkgSetting.getHidden(userId) != hidden) {
13202                    pkgSetting.setHidden(hidden, userId);
13203                    mSettings.writePackageRestrictionsLPr(userId);
13204                    if (hidden) {
13205                        sendRemoved = true;
13206                    } else {
13207                        sendAdded = true;
13208                    }
13209                }
13210            }
13211            if (sendAdded) {
13212                sendPackageAddedForUser(packageName, pkgSetting, userId);
13213                return true;
13214            }
13215            if (sendRemoved) {
13216                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13217                        "hiding pkg");
13218                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13219                return true;
13220            }
13221        } finally {
13222            Binder.restoreCallingIdentity(callingId);
13223        }
13224        return false;
13225    }
13226
13227    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13228            int userId) {
13229        final PackageRemovedInfo info = new PackageRemovedInfo();
13230        info.removedPackage = packageName;
13231        info.removedUsers = new int[] {userId};
13232        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13233        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13234    }
13235
13236    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13237        if (pkgList.length > 0) {
13238            Bundle extras = new Bundle(1);
13239            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13240
13241            sendPackageBroadcast(
13242                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13243                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13244                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13245                    new int[] {userId});
13246        }
13247    }
13248
13249    /**
13250     * Returns true if application is not found or there was an error. Otherwise it returns
13251     * the hidden state of the package for the given user.
13252     */
13253    @Override
13254    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13257                true /* requireFullPermission */, false /* checkShell */,
13258                "getApplicationHidden for user " + userId);
13259        PackageSetting pkgSetting;
13260        long callingId = Binder.clearCallingIdentity();
13261        try {
13262            // writer
13263            synchronized (mPackages) {
13264                pkgSetting = mSettings.mPackages.get(packageName);
13265                if (pkgSetting == null) {
13266                    return true;
13267                }
13268                return pkgSetting.getHidden(userId);
13269            }
13270        } finally {
13271            Binder.restoreCallingIdentity(callingId);
13272        }
13273    }
13274
13275    /**
13276     * @hide
13277     */
13278    @Override
13279    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13280            int installReason) {
13281        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13282                null);
13283        PackageSetting pkgSetting;
13284        final int uid = Binder.getCallingUid();
13285        enforceCrossUserPermission(uid, userId,
13286                true /* requireFullPermission */, true /* checkShell */,
13287                "installExistingPackage for user " + userId);
13288        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13289            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13290        }
13291
13292        long callingId = Binder.clearCallingIdentity();
13293        try {
13294            boolean installed = false;
13295            final boolean instantApp =
13296                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13297            final boolean fullApp =
13298                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13299
13300            // writer
13301            synchronized (mPackages) {
13302                pkgSetting = mSettings.mPackages.get(packageName);
13303                if (pkgSetting == null) {
13304                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13305                }
13306                if (!pkgSetting.getInstalled(userId)) {
13307                    pkgSetting.setInstalled(true, userId);
13308                    pkgSetting.setHidden(false, userId);
13309                    pkgSetting.setInstallReason(installReason, userId);
13310                    mSettings.writePackageRestrictionsLPr(userId);
13311                    mSettings.writeKernelMappingLPr(pkgSetting);
13312                    installed = true;
13313                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13314                    // upgrade app from instant to full; we don't allow app downgrade
13315                    installed = true;
13316                }
13317                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13318            }
13319
13320            if (installed) {
13321                if (pkgSetting.pkg != null) {
13322                    synchronized (mInstallLock) {
13323                        // We don't need to freeze for a brand new install
13324                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13325                    }
13326                }
13327                sendPackageAddedForUser(packageName, pkgSetting, userId);
13328                synchronized (mPackages) {
13329                    updateSequenceNumberLP(packageName, new int[]{ userId });
13330                }
13331            }
13332        } finally {
13333            Binder.restoreCallingIdentity(callingId);
13334        }
13335
13336        return PackageManager.INSTALL_SUCCEEDED;
13337    }
13338
13339    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13340            boolean instantApp, boolean fullApp) {
13341        // no state specified; do nothing
13342        if (!instantApp && !fullApp) {
13343            return;
13344        }
13345        if (userId != UserHandle.USER_ALL) {
13346            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13347                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13348            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13349                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13350            }
13351        } else {
13352            for (int currentUserId : sUserManager.getUserIds()) {
13353                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13354                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13355                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13356                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13357                }
13358            }
13359        }
13360    }
13361
13362    boolean isUserRestricted(int userId, String restrictionKey) {
13363        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13364        if (restrictions.getBoolean(restrictionKey, false)) {
13365            Log.w(TAG, "User is restricted: " + restrictionKey);
13366            return true;
13367        }
13368        return false;
13369    }
13370
13371    @Override
13372    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13373            int userId) {
13374        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13376                true /* requireFullPermission */, true /* checkShell */,
13377                "setPackagesSuspended for user " + userId);
13378
13379        if (ArrayUtils.isEmpty(packageNames)) {
13380            return packageNames;
13381        }
13382
13383        // List of package names for whom the suspended state has changed.
13384        List<String> changedPackages = new ArrayList<>(packageNames.length);
13385        // List of package names for whom the suspended state is not set as requested in this
13386        // method.
13387        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13388        long callingId = Binder.clearCallingIdentity();
13389        try {
13390            for (int i = 0; i < packageNames.length; i++) {
13391                String packageName = packageNames[i];
13392                boolean changed = false;
13393                final int appId;
13394                synchronized (mPackages) {
13395                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13396                    if (pkgSetting == null) {
13397                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13398                                + "\". Skipping suspending/un-suspending.");
13399                        unactionedPackages.add(packageName);
13400                        continue;
13401                    }
13402                    appId = pkgSetting.appId;
13403                    if (pkgSetting.getSuspended(userId) != suspended) {
13404                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13405                            unactionedPackages.add(packageName);
13406                            continue;
13407                        }
13408                        pkgSetting.setSuspended(suspended, userId);
13409                        mSettings.writePackageRestrictionsLPr(userId);
13410                        changed = true;
13411                        changedPackages.add(packageName);
13412                    }
13413                }
13414
13415                if (changed && suspended) {
13416                    killApplication(packageName, UserHandle.getUid(userId, appId),
13417                            "suspending package");
13418                }
13419            }
13420        } finally {
13421            Binder.restoreCallingIdentity(callingId);
13422        }
13423
13424        if (!changedPackages.isEmpty()) {
13425            sendPackagesSuspendedForUser(changedPackages.toArray(
13426                    new String[changedPackages.size()]), userId, suspended);
13427        }
13428
13429        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13430    }
13431
13432    @Override
13433    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13435                true /* requireFullPermission */, false /* checkShell */,
13436                "isPackageSuspendedForUser for user " + userId);
13437        synchronized (mPackages) {
13438            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13439            if (pkgSetting == null) {
13440                throw new IllegalArgumentException("Unknown target package: " + packageName);
13441            }
13442            return pkgSetting.getSuspended(userId);
13443        }
13444    }
13445
13446    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13447        if (isPackageDeviceAdmin(packageName, userId)) {
13448            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13449                    + "\": has an active device admin");
13450            return false;
13451        }
13452
13453        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13454        if (packageName.equals(activeLauncherPackageName)) {
13455            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13456                    + "\": contains the active launcher");
13457            return false;
13458        }
13459
13460        if (packageName.equals(mRequiredInstallerPackage)) {
13461            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13462                    + "\": required for package installation");
13463            return false;
13464        }
13465
13466        if (packageName.equals(mRequiredUninstallerPackage)) {
13467            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13468                    + "\": required for package uninstallation");
13469            return false;
13470        }
13471
13472        if (packageName.equals(mRequiredVerifierPackage)) {
13473            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13474                    + "\": required for package verification");
13475            return false;
13476        }
13477
13478        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13479            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13480                    + "\": is the default dialer");
13481            return false;
13482        }
13483
13484        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13485            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13486                    + "\": protected package");
13487            return false;
13488        }
13489
13490        // Cannot suspend static shared libs as they are considered
13491        // a part of the using app (emulating static linking). Also
13492        // static libs are installed always on internal storage.
13493        PackageParser.Package pkg = mPackages.get(packageName);
13494        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13495            Slog.w(TAG, "Cannot suspend package: " + packageName
13496                    + " providing static shared library: "
13497                    + pkg.staticSharedLibName);
13498            return false;
13499        }
13500
13501        return true;
13502    }
13503
13504    private String getActiveLauncherPackageName(int userId) {
13505        Intent intent = new Intent(Intent.ACTION_MAIN);
13506        intent.addCategory(Intent.CATEGORY_HOME);
13507        ResolveInfo resolveInfo = resolveIntent(
13508                intent,
13509                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13510                PackageManager.MATCH_DEFAULT_ONLY,
13511                userId);
13512
13513        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13514    }
13515
13516    private String getDefaultDialerPackageName(int userId) {
13517        synchronized (mPackages) {
13518            return mSettings.getDefaultDialerPackageNameLPw(userId);
13519        }
13520    }
13521
13522    @Override
13523    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13524        mContext.enforceCallingOrSelfPermission(
13525                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13526                "Only package verification agents can verify applications");
13527
13528        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13529        final PackageVerificationResponse response = new PackageVerificationResponse(
13530                verificationCode, Binder.getCallingUid());
13531        msg.arg1 = id;
13532        msg.obj = response;
13533        mHandler.sendMessage(msg);
13534    }
13535
13536    @Override
13537    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13538            long millisecondsToDelay) {
13539        mContext.enforceCallingOrSelfPermission(
13540                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13541                "Only package verification agents can extend verification timeouts");
13542
13543        final PackageVerificationState state = mPendingVerification.get(id);
13544        final PackageVerificationResponse response = new PackageVerificationResponse(
13545                verificationCodeAtTimeout, Binder.getCallingUid());
13546
13547        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13548            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13549        }
13550        if (millisecondsToDelay < 0) {
13551            millisecondsToDelay = 0;
13552        }
13553        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13554                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13555            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13556        }
13557
13558        if ((state != null) && !state.timeoutExtended()) {
13559            state.extendTimeout();
13560
13561            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13562            msg.arg1 = id;
13563            msg.obj = response;
13564            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13565        }
13566    }
13567
13568    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13569            int verificationCode, UserHandle user) {
13570        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13571        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13572        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13573        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13574        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13575
13576        mContext.sendBroadcastAsUser(intent, user,
13577                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13578    }
13579
13580    private ComponentName matchComponentForVerifier(String packageName,
13581            List<ResolveInfo> receivers) {
13582        ActivityInfo targetReceiver = null;
13583
13584        final int NR = receivers.size();
13585        for (int i = 0; i < NR; i++) {
13586            final ResolveInfo info = receivers.get(i);
13587            if (info.activityInfo == null) {
13588                continue;
13589            }
13590
13591            if (packageName.equals(info.activityInfo.packageName)) {
13592                targetReceiver = info.activityInfo;
13593                break;
13594            }
13595        }
13596
13597        if (targetReceiver == null) {
13598            return null;
13599        }
13600
13601        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13602    }
13603
13604    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13605            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13606        if (pkgInfo.verifiers.length == 0) {
13607            return null;
13608        }
13609
13610        final int N = pkgInfo.verifiers.length;
13611        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13612        for (int i = 0; i < N; i++) {
13613            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13614
13615            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13616                    receivers);
13617            if (comp == null) {
13618                continue;
13619            }
13620
13621            final int verifierUid = getUidForVerifier(verifierInfo);
13622            if (verifierUid == -1) {
13623                continue;
13624            }
13625
13626            if (DEBUG_VERIFY) {
13627                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13628                        + " with the correct signature");
13629            }
13630            sufficientVerifiers.add(comp);
13631            verificationState.addSufficientVerifier(verifierUid);
13632        }
13633
13634        return sufficientVerifiers;
13635    }
13636
13637    private int getUidForVerifier(VerifierInfo verifierInfo) {
13638        synchronized (mPackages) {
13639            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13640            if (pkg == null) {
13641                return -1;
13642            } else if (pkg.mSignatures.length != 1) {
13643                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13644                        + " has more than one signature; ignoring");
13645                return -1;
13646            }
13647
13648            /*
13649             * If the public key of the package's signature does not match
13650             * our expected public key, then this is a different package and
13651             * we should skip.
13652             */
13653
13654            final byte[] expectedPublicKey;
13655            try {
13656                final Signature verifierSig = pkg.mSignatures[0];
13657                final PublicKey publicKey = verifierSig.getPublicKey();
13658                expectedPublicKey = publicKey.getEncoded();
13659            } catch (CertificateException e) {
13660                return -1;
13661            }
13662
13663            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13664
13665            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13666                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13667                        + " does not have the expected public key; ignoring");
13668                return -1;
13669            }
13670
13671            return pkg.applicationInfo.uid;
13672        }
13673    }
13674
13675    @Override
13676    public void finishPackageInstall(int token, boolean didLaunch) {
13677        enforceSystemOrRoot("Only the system is allowed to finish installs");
13678
13679        if (DEBUG_INSTALL) {
13680            Slog.v(TAG, "BM finishing package install for " + token);
13681        }
13682        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13683
13684        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13685        mHandler.sendMessage(msg);
13686    }
13687
13688    /**
13689     * Get the verification agent timeout.
13690     *
13691     * @return verification timeout in milliseconds
13692     */
13693    private long getVerificationTimeout() {
13694        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13695                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13696                DEFAULT_VERIFICATION_TIMEOUT);
13697    }
13698
13699    /**
13700     * Get the default verification agent response code.
13701     *
13702     * @return default verification response code
13703     */
13704    private int getDefaultVerificationResponse() {
13705        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13706                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13707                DEFAULT_VERIFICATION_RESPONSE);
13708    }
13709
13710    /**
13711     * Check whether or not package verification has been enabled.
13712     *
13713     * @return true if verification should be performed
13714     */
13715    private boolean isVerificationEnabled(int userId, int installFlags) {
13716        if (!DEFAULT_VERIFY_ENABLE) {
13717            return false;
13718        }
13719        // Ephemeral apps don't get the full verification treatment
13720        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13721            if (DEBUG_EPHEMERAL) {
13722                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13723            }
13724            return false;
13725        }
13726
13727        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13728
13729        // Check if installing from ADB
13730        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13731            // Do not run verification in a test harness environment
13732            if (ActivityManager.isRunningInTestHarness()) {
13733                return false;
13734            }
13735            if (ensureVerifyAppsEnabled) {
13736                return true;
13737            }
13738            // Check if the developer does not want package verification for ADB installs
13739            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13740                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13741                return false;
13742            }
13743        }
13744
13745        if (ensureVerifyAppsEnabled) {
13746            return true;
13747        }
13748
13749        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13750                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13751    }
13752
13753    @Override
13754    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13755            throws RemoteException {
13756        mContext.enforceCallingOrSelfPermission(
13757                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13758                "Only intentfilter verification agents can verify applications");
13759
13760        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13761        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13762                Binder.getCallingUid(), verificationCode, failedDomains);
13763        msg.arg1 = id;
13764        msg.obj = response;
13765        mHandler.sendMessage(msg);
13766    }
13767
13768    @Override
13769    public int getIntentVerificationStatus(String packageName, int userId) {
13770        synchronized (mPackages) {
13771            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13772        }
13773    }
13774
13775    @Override
13776    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13777        mContext.enforceCallingOrSelfPermission(
13778                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13779
13780        boolean result = false;
13781        synchronized (mPackages) {
13782            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13783        }
13784        if (result) {
13785            scheduleWritePackageRestrictionsLocked(userId);
13786        }
13787        return result;
13788    }
13789
13790    @Override
13791    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13792            String packageName) {
13793        synchronized (mPackages) {
13794            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13795        }
13796    }
13797
13798    @Override
13799    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13800        if (TextUtils.isEmpty(packageName)) {
13801            return ParceledListSlice.emptyList();
13802        }
13803        synchronized (mPackages) {
13804            PackageParser.Package pkg = mPackages.get(packageName);
13805            if (pkg == null || pkg.activities == null) {
13806                return ParceledListSlice.emptyList();
13807            }
13808            final int count = pkg.activities.size();
13809            ArrayList<IntentFilter> result = new ArrayList<>();
13810            for (int n=0; n<count; n++) {
13811                PackageParser.Activity activity = pkg.activities.get(n);
13812                if (activity.intents != null && activity.intents.size() > 0) {
13813                    result.addAll(activity.intents);
13814                }
13815            }
13816            return new ParceledListSlice<>(result);
13817        }
13818    }
13819
13820    @Override
13821    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13822        mContext.enforceCallingOrSelfPermission(
13823                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13824
13825        synchronized (mPackages) {
13826            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13827            if (packageName != null) {
13828                result |= updateIntentVerificationStatus(packageName,
13829                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13830                        userId);
13831                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13832                        packageName, userId);
13833            }
13834            return result;
13835        }
13836    }
13837
13838    @Override
13839    public String getDefaultBrowserPackageName(int userId) {
13840        synchronized (mPackages) {
13841            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13842        }
13843    }
13844
13845    /**
13846     * Get the "allow unknown sources" setting.
13847     *
13848     * @return the current "allow unknown sources" setting
13849     */
13850    private int getUnknownSourcesSettings() {
13851        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13852                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13853                -1);
13854    }
13855
13856    @Override
13857    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13858        final int uid = Binder.getCallingUid();
13859        // writer
13860        synchronized (mPackages) {
13861            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13862            if (targetPackageSetting == null) {
13863                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13864            }
13865
13866            PackageSetting installerPackageSetting;
13867            if (installerPackageName != null) {
13868                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13869                if (installerPackageSetting == null) {
13870                    throw new IllegalArgumentException("Unknown installer package: "
13871                            + installerPackageName);
13872                }
13873            } else {
13874                installerPackageSetting = null;
13875            }
13876
13877            Signature[] callerSignature;
13878            Object obj = mSettings.getUserIdLPr(uid);
13879            if (obj != null) {
13880                if (obj instanceof SharedUserSetting) {
13881                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13882                } else if (obj instanceof PackageSetting) {
13883                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13884                } else {
13885                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13886                }
13887            } else {
13888                throw new SecurityException("Unknown calling UID: " + uid);
13889            }
13890
13891            // Verify: can't set installerPackageName to a package that is
13892            // not signed with the same cert as the caller.
13893            if (installerPackageSetting != null) {
13894                if (compareSignatures(callerSignature,
13895                        installerPackageSetting.signatures.mSignatures)
13896                        != PackageManager.SIGNATURE_MATCH) {
13897                    throw new SecurityException(
13898                            "Caller does not have same cert as new installer package "
13899                            + installerPackageName);
13900                }
13901            }
13902
13903            // Verify: if target already has an installer package, it must
13904            // be signed with the same cert as the caller.
13905            if (targetPackageSetting.installerPackageName != null) {
13906                PackageSetting setting = mSettings.mPackages.get(
13907                        targetPackageSetting.installerPackageName);
13908                // If the currently set package isn't valid, then it's always
13909                // okay to change it.
13910                if (setting != null) {
13911                    if (compareSignatures(callerSignature,
13912                            setting.signatures.mSignatures)
13913                            != PackageManager.SIGNATURE_MATCH) {
13914                        throw new SecurityException(
13915                                "Caller does not have same cert as old installer package "
13916                                + targetPackageSetting.installerPackageName);
13917                    }
13918                }
13919            }
13920
13921            // Okay!
13922            targetPackageSetting.installerPackageName = installerPackageName;
13923            if (installerPackageName != null) {
13924                mSettings.mInstallerPackages.add(installerPackageName);
13925            }
13926            scheduleWriteSettingsLocked();
13927        }
13928    }
13929
13930    @Override
13931    public void setApplicationCategoryHint(String packageName, int categoryHint,
13932            String callerPackageName) {
13933        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13934                callerPackageName);
13935        synchronized (mPackages) {
13936            PackageSetting ps = mSettings.mPackages.get(packageName);
13937            if (ps == null) {
13938                throw new IllegalArgumentException("Unknown target package " + packageName);
13939            }
13940
13941            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13942                throw new IllegalArgumentException("Calling package " + callerPackageName
13943                        + " is not installer for " + packageName);
13944            }
13945
13946            if (ps.categoryHint != categoryHint) {
13947                ps.categoryHint = categoryHint;
13948                scheduleWriteSettingsLocked();
13949            }
13950        }
13951    }
13952
13953    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13954        // Queue up an async operation since the package installation may take a little while.
13955        mHandler.post(new Runnable() {
13956            public void run() {
13957                mHandler.removeCallbacks(this);
13958                 // Result object to be returned
13959                PackageInstalledInfo res = new PackageInstalledInfo();
13960                res.setReturnCode(currentStatus);
13961                res.uid = -1;
13962                res.pkg = null;
13963                res.removedInfo = null;
13964                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13965                    args.doPreInstall(res.returnCode);
13966                    synchronized (mInstallLock) {
13967                        installPackageTracedLI(args, res);
13968                    }
13969                    args.doPostInstall(res.returnCode, res.uid);
13970                }
13971
13972                // A restore should be performed at this point if (a) the install
13973                // succeeded, (b) the operation is not an update, and (c) the new
13974                // package has not opted out of backup participation.
13975                final boolean update = res.removedInfo != null
13976                        && res.removedInfo.removedPackage != null;
13977                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13978                boolean doRestore = !update
13979                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13980
13981                // Set up the post-install work request bookkeeping.  This will be used
13982                // and cleaned up by the post-install event handling regardless of whether
13983                // there's a restore pass performed.  Token values are >= 1.
13984                int token;
13985                if (mNextInstallToken < 0) mNextInstallToken = 1;
13986                token = mNextInstallToken++;
13987
13988                PostInstallData data = new PostInstallData(args, res);
13989                mRunningInstalls.put(token, data);
13990                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13991
13992                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13993                    // Pass responsibility to the Backup Manager.  It will perform a
13994                    // restore if appropriate, then pass responsibility back to the
13995                    // Package Manager to run the post-install observer callbacks
13996                    // and broadcasts.
13997                    IBackupManager bm = IBackupManager.Stub.asInterface(
13998                            ServiceManager.getService(Context.BACKUP_SERVICE));
13999                    if (bm != null) {
14000                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14001                                + " to BM for possible restore");
14002                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14003                        try {
14004                            // TODO: http://b/22388012
14005                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14006                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14007                            } else {
14008                                doRestore = false;
14009                            }
14010                        } catch (RemoteException e) {
14011                            // can't happen; the backup manager is local
14012                        } catch (Exception e) {
14013                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14014                            doRestore = false;
14015                        }
14016                    } else {
14017                        Slog.e(TAG, "Backup Manager not found!");
14018                        doRestore = false;
14019                    }
14020                }
14021
14022                if (!doRestore) {
14023                    // No restore possible, or the Backup Manager was mysteriously not
14024                    // available -- just fire the post-install work request directly.
14025                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14026
14027                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14028
14029                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14030                    mHandler.sendMessage(msg);
14031                }
14032            }
14033        });
14034    }
14035
14036    /**
14037     * Callback from PackageSettings whenever an app is first transitioned out of the
14038     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14039     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14040     * here whether the app is the target of an ongoing install, and only send the
14041     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14042     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14043     * handling.
14044     */
14045    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14046        // Serialize this with the rest of the install-process message chain.  In the
14047        // restore-at-install case, this Runnable will necessarily run before the
14048        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14049        // are coherent.  In the non-restore case, the app has already completed install
14050        // and been launched through some other means, so it is not in a problematic
14051        // state for observers to see the FIRST_LAUNCH signal.
14052        mHandler.post(new Runnable() {
14053            @Override
14054            public void run() {
14055                for (int i = 0; i < mRunningInstalls.size(); i++) {
14056                    final PostInstallData data = mRunningInstalls.valueAt(i);
14057                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14058                        continue;
14059                    }
14060                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14061                        // right package; but is it for the right user?
14062                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14063                            if (userId == data.res.newUsers[uIndex]) {
14064                                if (DEBUG_BACKUP) {
14065                                    Slog.i(TAG, "Package " + pkgName
14066                                            + " being restored so deferring FIRST_LAUNCH");
14067                                }
14068                                return;
14069                            }
14070                        }
14071                    }
14072                }
14073                // didn't find it, so not being restored
14074                if (DEBUG_BACKUP) {
14075                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14076                }
14077                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14078            }
14079        });
14080    }
14081
14082    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14083        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14084                installerPkg, null, userIds);
14085    }
14086
14087    private abstract class HandlerParams {
14088        private static final int MAX_RETRIES = 4;
14089
14090        /**
14091         * Number of times startCopy() has been attempted and had a non-fatal
14092         * error.
14093         */
14094        private int mRetries = 0;
14095
14096        /** User handle for the user requesting the information or installation. */
14097        private final UserHandle mUser;
14098        String traceMethod;
14099        int traceCookie;
14100
14101        HandlerParams(UserHandle user) {
14102            mUser = user;
14103        }
14104
14105        UserHandle getUser() {
14106            return mUser;
14107        }
14108
14109        HandlerParams setTraceMethod(String traceMethod) {
14110            this.traceMethod = traceMethod;
14111            return this;
14112        }
14113
14114        HandlerParams setTraceCookie(int traceCookie) {
14115            this.traceCookie = traceCookie;
14116            return this;
14117        }
14118
14119        final boolean startCopy() {
14120            boolean res;
14121            try {
14122                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14123
14124                if (++mRetries > MAX_RETRIES) {
14125                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14126                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14127                    handleServiceError();
14128                    return false;
14129                } else {
14130                    handleStartCopy();
14131                    res = true;
14132                }
14133            } catch (RemoteException e) {
14134                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14135                mHandler.sendEmptyMessage(MCS_RECONNECT);
14136                res = false;
14137            }
14138            handleReturnCode();
14139            return res;
14140        }
14141
14142        final void serviceError() {
14143            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14144            handleServiceError();
14145            handleReturnCode();
14146        }
14147
14148        abstract void handleStartCopy() throws RemoteException;
14149        abstract void handleServiceError();
14150        abstract void handleReturnCode();
14151    }
14152
14153    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14154        for (File path : paths) {
14155            try {
14156                mcs.clearDirectory(path.getAbsolutePath());
14157            } catch (RemoteException e) {
14158            }
14159        }
14160    }
14161
14162    static class OriginInfo {
14163        /**
14164         * Location where install is coming from, before it has been
14165         * copied/renamed into place. This could be a single monolithic APK
14166         * file, or a cluster directory. This location may be untrusted.
14167         */
14168        final File file;
14169        final String cid;
14170
14171        /**
14172         * Flag indicating that {@link #file} or {@link #cid} has already been
14173         * staged, meaning downstream users don't need to defensively copy the
14174         * contents.
14175         */
14176        final boolean staged;
14177
14178        /**
14179         * Flag indicating that {@link #file} or {@link #cid} is an already
14180         * installed app that is being moved.
14181         */
14182        final boolean existing;
14183
14184        final String resolvedPath;
14185        final File resolvedFile;
14186
14187        static OriginInfo fromNothing() {
14188            return new OriginInfo(null, null, false, false);
14189        }
14190
14191        static OriginInfo fromUntrustedFile(File file) {
14192            return new OriginInfo(file, null, false, false);
14193        }
14194
14195        static OriginInfo fromExistingFile(File file) {
14196            return new OriginInfo(file, null, false, true);
14197        }
14198
14199        static OriginInfo fromStagedFile(File file) {
14200            return new OriginInfo(file, null, true, false);
14201        }
14202
14203        static OriginInfo fromStagedContainer(String cid) {
14204            return new OriginInfo(null, cid, true, false);
14205        }
14206
14207        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14208            this.file = file;
14209            this.cid = cid;
14210            this.staged = staged;
14211            this.existing = existing;
14212
14213            if (cid != null) {
14214                resolvedPath = PackageHelper.getSdDir(cid);
14215                resolvedFile = new File(resolvedPath);
14216            } else if (file != null) {
14217                resolvedPath = file.getAbsolutePath();
14218                resolvedFile = file;
14219            } else {
14220                resolvedPath = null;
14221                resolvedFile = null;
14222            }
14223        }
14224    }
14225
14226    static class MoveInfo {
14227        final int moveId;
14228        final String fromUuid;
14229        final String toUuid;
14230        final String packageName;
14231        final String dataAppName;
14232        final int appId;
14233        final String seinfo;
14234        final int targetSdkVersion;
14235
14236        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14237                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14238            this.moveId = moveId;
14239            this.fromUuid = fromUuid;
14240            this.toUuid = toUuid;
14241            this.packageName = packageName;
14242            this.dataAppName = dataAppName;
14243            this.appId = appId;
14244            this.seinfo = seinfo;
14245            this.targetSdkVersion = targetSdkVersion;
14246        }
14247    }
14248
14249    static class VerificationInfo {
14250        /** A constant used to indicate that a uid value is not present. */
14251        public static final int NO_UID = -1;
14252
14253        /** URI referencing where the package was downloaded from. */
14254        final Uri originatingUri;
14255
14256        /** HTTP referrer URI associated with the originatingURI. */
14257        final Uri referrer;
14258
14259        /** UID of the application that the install request originated from. */
14260        final int originatingUid;
14261
14262        /** UID of application requesting the install */
14263        final int installerUid;
14264
14265        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14266            this.originatingUri = originatingUri;
14267            this.referrer = referrer;
14268            this.originatingUid = originatingUid;
14269            this.installerUid = installerUid;
14270        }
14271    }
14272
14273    class InstallParams extends HandlerParams {
14274        final OriginInfo origin;
14275        final MoveInfo move;
14276        final IPackageInstallObserver2 observer;
14277        int installFlags;
14278        final String installerPackageName;
14279        final String volumeUuid;
14280        private InstallArgs mArgs;
14281        private int mRet;
14282        final String packageAbiOverride;
14283        final String[] grantedRuntimePermissions;
14284        final VerificationInfo verificationInfo;
14285        final Certificate[][] certificates;
14286        final int installReason;
14287
14288        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14289                int installFlags, String installerPackageName, String volumeUuid,
14290                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14291                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14292            super(user);
14293            this.origin = origin;
14294            this.move = move;
14295            this.observer = observer;
14296            this.installFlags = installFlags;
14297            this.installerPackageName = installerPackageName;
14298            this.volumeUuid = volumeUuid;
14299            this.verificationInfo = verificationInfo;
14300            this.packageAbiOverride = packageAbiOverride;
14301            this.grantedRuntimePermissions = grantedPermissions;
14302            this.certificates = certificates;
14303            this.installReason = installReason;
14304        }
14305
14306        @Override
14307        public String toString() {
14308            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14309                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14310        }
14311
14312        private int installLocationPolicy(PackageInfoLite pkgLite) {
14313            String packageName = pkgLite.packageName;
14314            int installLocation = pkgLite.installLocation;
14315            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14316            // reader
14317            synchronized (mPackages) {
14318                // Currently installed package which the new package is attempting to replace or
14319                // null if no such package is installed.
14320                PackageParser.Package installedPkg = mPackages.get(packageName);
14321                // Package which currently owns the data which the new package will own if installed.
14322                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14323                // will be null whereas dataOwnerPkg will contain information about the package
14324                // which was uninstalled while keeping its data.
14325                PackageParser.Package dataOwnerPkg = installedPkg;
14326                if (dataOwnerPkg  == null) {
14327                    PackageSetting ps = mSettings.mPackages.get(packageName);
14328                    if (ps != null) {
14329                        dataOwnerPkg = ps.pkg;
14330                    }
14331                }
14332
14333                if (dataOwnerPkg != null) {
14334                    // If installed, the package will get access to data left on the device by its
14335                    // predecessor. As a security measure, this is permited only if this is not a
14336                    // version downgrade or if the predecessor package is marked as debuggable and
14337                    // a downgrade is explicitly requested.
14338                    //
14339                    // On debuggable platform builds, downgrades are permitted even for
14340                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14341                    // not offer security guarantees and thus it's OK to disable some security
14342                    // mechanisms to make debugging/testing easier on those builds. However, even on
14343                    // debuggable builds downgrades of packages are permitted only if requested via
14344                    // installFlags. This is because we aim to keep the behavior of debuggable
14345                    // platform builds as close as possible to the behavior of non-debuggable
14346                    // platform builds.
14347                    final boolean downgradeRequested =
14348                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14349                    final boolean packageDebuggable =
14350                                (dataOwnerPkg.applicationInfo.flags
14351                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14352                    final boolean downgradePermitted =
14353                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14354                    if (!downgradePermitted) {
14355                        try {
14356                            checkDowngrade(dataOwnerPkg, pkgLite);
14357                        } catch (PackageManagerException e) {
14358                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14359                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14360                        }
14361                    }
14362                }
14363
14364                if (installedPkg != null) {
14365                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14366                        // Check for updated system application.
14367                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14368                            if (onSd) {
14369                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14370                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14371                            }
14372                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14373                        } else {
14374                            if (onSd) {
14375                                // Install flag overrides everything.
14376                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14377                            }
14378                            // If current upgrade specifies particular preference
14379                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14380                                // Application explicitly specified internal.
14381                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14382                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14383                                // App explictly prefers external. Let policy decide
14384                            } else {
14385                                // Prefer previous location
14386                                if (isExternal(installedPkg)) {
14387                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14388                                }
14389                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14390                            }
14391                        }
14392                    } else {
14393                        // Invalid install. Return error code
14394                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14395                    }
14396                }
14397            }
14398            // All the special cases have been taken care of.
14399            // Return result based on recommended install location.
14400            if (onSd) {
14401                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14402            }
14403            return pkgLite.recommendedInstallLocation;
14404        }
14405
14406        /*
14407         * Invoke remote method to get package information and install
14408         * location values. Override install location based on default
14409         * policy if needed and then create install arguments based
14410         * on the install location.
14411         */
14412        public void handleStartCopy() throws RemoteException {
14413            int ret = PackageManager.INSTALL_SUCCEEDED;
14414
14415            // If we're already staged, we've firmly committed to an install location
14416            if (origin.staged) {
14417                if (origin.file != null) {
14418                    installFlags |= PackageManager.INSTALL_INTERNAL;
14419                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14420                } else if (origin.cid != null) {
14421                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14422                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14423                } else {
14424                    throw new IllegalStateException("Invalid stage location");
14425                }
14426            }
14427
14428            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14429            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14430            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14431            PackageInfoLite pkgLite = null;
14432
14433            if (onInt && onSd) {
14434                // Check if both bits are set.
14435                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14436                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14437            } else if (onSd && ephemeral) {
14438                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14439                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14440            } else {
14441                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14442                        packageAbiOverride);
14443
14444                if (DEBUG_EPHEMERAL && ephemeral) {
14445                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14446                }
14447
14448                /*
14449                 * If we have too little free space, try to free cache
14450                 * before giving up.
14451                 */
14452                if (!origin.staged && pkgLite.recommendedInstallLocation
14453                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14454                    // TODO: focus freeing disk space on the target device
14455                    final StorageManager storage = StorageManager.from(mContext);
14456                    final long lowThreshold = storage.getStorageLowBytes(
14457                            Environment.getDataDirectory());
14458
14459                    final long sizeBytes = mContainerService.calculateInstalledSize(
14460                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14461
14462                    try {
14463                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14464                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14465                                installFlags, packageAbiOverride);
14466                    } catch (InstallerException e) {
14467                        Slog.w(TAG, "Failed to free cache", e);
14468                    }
14469
14470                    /*
14471                     * The cache free must have deleted the file we
14472                     * downloaded to install.
14473                     *
14474                     * TODO: fix the "freeCache" call to not delete
14475                     *       the file we care about.
14476                     */
14477                    if (pkgLite.recommendedInstallLocation
14478                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14479                        pkgLite.recommendedInstallLocation
14480                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14481                    }
14482                }
14483            }
14484
14485            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14486                int loc = pkgLite.recommendedInstallLocation;
14487                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14488                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14489                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14490                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14491                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14492                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14493                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14494                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14495                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14496                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14497                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14498                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14499                } else {
14500                    // Override with defaults if needed.
14501                    loc = installLocationPolicy(pkgLite);
14502                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14503                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14504                    } else if (!onSd && !onInt) {
14505                        // Override install location with flags
14506                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14507                            // Set the flag to install on external media.
14508                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14509                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14510                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14511                            if (DEBUG_EPHEMERAL) {
14512                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14513                            }
14514                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14515                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14516                                    |PackageManager.INSTALL_INTERNAL);
14517                        } else {
14518                            // Make sure the flag for installing on external
14519                            // media is unset
14520                            installFlags |= PackageManager.INSTALL_INTERNAL;
14521                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14522                        }
14523                    }
14524                }
14525            }
14526
14527            final InstallArgs args = createInstallArgs(this);
14528            mArgs = args;
14529
14530            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14531                // TODO: http://b/22976637
14532                // Apps installed for "all" users use the device owner to verify the app
14533                UserHandle verifierUser = getUser();
14534                if (verifierUser == UserHandle.ALL) {
14535                    verifierUser = UserHandle.SYSTEM;
14536                }
14537
14538                /*
14539                 * Determine if we have any installed package verifiers. If we
14540                 * do, then we'll defer to them to verify the packages.
14541                 */
14542                final int requiredUid = mRequiredVerifierPackage == null ? -1
14543                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14544                                verifierUser.getIdentifier());
14545                if (!origin.existing && requiredUid != -1
14546                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14547                    final Intent verification = new Intent(
14548                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14549                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14550                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14551                            PACKAGE_MIME_TYPE);
14552                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14553
14554                    // Query all live verifiers based on current user state
14555                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14556                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14557
14558                    if (DEBUG_VERIFY) {
14559                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14560                                + verification.toString() + " with " + pkgLite.verifiers.length
14561                                + " optional verifiers");
14562                    }
14563
14564                    final int verificationId = mPendingVerificationToken++;
14565
14566                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14567
14568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14569                            installerPackageName);
14570
14571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14572                            installFlags);
14573
14574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14575                            pkgLite.packageName);
14576
14577                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14578                            pkgLite.versionCode);
14579
14580                    if (verificationInfo != null) {
14581                        if (verificationInfo.originatingUri != null) {
14582                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14583                                    verificationInfo.originatingUri);
14584                        }
14585                        if (verificationInfo.referrer != null) {
14586                            verification.putExtra(Intent.EXTRA_REFERRER,
14587                                    verificationInfo.referrer);
14588                        }
14589                        if (verificationInfo.originatingUid >= 0) {
14590                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14591                                    verificationInfo.originatingUid);
14592                        }
14593                        if (verificationInfo.installerUid >= 0) {
14594                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14595                                    verificationInfo.installerUid);
14596                        }
14597                    }
14598
14599                    final PackageVerificationState verificationState = new PackageVerificationState(
14600                            requiredUid, args);
14601
14602                    mPendingVerification.append(verificationId, verificationState);
14603
14604                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14605                            receivers, verificationState);
14606
14607                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14608                    final long idleDuration = getVerificationTimeout();
14609
14610                    /*
14611                     * If any sufficient verifiers were listed in the package
14612                     * manifest, attempt to ask them.
14613                     */
14614                    if (sufficientVerifiers != null) {
14615                        final int N = sufficientVerifiers.size();
14616                        if (N == 0) {
14617                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14618                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14619                        } else {
14620                            for (int i = 0; i < N; i++) {
14621                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14622                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14623                                        verifierComponent.getPackageName(), idleDuration,
14624                                        verifierUser.getIdentifier(), false, "package verifier");
14625
14626                                final Intent sufficientIntent = new Intent(verification);
14627                                sufficientIntent.setComponent(verifierComponent);
14628                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14629                            }
14630                        }
14631                    }
14632
14633                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14634                            mRequiredVerifierPackage, receivers);
14635                    if (ret == PackageManager.INSTALL_SUCCEEDED
14636                            && mRequiredVerifierPackage != null) {
14637                        Trace.asyncTraceBegin(
14638                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14639                        /*
14640                         * Send the intent to the required verification agent,
14641                         * but only start the verification timeout after the
14642                         * target BroadcastReceivers have run.
14643                         */
14644                        verification.setComponent(requiredVerifierComponent);
14645                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14646                                requiredVerifierComponent.getPackageName(), idleDuration,
14647                                verifierUser.getIdentifier(), false, "package verifier");
14648                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14649                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14650                                new BroadcastReceiver() {
14651                                    @Override
14652                                    public void onReceive(Context context, Intent intent) {
14653                                        final Message msg = mHandler
14654                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14655                                        msg.arg1 = verificationId;
14656                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14657                                    }
14658                                }, null, 0, null, null);
14659
14660                        /*
14661                         * We don't want the copy to proceed until verification
14662                         * succeeds, so null out this field.
14663                         */
14664                        mArgs = null;
14665                    }
14666                } else {
14667                    /*
14668                     * No package verification is enabled, so immediately start
14669                     * the remote call to initiate copy using temporary file.
14670                     */
14671                    ret = args.copyApk(mContainerService, true);
14672                }
14673            }
14674
14675            mRet = ret;
14676        }
14677
14678        @Override
14679        void handleReturnCode() {
14680            // If mArgs is null, then MCS couldn't be reached. When it
14681            // reconnects, it will try again to install. At that point, this
14682            // will succeed.
14683            if (mArgs != null) {
14684                processPendingInstall(mArgs, mRet);
14685            }
14686        }
14687
14688        @Override
14689        void handleServiceError() {
14690            mArgs = createInstallArgs(this);
14691            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14692        }
14693
14694        public boolean isForwardLocked() {
14695            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14696        }
14697    }
14698
14699    /**
14700     * Used during creation of InstallArgs
14701     *
14702     * @param installFlags package installation flags
14703     * @return true if should be installed on external storage
14704     */
14705    private static boolean installOnExternalAsec(int installFlags) {
14706        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14707            return false;
14708        }
14709        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14710            return true;
14711        }
14712        return false;
14713    }
14714
14715    /**
14716     * Used during creation of InstallArgs
14717     *
14718     * @param installFlags package installation flags
14719     * @return true if should be installed as forward locked
14720     */
14721    private static boolean installForwardLocked(int installFlags) {
14722        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14723    }
14724
14725    private InstallArgs createInstallArgs(InstallParams params) {
14726        if (params.move != null) {
14727            return new MoveInstallArgs(params);
14728        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14729            return new AsecInstallArgs(params);
14730        } else {
14731            return new FileInstallArgs(params);
14732        }
14733    }
14734
14735    /**
14736     * Create args that describe an existing installed package. Typically used
14737     * when cleaning up old installs, or used as a move source.
14738     */
14739    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14740            String resourcePath, String[] instructionSets) {
14741        final boolean isInAsec;
14742        if (installOnExternalAsec(installFlags)) {
14743            /* Apps on SD card are always in ASEC containers. */
14744            isInAsec = true;
14745        } else if (installForwardLocked(installFlags)
14746                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14747            /*
14748             * Forward-locked apps are only in ASEC containers if they're the
14749             * new style
14750             */
14751            isInAsec = true;
14752        } else {
14753            isInAsec = false;
14754        }
14755
14756        if (isInAsec) {
14757            return new AsecInstallArgs(codePath, instructionSets,
14758                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14759        } else {
14760            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14761        }
14762    }
14763
14764    static abstract class InstallArgs {
14765        /** @see InstallParams#origin */
14766        final OriginInfo origin;
14767        /** @see InstallParams#move */
14768        final MoveInfo move;
14769
14770        final IPackageInstallObserver2 observer;
14771        // Always refers to PackageManager flags only
14772        final int installFlags;
14773        final String installerPackageName;
14774        final String volumeUuid;
14775        final UserHandle user;
14776        final String abiOverride;
14777        final String[] installGrantPermissions;
14778        /** If non-null, drop an async trace when the install completes */
14779        final String traceMethod;
14780        final int traceCookie;
14781        final Certificate[][] certificates;
14782        final int installReason;
14783
14784        // The list of instruction sets supported by this app. This is currently
14785        // only used during the rmdex() phase to clean up resources. We can get rid of this
14786        // if we move dex files under the common app path.
14787        /* nullable */ String[] instructionSets;
14788
14789        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14790                int installFlags, String installerPackageName, String volumeUuid,
14791                UserHandle user, String[] instructionSets,
14792                String abiOverride, String[] installGrantPermissions,
14793                String traceMethod, int traceCookie, Certificate[][] certificates,
14794                int installReason) {
14795            this.origin = origin;
14796            this.move = move;
14797            this.installFlags = installFlags;
14798            this.observer = observer;
14799            this.installerPackageName = installerPackageName;
14800            this.volumeUuid = volumeUuid;
14801            this.user = user;
14802            this.instructionSets = instructionSets;
14803            this.abiOverride = abiOverride;
14804            this.installGrantPermissions = installGrantPermissions;
14805            this.traceMethod = traceMethod;
14806            this.traceCookie = traceCookie;
14807            this.certificates = certificates;
14808            this.installReason = installReason;
14809        }
14810
14811        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14812        abstract int doPreInstall(int status);
14813
14814        /**
14815         * Rename package into final resting place. All paths on the given
14816         * scanned package should be updated to reflect the rename.
14817         */
14818        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14819        abstract int doPostInstall(int status, int uid);
14820
14821        /** @see PackageSettingBase#codePathString */
14822        abstract String getCodePath();
14823        /** @see PackageSettingBase#resourcePathString */
14824        abstract String getResourcePath();
14825
14826        // Need installer lock especially for dex file removal.
14827        abstract void cleanUpResourcesLI();
14828        abstract boolean doPostDeleteLI(boolean delete);
14829
14830        /**
14831         * Called before the source arguments are copied. This is used mostly
14832         * for MoveParams when it needs to read the source file to put it in the
14833         * destination.
14834         */
14835        int doPreCopy() {
14836            return PackageManager.INSTALL_SUCCEEDED;
14837        }
14838
14839        /**
14840         * Called after the source arguments are copied. This is used mostly for
14841         * MoveParams when it needs to read the source file to put it in the
14842         * destination.
14843         */
14844        int doPostCopy(int uid) {
14845            return PackageManager.INSTALL_SUCCEEDED;
14846        }
14847
14848        protected boolean isFwdLocked() {
14849            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14850        }
14851
14852        protected boolean isExternalAsec() {
14853            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14854        }
14855
14856        protected boolean isEphemeral() {
14857            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14858        }
14859
14860        UserHandle getUser() {
14861            return user;
14862        }
14863    }
14864
14865    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14866        if (!allCodePaths.isEmpty()) {
14867            if (instructionSets == null) {
14868                throw new IllegalStateException("instructionSet == null");
14869            }
14870            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14871            for (String codePath : allCodePaths) {
14872                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14873                    try {
14874                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14875                    } catch (InstallerException ignored) {
14876                    }
14877                }
14878            }
14879        }
14880    }
14881
14882    /**
14883     * Logic to handle installation of non-ASEC applications, including copying
14884     * and renaming logic.
14885     */
14886    class FileInstallArgs extends InstallArgs {
14887        private File codeFile;
14888        private File resourceFile;
14889
14890        // Example topology:
14891        // /data/app/com.example/base.apk
14892        // /data/app/com.example/split_foo.apk
14893        // /data/app/com.example/lib/arm/libfoo.so
14894        // /data/app/com.example/lib/arm64/libfoo.so
14895        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14896
14897        /** New install */
14898        FileInstallArgs(InstallParams params) {
14899            super(params.origin, params.move, params.observer, params.installFlags,
14900                    params.installerPackageName, params.volumeUuid,
14901                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14902                    params.grantedRuntimePermissions,
14903                    params.traceMethod, params.traceCookie, params.certificates,
14904                    params.installReason);
14905            if (isFwdLocked()) {
14906                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14907            }
14908        }
14909
14910        /** Existing install */
14911        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14912            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14913                    null, null, null, 0, null /*certificates*/,
14914                    PackageManager.INSTALL_REASON_UNKNOWN);
14915            this.codeFile = (codePath != null) ? new File(codePath) : null;
14916            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14917        }
14918
14919        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14920            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14921            try {
14922                return doCopyApk(imcs, temp);
14923            } finally {
14924                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14925            }
14926        }
14927
14928        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14929            if (origin.staged) {
14930                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14931                codeFile = origin.file;
14932                resourceFile = origin.file;
14933                return PackageManager.INSTALL_SUCCEEDED;
14934            }
14935
14936            try {
14937                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14938                final File tempDir =
14939                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14940                codeFile = tempDir;
14941                resourceFile = tempDir;
14942            } catch (IOException e) {
14943                Slog.w(TAG, "Failed to create copy file: " + e);
14944                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14945            }
14946
14947            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14948                @Override
14949                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14950                    if (!FileUtils.isValidExtFilename(name)) {
14951                        throw new IllegalArgumentException("Invalid filename: " + name);
14952                    }
14953                    try {
14954                        final File file = new File(codeFile, name);
14955                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14956                                O_RDWR | O_CREAT, 0644);
14957                        Os.chmod(file.getAbsolutePath(), 0644);
14958                        return new ParcelFileDescriptor(fd);
14959                    } catch (ErrnoException e) {
14960                        throw new RemoteException("Failed to open: " + e.getMessage());
14961                    }
14962                }
14963            };
14964
14965            int ret = PackageManager.INSTALL_SUCCEEDED;
14966            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14967            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14968                Slog.e(TAG, "Failed to copy package");
14969                return ret;
14970            }
14971
14972            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14973            NativeLibraryHelper.Handle handle = null;
14974            try {
14975                handle = NativeLibraryHelper.Handle.create(codeFile);
14976                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14977                        abiOverride);
14978            } catch (IOException e) {
14979                Slog.e(TAG, "Copying native libraries failed", e);
14980                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14981            } finally {
14982                IoUtils.closeQuietly(handle);
14983            }
14984
14985            return ret;
14986        }
14987
14988        int doPreInstall(int status) {
14989            if (status != PackageManager.INSTALL_SUCCEEDED) {
14990                cleanUp();
14991            }
14992            return status;
14993        }
14994
14995        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14996            if (status != PackageManager.INSTALL_SUCCEEDED) {
14997                cleanUp();
14998                return false;
14999            }
15000
15001            final File targetDir = codeFile.getParentFile();
15002            final File beforeCodeFile = codeFile;
15003            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15004
15005            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15006            try {
15007                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15008            } catch (ErrnoException e) {
15009                Slog.w(TAG, "Failed to rename", e);
15010                return false;
15011            }
15012
15013            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15014                Slog.w(TAG, "Failed to restorecon");
15015                return false;
15016            }
15017
15018            // Reflect the rename internally
15019            codeFile = afterCodeFile;
15020            resourceFile = afterCodeFile;
15021
15022            // Reflect the rename in scanned details
15023            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15024            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15025                    afterCodeFile, pkg.baseCodePath));
15026            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15027                    afterCodeFile, pkg.splitCodePaths));
15028
15029            // Reflect the rename in app info
15030            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15031            pkg.setApplicationInfoCodePath(pkg.codePath);
15032            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15033            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15034            pkg.setApplicationInfoResourcePath(pkg.codePath);
15035            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15036            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15037
15038            return true;
15039        }
15040
15041        int doPostInstall(int status, int uid) {
15042            if (status != PackageManager.INSTALL_SUCCEEDED) {
15043                cleanUp();
15044            }
15045            return status;
15046        }
15047
15048        @Override
15049        String getCodePath() {
15050            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15051        }
15052
15053        @Override
15054        String getResourcePath() {
15055            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15056        }
15057
15058        private boolean cleanUp() {
15059            if (codeFile == null || !codeFile.exists()) {
15060                return false;
15061            }
15062
15063            removeCodePathLI(codeFile);
15064
15065            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15066                resourceFile.delete();
15067            }
15068
15069            return true;
15070        }
15071
15072        void cleanUpResourcesLI() {
15073            // Try enumerating all code paths before deleting
15074            List<String> allCodePaths = Collections.EMPTY_LIST;
15075            if (codeFile != null && codeFile.exists()) {
15076                try {
15077                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15078                    allCodePaths = pkg.getAllCodePaths();
15079                } catch (PackageParserException e) {
15080                    // Ignored; we tried our best
15081                }
15082            }
15083
15084            cleanUp();
15085            removeDexFiles(allCodePaths, instructionSets);
15086        }
15087
15088        boolean doPostDeleteLI(boolean delete) {
15089            // XXX err, shouldn't we respect the delete flag?
15090            cleanUpResourcesLI();
15091            return true;
15092        }
15093    }
15094
15095    private boolean isAsecExternal(String cid) {
15096        final String asecPath = PackageHelper.getSdFilesystem(cid);
15097        return !asecPath.startsWith(mAsecInternalPath);
15098    }
15099
15100    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15101            PackageManagerException {
15102        if (copyRet < 0) {
15103            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15104                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15105                throw new PackageManagerException(copyRet, message);
15106            }
15107        }
15108    }
15109
15110    /**
15111     * Extract the StorageManagerService "container ID" from the full code path of an
15112     * .apk.
15113     */
15114    static String cidFromCodePath(String fullCodePath) {
15115        int eidx = fullCodePath.lastIndexOf("/");
15116        String subStr1 = fullCodePath.substring(0, eidx);
15117        int sidx = subStr1.lastIndexOf("/");
15118        return subStr1.substring(sidx+1, eidx);
15119    }
15120
15121    /**
15122     * Logic to handle installation of ASEC applications, including copying and
15123     * renaming logic.
15124     */
15125    class AsecInstallArgs extends InstallArgs {
15126        static final String RES_FILE_NAME = "pkg.apk";
15127        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15128
15129        String cid;
15130        String packagePath;
15131        String resourcePath;
15132
15133        /** New install */
15134        AsecInstallArgs(InstallParams params) {
15135            super(params.origin, params.move, params.observer, params.installFlags,
15136                    params.installerPackageName, params.volumeUuid,
15137                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15138                    params.grantedRuntimePermissions,
15139                    params.traceMethod, params.traceCookie, params.certificates,
15140                    params.installReason);
15141        }
15142
15143        /** Existing install */
15144        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15145                        boolean isExternal, boolean isForwardLocked) {
15146            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15147                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15148                    instructionSets, null, null, null, 0, null /*certificates*/,
15149                    PackageManager.INSTALL_REASON_UNKNOWN);
15150            // Hackily pretend we're still looking at a full code path
15151            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15152                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15153            }
15154
15155            // Extract cid from fullCodePath
15156            int eidx = fullCodePath.lastIndexOf("/");
15157            String subStr1 = fullCodePath.substring(0, eidx);
15158            int sidx = subStr1.lastIndexOf("/");
15159            cid = subStr1.substring(sidx+1, eidx);
15160            setMountPath(subStr1);
15161        }
15162
15163        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15164            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15165                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15166                    instructionSets, null, null, null, 0, null /*certificates*/,
15167                    PackageManager.INSTALL_REASON_UNKNOWN);
15168            this.cid = cid;
15169            setMountPath(PackageHelper.getSdDir(cid));
15170        }
15171
15172        void createCopyFile() {
15173            cid = mInstallerService.allocateExternalStageCidLegacy();
15174        }
15175
15176        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15177            if (origin.staged && origin.cid != null) {
15178                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15179                cid = origin.cid;
15180                setMountPath(PackageHelper.getSdDir(cid));
15181                return PackageManager.INSTALL_SUCCEEDED;
15182            }
15183
15184            if (temp) {
15185                createCopyFile();
15186            } else {
15187                /*
15188                 * Pre-emptively destroy the container since it's destroyed if
15189                 * copying fails due to it existing anyway.
15190                 */
15191                PackageHelper.destroySdDir(cid);
15192            }
15193
15194            final String newMountPath = imcs.copyPackageToContainer(
15195                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15196                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15197
15198            if (newMountPath != null) {
15199                setMountPath(newMountPath);
15200                return PackageManager.INSTALL_SUCCEEDED;
15201            } else {
15202                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15203            }
15204        }
15205
15206        @Override
15207        String getCodePath() {
15208            return packagePath;
15209        }
15210
15211        @Override
15212        String getResourcePath() {
15213            return resourcePath;
15214        }
15215
15216        int doPreInstall(int status) {
15217            if (status != PackageManager.INSTALL_SUCCEEDED) {
15218                // Destroy container
15219                PackageHelper.destroySdDir(cid);
15220            } else {
15221                boolean mounted = PackageHelper.isContainerMounted(cid);
15222                if (!mounted) {
15223                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15224                            Process.SYSTEM_UID);
15225                    if (newMountPath != null) {
15226                        setMountPath(newMountPath);
15227                    } else {
15228                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15229                    }
15230                }
15231            }
15232            return status;
15233        }
15234
15235        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15236            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15237            String newMountPath = null;
15238            if (PackageHelper.isContainerMounted(cid)) {
15239                // Unmount the container
15240                if (!PackageHelper.unMountSdDir(cid)) {
15241                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15242                    return false;
15243                }
15244            }
15245            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15246                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15247                        " which might be stale. Will try to clean up.");
15248                // Clean up the stale container and proceed to recreate.
15249                if (!PackageHelper.destroySdDir(newCacheId)) {
15250                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15251                    return false;
15252                }
15253                // Successfully cleaned up stale container. Try to rename again.
15254                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15255                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15256                            + " inspite of cleaning it up.");
15257                    return false;
15258                }
15259            }
15260            if (!PackageHelper.isContainerMounted(newCacheId)) {
15261                Slog.w(TAG, "Mounting container " + newCacheId);
15262                newMountPath = PackageHelper.mountSdDir(newCacheId,
15263                        getEncryptKey(), Process.SYSTEM_UID);
15264            } else {
15265                newMountPath = PackageHelper.getSdDir(newCacheId);
15266            }
15267            if (newMountPath == null) {
15268                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15269                return false;
15270            }
15271            Log.i(TAG, "Succesfully renamed " + cid +
15272                    " to " + newCacheId +
15273                    " at new path: " + newMountPath);
15274            cid = newCacheId;
15275
15276            final File beforeCodeFile = new File(packagePath);
15277            setMountPath(newMountPath);
15278            final File afterCodeFile = new File(packagePath);
15279
15280            // Reflect the rename in scanned details
15281            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15282            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15283                    afterCodeFile, pkg.baseCodePath));
15284            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15285                    afterCodeFile, pkg.splitCodePaths));
15286
15287            // Reflect the rename in app info
15288            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15289            pkg.setApplicationInfoCodePath(pkg.codePath);
15290            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15291            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15292            pkg.setApplicationInfoResourcePath(pkg.codePath);
15293            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15294            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15295
15296            return true;
15297        }
15298
15299        private void setMountPath(String mountPath) {
15300            final File mountFile = new File(mountPath);
15301
15302            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15303            if (monolithicFile.exists()) {
15304                packagePath = monolithicFile.getAbsolutePath();
15305                if (isFwdLocked()) {
15306                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15307                } else {
15308                    resourcePath = packagePath;
15309                }
15310            } else {
15311                packagePath = mountFile.getAbsolutePath();
15312                resourcePath = packagePath;
15313            }
15314        }
15315
15316        int doPostInstall(int status, int uid) {
15317            if (status != PackageManager.INSTALL_SUCCEEDED) {
15318                cleanUp();
15319            } else {
15320                final int groupOwner;
15321                final String protectedFile;
15322                if (isFwdLocked()) {
15323                    groupOwner = UserHandle.getSharedAppGid(uid);
15324                    protectedFile = RES_FILE_NAME;
15325                } else {
15326                    groupOwner = -1;
15327                    protectedFile = null;
15328                }
15329
15330                if (uid < Process.FIRST_APPLICATION_UID
15331                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15332                    Slog.e(TAG, "Failed to finalize " + cid);
15333                    PackageHelper.destroySdDir(cid);
15334                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15335                }
15336
15337                boolean mounted = PackageHelper.isContainerMounted(cid);
15338                if (!mounted) {
15339                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15340                }
15341            }
15342            return status;
15343        }
15344
15345        private void cleanUp() {
15346            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15347
15348            // Destroy secure container
15349            PackageHelper.destroySdDir(cid);
15350        }
15351
15352        private List<String> getAllCodePaths() {
15353            final File codeFile = new File(getCodePath());
15354            if (codeFile != null && codeFile.exists()) {
15355                try {
15356                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15357                    return pkg.getAllCodePaths();
15358                } catch (PackageParserException e) {
15359                    // Ignored; we tried our best
15360                }
15361            }
15362            return Collections.EMPTY_LIST;
15363        }
15364
15365        void cleanUpResourcesLI() {
15366            // Enumerate all code paths before deleting
15367            cleanUpResourcesLI(getAllCodePaths());
15368        }
15369
15370        private void cleanUpResourcesLI(List<String> allCodePaths) {
15371            cleanUp();
15372            removeDexFiles(allCodePaths, instructionSets);
15373        }
15374
15375        String getPackageName() {
15376            return getAsecPackageName(cid);
15377        }
15378
15379        boolean doPostDeleteLI(boolean delete) {
15380            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15381            final List<String> allCodePaths = getAllCodePaths();
15382            boolean mounted = PackageHelper.isContainerMounted(cid);
15383            if (mounted) {
15384                // Unmount first
15385                if (PackageHelper.unMountSdDir(cid)) {
15386                    mounted = false;
15387                }
15388            }
15389            if (!mounted && delete) {
15390                cleanUpResourcesLI(allCodePaths);
15391            }
15392            return !mounted;
15393        }
15394
15395        @Override
15396        int doPreCopy() {
15397            if (isFwdLocked()) {
15398                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15399                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15400                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15401                }
15402            }
15403
15404            return PackageManager.INSTALL_SUCCEEDED;
15405        }
15406
15407        @Override
15408        int doPostCopy(int uid) {
15409            if (isFwdLocked()) {
15410                if (uid < Process.FIRST_APPLICATION_UID
15411                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15412                                RES_FILE_NAME)) {
15413                    Slog.e(TAG, "Failed to finalize " + cid);
15414                    PackageHelper.destroySdDir(cid);
15415                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15416                }
15417            }
15418
15419            return PackageManager.INSTALL_SUCCEEDED;
15420        }
15421    }
15422
15423    /**
15424     * Logic to handle movement of existing installed applications.
15425     */
15426    class MoveInstallArgs extends InstallArgs {
15427        private File codeFile;
15428        private File resourceFile;
15429
15430        /** New install */
15431        MoveInstallArgs(InstallParams params) {
15432            super(params.origin, params.move, params.observer, params.installFlags,
15433                    params.installerPackageName, params.volumeUuid,
15434                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15435                    params.grantedRuntimePermissions,
15436                    params.traceMethod, params.traceCookie, params.certificates,
15437                    params.installReason);
15438        }
15439
15440        int copyApk(IMediaContainerService imcs, boolean temp) {
15441            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15442                    + move.fromUuid + " to " + move.toUuid);
15443            synchronized (mInstaller) {
15444                try {
15445                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15446                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15447                } catch (InstallerException e) {
15448                    Slog.w(TAG, "Failed to move app", e);
15449                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15450                }
15451            }
15452
15453            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15454            resourceFile = codeFile;
15455            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15456
15457            return PackageManager.INSTALL_SUCCEEDED;
15458        }
15459
15460        int doPreInstall(int status) {
15461            if (status != PackageManager.INSTALL_SUCCEEDED) {
15462                cleanUp(move.toUuid);
15463            }
15464            return status;
15465        }
15466
15467        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15468            if (status != PackageManager.INSTALL_SUCCEEDED) {
15469                cleanUp(move.toUuid);
15470                return false;
15471            }
15472
15473            // Reflect the move in app info
15474            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15475            pkg.setApplicationInfoCodePath(pkg.codePath);
15476            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15477            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15478            pkg.setApplicationInfoResourcePath(pkg.codePath);
15479            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15480            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15481
15482            return true;
15483        }
15484
15485        int doPostInstall(int status, int uid) {
15486            if (status == PackageManager.INSTALL_SUCCEEDED) {
15487                cleanUp(move.fromUuid);
15488            } else {
15489                cleanUp(move.toUuid);
15490            }
15491            return status;
15492        }
15493
15494        @Override
15495        String getCodePath() {
15496            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15497        }
15498
15499        @Override
15500        String getResourcePath() {
15501            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15502        }
15503
15504        private boolean cleanUp(String volumeUuid) {
15505            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15506                    move.dataAppName);
15507            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15508            final int[] userIds = sUserManager.getUserIds();
15509            synchronized (mInstallLock) {
15510                // Clean up both app data and code
15511                // All package moves are frozen until finished
15512                for (int userId : userIds) {
15513                    try {
15514                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15515                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15516                    } catch (InstallerException e) {
15517                        Slog.w(TAG, String.valueOf(e));
15518                    }
15519                }
15520                removeCodePathLI(codeFile);
15521            }
15522            return true;
15523        }
15524
15525        void cleanUpResourcesLI() {
15526            throw new UnsupportedOperationException();
15527        }
15528
15529        boolean doPostDeleteLI(boolean delete) {
15530            throw new UnsupportedOperationException();
15531        }
15532    }
15533
15534    static String getAsecPackageName(String packageCid) {
15535        int idx = packageCid.lastIndexOf("-");
15536        if (idx == -1) {
15537            return packageCid;
15538        }
15539        return packageCid.substring(0, idx);
15540    }
15541
15542    // Utility method used to create code paths based on package name and available index.
15543    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15544        String idxStr = "";
15545        int idx = 1;
15546        // Fall back to default value of idx=1 if prefix is not
15547        // part of oldCodePath
15548        if (oldCodePath != null) {
15549            String subStr = oldCodePath;
15550            // Drop the suffix right away
15551            if (suffix != null && subStr.endsWith(suffix)) {
15552                subStr = subStr.substring(0, subStr.length() - suffix.length());
15553            }
15554            // If oldCodePath already contains prefix find out the
15555            // ending index to either increment or decrement.
15556            int sidx = subStr.lastIndexOf(prefix);
15557            if (sidx != -1) {
15558                subStr = subStr.substring(sidx + prefix.length());
15559                if (subStr != null) {
15560                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15561                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15562                    }
15563                    try {
15564                        idx = Integer.parseInt(subStr);
15565                        if (idx <= 1) {
15566                            idx++;
15567                        } else {
15568                            idx--;
15569                        }
15570                    } catch(NumberFormatException e) {
15571                    }
15572                }
15573            }
15574        }
15575        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15576        return prefix + idxStr;
15577    }
15578
15579    private File getNextCodePath(File targetDir, String packageName) {
15580        File result;
15581        SecureRandom random = new SecureRandom();
15582        byte[] bytes = new byte[16];
15583        do {
15584            random.nextBytes(bytes);
15585            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15586            result = new File(targetDir, packageName + "-" + suffix);
15587        } while (result.exists());
15588        return result;
15589    }
15590
15591    // Utility method that returns the relative package path with respect
15592    // to the installation directory. Like say for /data/data/com.test-1.apk
15593    // string com.test-1 is returned.
15594    static String deriveCodePathName(String codePath) {
15595        if (codePath == null) {
15596            return null;
15597        }
15598        final File codeFile = new File(codePath);
15599        final String name = codeFile.getName();
15600        if (codeFile.isDirectory()) {
15601            return name;
15602        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15603            final int lastDot = name.lastIndexOf('.');
15604            return name.substring(0, lastDot);
15605        } else {
15606            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15607            return null;
15608        }
15609    }
15610
15611    static class PackageInstalledInfo {
15612        String name;
15613        int uid;
15614        // The set of users that originally had this package installed.
15615        int[] origUsers;
15616        // The set of users that now have this package installed.
15617        int[] newUsers;
15618        PackageParser.Package pkg;
15619        int returnCode;
15620        String returnMsg;
15621        PackageRemovedInfo removedInfo;
15622        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15623
15624        public void setError(int code, String msg) {
15625            setReturnCode(code);
15626            setReturnMessage(msg);
15627            Slog.w(TAG, msg);
15628        }
15629
15630        public void setError(String msg, PackageParserException e) {
15631            setReturnCode(e.error);
15632            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15633            Slog.w(TAG, msg, e);
15634        }
15635
15636        public void setError(String msg, PackageManagerException e) {
15637            returnCode = e.error;
15638            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15639            Slog.w(TAG, msg, e);
15640        }
15641
15642        public void setReturnCode(int returnCode) {
15643            this.returnCode = returnCode;
15644            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15645            for (int i = 0; i < childCount; i++) {
15646                addedChildPackages.valueAt(i).returnCode = returnCode;
15647            }
15648        }
15649
15650        private void setReturnMessage(String returnMsg) {
15651            this.returnMsg = returnMsg;
15652            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15653            for (int i = 0; i < childCount; i++) {
15654                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15655            }
15656        }
15657
15658        // In some error cases we want to convey more info back to the observer
15659        String origPackage;
15660        String origPermission;
15661    }
15662
15663    /*
15664     * Install a non-existing package.
15665     */
15666    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15667            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15668            PackageInstalledInfo res, int installReason) {
15669        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15670
15671        // Remember this for later, in case we need to rollback this install
15672        String pkgName = pkg.packageName;
15673
15674        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15675
15676        synchronized(mPackages) {
15677            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15678            if (renamedPackage != null) {
15679                // A package with the same name is already installed, though
15680                // it has been renamed to an older name.  The package we
15681                // are trying to install should be installed as an update to
15682                // the existing one, but that has not been requested, so bail.
15683                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15684                        + " without first uninstalling package running as "
15685                        + renamedPackage);
15686                return;
15687            }
15688            if (mPackages.containsKey(pkgName)) {
15689                // Don't allow installation over an existing package with the same name.
15690                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15691                        + " without first uninstalling.");
15692                return;
15693            }
15694        }
15695
15696        try {
15697            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15698                    System.currentTimeMillis(), user);
15699
15700            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15701
15702            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15703                prepareAppDataAfterInstallLIF(newPackage);
15704
15705            } else {
15706                // Remove package from internal structures, but keep around any
15707                // data that might have already existed
15708                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15709                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15710            }
15711        } catch (PackageManagerException e) {
15712            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15713        }
15714
15715        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15716    }
15717
15718    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15719        // Can't rotate keys during boot or if sharedUser.
15720        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15721                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15722            return false;
15723        }
15724        // app is using upgradeKeySets; make sure all are valid
15725        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15726        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15727        for (int i = 0; i < upgradeKeySets.length; i++) {
15728            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15729                Slog.wtf(TAG, "Package "
15730                         + (oldPs.name != null ? oldPs.name : "<null>")
15731                         + " contains upgrade-key-set reference to unknown key-set: "
15732                         + upgradeKeySets[i]
15733                         + " reverting to signatures check.");
15734                return false;
15735            }
15736        }
15737        return true;
15738    }
15739
15740    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15741        // Upgrade keysets are being used.  Determine if new package has a superset of the
15742        // required keys.
15743        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15744        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15745        for (int i = 0; i < upgradeKeySets.length; i++) {
15746            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15747            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15748                return true;
15749            }
15750        }
15751        return false;
15752    }
15753
15754    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15755        try (DigestInputStream digestStream =
15756                new DigestInputStream(new FileInputStream(file), digest)) {
15757            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15758        }
15759    }
15760
15761    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15762            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15763            int installReason) {
15764        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15765
15766        final PackageParser.Package oldPackage;
15767        final String pkgName = pkg.packageName;
15768        final int[] allUsers;
15769        final int[] installedUsers;
15770
15771        synchronized(mPackages) {
15772            oldPackage = mPackages.get(pkgName);
15773            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15774
15775            // don't allow upgrade to target a release SDK from a pre-release SDK
15776            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15777                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15778            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15779                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15780            if (oldTargetsPreRelease
15781                    && !newTargetsPreRelease
15782                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15783                Slog.w(TAG, "Can't install package targeting released sdk");
15784                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15785                return;
15786            }
15787
15788            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15789
15790            // don't allow an upgrade from full to ephemeral
15791            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15792                // can't downgrade from full to instant
15793                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15794                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15795                return;
15796            }
15797
15798            // verify signatures are valid
15799            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15800                if (!checkUpgradeKeySetLP(ps, pkg)) {
15801                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15802                            "New package not signed by keys specified by upgrade-keysets: "
15803                                    + pkgName);
15804                    return;
15805                }
15806            } else {
15807                // default to original signature matching
15808                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15809                        != PackageManager.SIGNATURE_MATCH) {
15810                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15811                            "New package has a different signature: " + pkgName);
15812                    return;
15813                }
15814            }
15815
15816            // don't allow a system upgrade unless the upgrade hash matches
15817            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15818                byte[] digestBytes = null;
15819                try {
15820                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15821                    updateDigest(digest, new File(pkg.baseCodePath));
15822                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15823                        for (String path : pkg.splitCodePaths) {
15824                            updateDigest(digest, new File(path));
15825                        }
15826                    }
15827                    digestBytes = digest.digest();
15828                } catch (NoSuchAlgorithmException | IOException e) {
15829                    res.setError(INSTALL_FAILED_INVALID_APK,
15830                            "Could not compute hash: " + pkgName);
15831                    return;
15832                }
15833                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15834                    res.setError(INSTALL_FAILED_INVALID_APK,
15835                            "New package fails restrict-update check: " + pkgName);
15836                    return;
15837                }
15838                // retain upgrade restriction
15839                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15840            }
15841
15842            // Check for shared user id changes
15843            String invalidPackageName =
15844                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15845            if (invalidPackageName != null) {
15846                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15847                        "Package " + invalidPackageName + " tried to change user "
15848                                + oldPackage.mSharedUserId);
15849                return;
15850            }
15851
15852            // In case of rollback, remember per-user/profile install state
15853            allUsers = sUserManager.getUserIds();
15854            installedUsers = ps.queryInstalledUsers(allUsers, true);
15855        }
15856
15857        // Update what is removed
15858        res.removedInfo = new PackageRemovedInfo();
15859        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15860        res.removedInfo.removedPackage = oldPackage.packageName;
15861        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15862        res.removedInfo.isUpdate = true;
15863        res.removedInfo.origUsers = installedUsers;
15864        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15865        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15866        for (int i = 0; i < installedUsers.length; i++) {
15867            final int userId = installedUsers[i];
15868            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15869        }
15870
15871        final int childCount = (oldPackage.childPackages != null)
15872                ? oldPackage.childPackages.size() : 0;
15873        for (int i = 0; i < childCount; i++) {
15874            boolean childPackageUpdated = false;
15875            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15876            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15877            if (res.addedChildPackages != null) {
15878                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15879                if (childRes != null) {
15880                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15881                    childRes.removedInfo.removedPackage = childPkg.packageName;
15882                    childRes.removedInfo.isUpdate = true;
15883                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15884                    childPackageUpdated = true;
15885                }
15886            }
15887            if (!childPackageUpdated) {
15888                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15889                childRemovedRes.removedPackage = childPkg.packageName;
15890                childRemovedRes.isUpdate = false;
15891                childRemovedRes.dataRemoved = true;
15892                synchronized (mPackages) {
15893                    if (childPs != null) {
15894                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15895                    }
15896                }
15897                if (res.removedInfo.removedChildPackages == null) {
15898                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15899                }
15900                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15901            }
15902        }
15903
15904        boolean sysPkg = (isSystemApp(oldPackage));
15905        if (sysPkg) {
15906            // Set the system/privileged flags as needed
15907            final boolean privileged =
15908                    (oldPackage.applicationInfo.privateFlags
15909                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15910            final int systemPolicyFlags = policyFlags
15911                    | PackageParser.PARSE_IS_SYSTEM
15912                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15913
15914            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15915                    user, allUsers, installerPackageName, res, installReason);
15916        } else {
15917            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15918                    user, allUsers, installerPackageName, res, installReason);
15919        }
15920    }
15921
15922    public List<String> getPreviousCodePaths(String packageName) {
15923        final PackageSetting ps = mSettings.mPackages.get(packageName);
15924        final List<String> result = new ArrayList<String>();
15925        if (ps != null && ps.oldCodePaths != null) {
15926            result.addAll(ps.oldCodePaths);
15927        }
15928        return result;
15929    }
15930
15931    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15932            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15933            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15934            int installReason) {
15935        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15936                + deletedPackage);
15937
15938        String pkgName = deletedPackage.packageName;
15939        boolean deletedPkg = true;
15940        boolean addedPkg = false;
15941        boolean updatedSettings = false;
15942        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15943        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15944                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15945
15946        final long origUpdateTime = (pkg.mExtras != null)
15947                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15948
15949        // First delete the existing package while retaining the data directory
15950        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15951                res.removedInfo, true, pkg)) {
15952            // If the existing package wasn't successfully deleted
15953            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15954            deletedPkg = false;
15955        } else {
15956            // Successfully deleted the old package; proceed with replace.
15957
15958            // If deleted package lived in a container, give users a chance to
15959            // relinquish resources before killing.
15960            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15961                if (DEBUG_INSTALL) {
15962                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15963                }
15964                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15965                final ArrayList<String> pkgList = new ArrayList<String>(1);
15966                pkgList.add(deletedPackage.applicationInfo.packageName);
15967                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15968            }
15969
15970            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15971                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15972            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15973
15974            try {
15975                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15976                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15977                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15978                        installReason);
15979
15980                // Update the in-memory copy of the previous code paths.
15981                PackageSetting ps = mSettings.mPackages.get(pkgName);
15982                if (!killApp) {
15983                    if (ps.oldCodePaths == null) {
15984                        ps.oldCodePaths = new ArraySet<>();
15985                    }
15986                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15987                    if (deletedPackage.splitCodePaths != null) {
15988                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15989                    }
15990                } else {
15991                    ps.oldCodePaths = null;
15992                }
15993                if (ps.childPackageNames != null) {
15994                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15995                        final String childPkgName = ps.childPackageNames.get(i);
15996                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15997                        childPs.oldCodePaths = ps.oldCodePaths;
15998                    }
15999                }
16000                // set instant app status, but, only if it's explicitly specified
16001                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16002                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16003                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16004                prepareAppDataAfterInstallLIF(newPackage);
16005                addedPkg = true;
16006                mDexManager.notifyPackageUpdated(newPackage.packageName,
16007                        newPackage.baseCodePath, newPackage.splitCodePaths);
16008            } catch (PackageManagerException e) {
16009                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16010            }
16011        }
16012
16013        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16014            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16015
16016            // Revert all internal state mutations and added folders for the failed install
16017            if (addedPkg) {
16018                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16019                        res.removedInfo, true, null);
16020            }
16021
16022            // Restore the old package
16023            if (deletedPkg) {
16024                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16025                File restoreFile = new File(deletedPackage.codePath);
16026                // Parse old package
16027                boolean oldExternal = isExternal(deletedPackage);
16028                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16029                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16030                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16031                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16032                try {
16033                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16034                            null);
16035                } catch (PackageManagerException e) {
16036                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16037                            + e.getMessage());
16038                    return;
16039                }
16040
16041                synchronized (mPackages) {
16042                    // Ensure the installer package name up to date
16043                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16044
16045                    // Update permissions for restored package
16046                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16047
16048                    mSettings.writeLPr();
16049                }
16050
16051                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16052            }
16053        } else {
16054            synchronized (mPackages) {
16055                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16056                if (ps != null) {
16057                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16058                    if (res.removedInfo.removedChildPackages != null) {
16059                        final int childCount = res.removedInfo.removedChildPackages.size();
16060                        // Iterate in reverse as we may modify the collection
16061                        for (int i = childCount - 1; i >= 0; i--) {
16062                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16063                            if (res.addedChildPackages.containsKey(childPackageName)) {
16064                                res.removedInfo.removedChildPackages.removeAt(i);
16065                            } else {
16066                                PackageRemovedInfo childInfo = res.removedInfo
16067                                        .removedChildPackages.valueAt(i);
16068                                childInfo.removedForAllUsers = mPackages.get(
16069                                        childInfo.removedPackage) == null;
16070                            }
16071                        }
16072                    }
16073                }
16074            }
16075        }
16076    }
16077
16078    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16079            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16080            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16081            int installReason) {
16082        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16083                + ", old=" + deletedPackage);
16084
16085        final boolean disabledSystem;
16086
16087        // Remove existing system package
16088        removePackageLI(deletedPackage, true);
16089
16090        synchronized (mPackages) {
16091            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16092        }
16093        if (!disabledSystem) {
16094            // We didn't need to disable the .apk as a current system package,
16095            // which means we are replacing another update that is already
16096            // installed.  We need to make sure to delete the older one's .apk.
16097            res.removedInfo.args = createInstallArgsForExisting(0,
16098                    deletedPackage.applicationInfo.getCodePath(),
16099                    deletedPackage.applicationInfo.getResourcePath(),
16100                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16101        } else {
16102            res.removedInfo.args = null;
16103        }
16104
16105        // Successfully disabled the old package. Now proceed with re-installation
16106        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16107                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16108        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16109
16110        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16111        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16112                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16113
16114        PackageParser.Package newPackage = null;
16115        try {
16116            // Add the package to the internal data structures
16117            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16118
16119            // Set the update and install times
16120            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16121            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16122                    System.currentTimeMillis());
16123
16124            // Update the package dynamic state if succeeded
16125            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16126                // Now that the install succeeded make sure we remove data
16127                // directories for any child package the update removed.
16128                final int deletedChildCount = (deletedPackage.childPackages != null)
16129                        ? deletedPackage.childPackages.size() : 0;
16130                final int newChildCount = (newPackage.childPackages != null)
16131                        ? newPackage.childPackages.size() : 0;
16132                for (int i = 0; i < deletedChildCount; i++) {
16133                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16134                    boolean childPackageDeleted = true;
16135                    for (int j = 0; j < newChildCount; j++) {
16136                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16137                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16138                            childPackageDeleted = false;
16139                            break;
16140                        }
16141                    }
16142                    if (childPackageDeleted) {
16143                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16144                                deletedChildPkg.packageName);
16145                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16146                            PackageRemovedInfo removedChildRes = res.removedInfo
16147                                    .removedChildPackages.get(deletedChildPkg.packageName);
16148                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16149                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16150                        }
16151                    }
16152                }
16153
16154                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16155                        installReason);
16156                prepareAppDataAfterInstallLIF(newPackage);
16157
16158                mDexManager.notifyPackageUpdated(newPackage.packageName,
16159                            newPackage.baseCodePath, newPackage.splitCodePaths);
16160            }
16161        } catch (PackageManagerException e) {
16162            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16163            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16164        }
16165
16166        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16167            // Re installation failed. Restore old information
16168            // Remove new pkg information
16169            if (newPackage != null) {
16170                removeInstalledPackageLI(newPackage, true);
16171            }
16172            // Add back the old system package
16173            try {
16174                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16175            } catch (PackageManagerException e) {
16176                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16177            }
16178
16179            synchronized (mPackages) {
16180                if (disabledSystem) {
16181                    enableSystemPackageLPw(deletedPackage);
16182                }
16183
16184                // Ensure the installer package name up to date
16185                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16186
16187                // Update permissions for restored package
16188                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16189
16190                mSettings.writeLPr();
16191            }
16192
16193            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16194                    + " after failed upgrade");
16195        }
16196    }
16197
16198    /**
16199     * Checks whether the parent or any of the child packages have a change shared
16200     * user. For a package to be a valid update the shred users of the parent and
16201     * the children should match. We may later support changing child shared users.
16202     * @param oldPkg The updated package.
16203     * @param newPkg The update package.
16204     * @return The shared user that change between the versions.
16205     */
16206    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16207            PackageParser.Package newPkg) {
16208        // Check parent shared user
16209        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16210            return newPkg.packageName;
16211        }
16212        // Check child shared users
16213        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16214        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16215        for (int i = 0; i < newChildCount; i++) {
16216            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16217            // If this child was present, did it have the same shared user?
16218            for (int j = 0; j < oldChildCount; j++) {
16219                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16220                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16221                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16222                    return newChildPkg.packageName;
16223                }
16224            }
16225        }
16226        return null;
16227    }
16228
16229    private void removeNativeBinariesLI(PackageSetting ps) {
16230        // Remove the lib path for the parent package
16231        if (ps != null) {
16232            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16233            // Remove the lib path for the child packages
16234            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16235            for (int i = 0; i < childCount; i++) {
16236                PackageSetting childPs = null;
16237                synchronized (mPackages) {
16238                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16239                }
16240                if (childPs != null) {
16241                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16242                            .legacyNativeLibraryPathString);
16243                }
16244            }
16245        }
16246    }
16247
16248    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16249        // Enable the parent package
16250        mSettings.enableSystemPackageLPw(pkg.packageName);
16251        // Enable the child packages
16252        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16253        for (int i = 0; i < childCount; i++) {
16254            PackageParser.Package childPkg = pkg.childPackages.get(i);
16255            mSettings.enableSystemPackageLPw(childPkg.packageName);
16256        }
16257    }
16258
16259    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16260            PackageParser.Package newPkg) {
16261        // Disable the parent package (parent always replaced)
16262        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16263        // Disable the child packages
16264        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16265        for (int i = 0; i < childCount; i++) {
16266            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16267            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16268            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16269        }
16270        return disabled;
16271    }
16272
16273    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16274            String installerPackageName) {
16275        // Enable the parent package
16276        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16277        // Enable the child packages
16278        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16279        for (int i = 0; i < childCount; i++) {
16280            PackageParser.Package childPkg = pkg.childPackages.get(i);
16281            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16282        }
16283    }
16284
16285    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16286        // Collect all used permissions in the UID
16287        ArraySet<String> usedPermissions = new ArraySet<>();
16288        final int packageCount = su.packages.size();
16289        for (int i = 0; i < packageCount; i++) {
16290            PackageSetting ps = su.packages.valueAt(i);
16291            if (ps.pkg == null) {
16292                continue;
16293            }
16294            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16295            for (int j = 0; j < requestedPermCount; j++) {
16296                String permission = ps.pkg.requestedPermissions.get(j);
16297                BasePermission bp = mSettings.mPermissions.get(permission);
16298                if (bp != null) {
16299                    usedPermissions.add(permission);
16300                }
16301            }
16302        }
16303
16304        PermissionsState permissionsState = su.getPermissionsState();
16305        // Prune install permissions
16306        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16307        final int installPermCount = installPermStates.size();
16308        for (int i = installPermCount - 1; i >= 0;  i--) {
16309            PermissionState permissionState = installPermStates.get(i);
16310            if (!usedPermissions.contains(permissionState.getName())) {
16311                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16312                if (bp != null) {
16313                    permissionsState.revokeInstallPermission(bp);
16314                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16315                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16316                }
16317            }
16318        }
16319
16320        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16321
16322        // Prune runtime permissions
16323        for (int userId : allUserIds) {
16324            List<PermissionState> runtimePermStates = permissionsState
16325                    .getRuntimePermissionStates(userId);
16326            final int runtimePermCount = runtimePermStates.size();
16327            for (int i = runtimePermCount - 1; i >= 0; i--) {
16328                PermissionState permissionState = runtimePermStates.get(i);
16329                if (!usedPermissions.contains(permissionState.getName())) {
16330                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16331                    if (bp != null) {
16332                        permissionsState.revokeRuntimePermission(bp, userId);
16333                        permissionsState.updatePermissionFlags(bp, userId,
16334                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16335                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16336                                runtimePermissionChangedUserIds, userId);
16337                    }
16338                }
16339            }
16340        }
16341
16342        return runtimePermissionChangedUserIds;
16343    }
16344
16345    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16346            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16347        // Update the parent package setting
16348        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16349                res, user, installReason);
16350        // Update the child packages setting
16351        final int childCount = (newPackage.childPackages != null)
16352                ? newPackage.childPackages.size() : 0;
16353        for (int i = 0; i < childCount; i++) {
16354            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16355            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16356            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16357                    childRes.origUsers, childRes, user, installReason);
16358        }
16359    }
16360
16361    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16362            String installerPackageName, int[] allUsers, int[] installedForUsers,
16363            PackageInstalledInfo res, UserHandle user, int installReason) {
16364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16365
16366        String pkgName = newPackage.packageName;
16367        synchronized (mPackages) {
16368            //write settings. the installStatus will be incomplete at this stage.
16369            //note that the new package setting would have already been
16370            //added to mPackages. It hasn't been persisted yet.
16371            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16372            // TODO: Remove this write? It's also written at the end of this method
16373            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16374            mSettings.writeLPr();
16375            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16376        }
16377
16378        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16379        synchronized (mPackages) {
16380            updatePermissionsLPw(newPackage.packageName, newPackage,
16381                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16382                            ? UPDATE_PERMISSIONS_ALL : 0));
16383            // For system-bundled packages, we assume that installing an upgraded version
16384            // of the package implies that the user actually wants to run that new code,
16385            // so we enable the package.
16386            PackageSetting ps = mSettings.mPackages.get(pkgName);
16387            final int userId = user.getIdentifier();
16388            if (ps != null) {
16389                if (isSystemApp(newPackage)) {
16390                    if (DEBUG_INSTALL) {
16391                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16392                    }
16393                    // Enable system package for requested users
16394                    if (res.origUsers != null) {
16395                        for (int origUserId : res.origUsers) {
16396                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16397                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16398                                        origUserId, installerPackageName);
16399                            }
16400                        }
16401                    }
16402                    // Also convey the prior install/uninstall state
16403                    if (allUsers != null && installedForUsers != null) {
16404                        for (int currentUserId : allUsers) {
16405                            final boolean installed = ArrayUtils.contains(
16406                                    installedForUsers, currentUserId);
16407                            if (DEBUG_INSTALL) {
16408                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16409                            }
16410                            ps.setInstalled(installed, currentUserId);
16411                        }
16412                        // these install state changes will be persisted in the
16413                        // upcoming call to mSettings.writeLPr().
16414                    }
16415                }
16416                // It's implied that when a user requests installation, they want the app to be
16417                // installed and enabled.
16418                if (userId != UserHandle.USER_ALL) {
16419                    ps.setInstalled(true, userId);
16420                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16421                }
16422
16423                // When replacing an existing package, preserve the original install reason for all
16424                // users that had the package installed before.
16425                final Set<Integer> previousUserIds = new ArraySet<>();
16426                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16427                    final int installReasonCount = res.removedInfo.installReasons.size();
16428                    for (int i = 0; i < installReasonCount; i++) {
16429                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16430                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16431                        ps.setInstallReason(previousInstallReason, previousUserId);
16432                        previousUserIds.add(previousUserId);
16433                    }
16434                }
16435
16436                // Set install reason for users that are having the package newly installed.
16437                if (userId == UserHandle.USER_ALL) {
16438                    for (int currentUserId : sUserManager.getUserIds()) {
16439                        if (!previousUserIds.contains(currentUserId)) {
16440                            ps.setInstallReason(installReason, currentUserId);
16441                        }
16442                    }
16443                } else if (!previousUserIds.contains(userId)) {
16444                    ps.setInstallReason(installReason, userId);
16445                }
16446                mSettings.writeKernelMappingLPr(ps);
16447            }
16448            res.name = pkgName;
16449            res.uid = newPackage.applicationInfo.uid;
16450            res.pkg = newPackage;
16451            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16452            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16453            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16454            //to update install status
16455            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16456            mSettings.writeLPr();
16457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16458        }
16459
16460        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16461    }
16462
16463    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16464        try {
16465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16466            installPackageLI(args, res);
16467        } finally {
16468            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16469        }
16470    }
16471
16472    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16473        final int installFlags = args.installFlags;
16474        final String installerPackageName = args.installerPackageName;
16475        final String volumeUuid = args.volumeUuid;
16476        final File tmpPackageFile = new File(args.getCodePath());
16477        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16478        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16479                || (args.volumeUuid != null));
16480        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16481        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16482        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16483        boolean replace = false;
16484        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16485        if (args.move != null) {
16486            // moving a complete application; perform an initial scan on the new install location
16487            scanFlags |= SCAN_INITIAL;
16488        }
16489        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16490            scanFlags |= SCAN_DONT_KILL_APP;
16491        }
16492        if (instantApp) {
16493            scanFlags |= SCAN_AS_INSTANT_APP;
16494        }
16495        if (fullApp) {
16496            scanFlags |= SCAN_AS_FULL_APP;
16497        }
16498
16499        // Result object to be returned
16500        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16501
16502        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16503
16504        // Sanity check
16505        if (instantApp && (forwardLocked || onExternal)) {
16506            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16507                    + " external=" + onExternal);
16508            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16509            return;
16510        }
16511
16512        // Retrieve PackageSettings and parse package
16513        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16514                | PackageParser.PARSE_ENFORCE_CODE
16515                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16516                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16517                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16518                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16519        PackageParser pp = new PackageParser();
16520        pp.setSeparateProcesses(mSeparateProcesses);
16521        pp.setDisplayMetrics(mMetrics);
16522        pp.setCallback(mPackageParserCallback);
16523
16524        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16525        final PackageParser.Package pkg;
16526        try {
16527            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16528        } catch (PackageParserException e) {
16529            res.setError("Failed parse during installPackageLI", e);
16530            return;
16531        } finally {
16532            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16533        }
16534
16535        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16536        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16537            Slog.w(TAG, "Instant app package " + pkg.packageName
16538                    + " does not target O, this will be a fatal error.");
16539            // STOPSHIP: Make this a fatal error
16540            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16541        }
16542        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16543            Slog.w(TAG, "Instant app package " + pkg.packageName
16544                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16545            // STOPSHIP: Make this a fatal error
16546            pkg.applicationInfo.targetSandboxVersion = 2;
16547        }
16548
16549        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16550            // Static shared libraries have synthetic package names
16551            renameStaticSharedLibraryPackage(pkg);
16552
16553            // No static shared libs on external storage
16554            if (onExternal) {
16555                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16556                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16557                        "Packages declaring static-shared libs cannot be updated");
16558                return;
16559            }
16560        }
16561
16562        // If we are installing a clustered package add results for the children
16563        if (pkg.childPackages != null) {
16564            synchronized (mPackages) {
16565                final int childCount = pkg.childPackages.size();
16566                for (int i = 0; i < childCount; i++) {
16567                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16568                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16569                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16570                    childRes.pkg = childPkg;
16571                    childRes.name = childPkg.packageName;
16572                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16573                    if (childPs != null) {
16574                        childRes.origUsers = childPs.queryInstalledUsers(
16575                                sUserManager.getUserIds(), true);
16576                    }
16577                    if ((mPackages.containsKey(childPkg.packageName))) {
16578                        childRes.removedInfo = new PackageRemovedInfo();
16579                        childRes.removedInfo.removedPackage = childPkg.packageName;
16580                    }
16581                    if (res.addedChildPackages == null) {
16582                        res.addedChildPackages = new ArrayMap<>();
16583                    }
16584                    res.addedChildPackages.put(childPkg.packageName, childRes);
16585                }
16586            }
16587        }
16588
16589        // If package doesn't declare API override, mark that we have an install
16590        // time CPU ABI override.
16591        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16592            pkg.cpuAbiOverride = args.abiOverride;
16593        }
16594
16595        String pkgName = res.name = pkg.packageName;
16596        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16597            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16598                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16599                return;
16600            }
16601        }
16602
16603        try {
16604            // either use what we've been given or parse directly from the APK
16605            if (args.certificates != null) {
16606                try {
16607                    PackageParser.populateCertificates(pkg, args.certificates);
16608                } catch (PackageParserException e) {
16609                    // there was something wrong with the certificates we were given;
16610                    // try to pull them from the APK
16611                    PackageParser.collectCertificates(pkg, parseFlags);
16612                }
16613            } else {
16614                PackageParser.collectCertificates(pkg, parseFlags);
16615            }
16616        } catch (PackageParserException e) {
16617            res.setError("Failed collect during installPackageLI", e);
16618            return;
16619        }
16620
16621        // Get rid of all references to package scan path via parser.
16622        pp = null;
16623        String oldCodePath = null;
16624        boolean systemApp = false;
16625        synchronized (mPackages) {
16626            // Check if installing already existing package
16627            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16628                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16629                if (pkg.mOriginalPackages != null
16630                        && pkg.mOriginalPackages.contains(oldName)
16631                        && mPackages.containsKey(oldName)) {
16632                    // This package is derived from an original package,
16633                    // and this device has been updating from that original
16634                    // name.  We must continue using the original name, so
16635                    // rename the new package here.
16636                    pkg.setPackageName(oldName);
16637                    pkgName = pkg.packageName;
16638                    replace = true;
16639                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16640                            + oldName + " pkgName=" + pkgName);
16641                } else if (mPackages.containsKey(pkgName)) {
16642                    // This package, under its official name, already exists
16643                    // on the device; we should replace it.
16644                    replace = true;
16645                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16646                }
16647
16648                // Child packages are installed through the parent package
16649                if (pkg.parentPackage != null) {
16650                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16651                            "Package " + pkg.packageName + " is child of package "
16652                                    + pkg.parentPackage.parentPackage + ". Child packages "
16653                                    + "can be updated only through the parent package.");
16654                    return;
16655                }
16656
16657                if (replace) {
16658                    // Prevent apps opting out from runtime permissions
16659                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16660                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16661                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16662                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16663                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16664                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16665                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16666                                        + " doesn't support runtime permissions but the old"
16667                                        + " target SDK " + oldTargetSdk + " does.");
16668                        return;
16669                    }
16670
16671                    // Prevent installing of child packages
16672                    if (oldPackage.parentPackage != null) {
16673                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16674                                "Package " + pkg.packageName + " is child of package "
16675                                        + oldPackage.parentPackage + ". Child packages "
16676                                        + "can be updated only through the parent package.");
16677                        return;
16678                    }
16679                }
16680            }
16681
16682            PackageSetting ps = mSettings.mPackages.get(pkgName);
16683            if (ps != null) {
16684                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16685
16686                // Static shared libs have same package with different versions where
16687                // we internally use a synthetic package name to allow multiple versions
16688                // of the same package, therefore we need to compare signatures against
16689                // the package setting for the latest library version.
16690                PackageSetting signatureCheckPs = ps;
16691                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16692                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16693                    if (libraryEntry != null) {
16694                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16695                    }
16696                }
16697
16698                // Quick sanity check that we're signed correctly if updating;
16699                // we'll check this again later when scanning, but we want to
16700                // bail early here before tripping over redefined permissions.
16701                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16702                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16703                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16704                                + pkg.packageName + " upgrade keys do not match the "
16705                                + "previously installed version");
16706                        return;
16707                    }
16708                } else {
16709                    try {
16710                        verifySignaturesLP(signatureCheckPs, pkg);
16711                    } catch (PackageManagerException e) {
16712                        res.setError(e.error, e.getMessage());
16713                        return;
16714                    }
16715                }
16716
16717                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16718                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16719                    systemApp = (ps.pkg.applicationInfo.flags &
16720                            ApplicationInfo.FLAG_SYSTEM) != 0;
16721                }
16722                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16723            }
16724
16725            int N = pkg.permissions.size();
16726            for (int i = N-1; i >= 0; i--) {
16727                PackageParser.Permission perm = pkg.permissions.get(i);
16728                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16729
16730                // Don't allow anyone but the platform to define ephemeral permissions.
16731                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16732                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16733                    Slog.w(TAG, "Package " + pkg.packageName
16734                            + " attempting to delcare ephemeral permission "
16735                            + perm.info.name + "; Removing ephemeral.");
16736                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16737                }
16738                // Check whether the newly-scanned package wants to define an already-defined perm
16739                if (bp != null) {
16740                    // If the defining package is signed with our cert, it's okay.  This
16741                    // also includes the "updating the same package" case, of course.
16742                    // "updating same package" could also involve key-rotation.
16743                    final boolean sigsOk;
16744                    if (bp.sourcePackage.equals(pkg.packageName)
16745                            && (bp.packageSetting instanceof PackageSetting)
16746                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16747                                    scanFlags))) {
16748                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16749                    } else {
16750                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16751                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16752                    }
16753                    if (!sigsOk) {
16754                        // If the owning package is the system itself, we log but allow
16755                        // install to proceed; we fail the install on all other permission
16756                        // redefinitions.
16757                        if (!bp.sourcePackage.equals("android")) {
16758                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16759                                    + pkg.packageName + " attempting to redeclare permission "
16760                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16761                            res.origPermission = perm.info.name;
16762                            res.origPackage = bp.sourcePackage;
16763                            return;
16764                        } else {
16765                            Slog.w(TAG, "Package " + pkg.packageName
16766                                    + " attempting to redeclare system permission "
16767                                    + perm.info.name + "; ignoring new declaration");
16768                            pkg.permissions.remove(i);
16769                        }
16770                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16771                        // Prevent apps to change protection level to dangerous from any other
16772                        // type as this would allow a privilege escalation where an app adds a
16773                        // normal/signature permission in other app's group and later redefines
16774                        // it as dangerous leading to the group auto-grant.
16775                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16776                                == PermissionInfo.PROTECTION_DANGEROUS) {
16777                            if (bp != null && !bp.isRuntime()) {
16778                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16779                                        + "non-runtime permission " + perm.info.name
16780                                        + " to runtime; keeping old protection level");
16781                                perm.info.protectionLevel = bp.protectionLevel;
16782                            }
16783                        }
16784                    }
16785                }
16786            }
16787        }
16788
16789        if (systemApp) {
16790            if (onExternal) {
16791                // Abort update; system app can't be replaced with app on sdcard
16792                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16793                        "Cannot install updates to system apps on sdcard");
16794                return;
16795            } else if (instantApp) {
16796                // Abort update; system app can't be replaced with an instant app
16797                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16798                        "Cannot update a system app with an instant app");
16799                return;
16800            }
16801        }
16802
16803        if (args.move != null) {
16804            // We did an in-place move, so dex is ready to roll
16805            scanFlags |= SCAN_NO_DEX;
16806            scanFlags |= SCAN_MOVE;
16807
16808            synchronized (mPackages) {
16809                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16810                if (ps == null) {
16811                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16812                            "Missing settings for moved package " + pkgName);
16813                }
16814
16815                // We moved the entire application as-is, so bring over the
16816                // previously derived ABI information.
16817                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16818                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16819            }
16820
16821        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16822            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16823            scanFlags |= SCAN_NO_DEX;
16824
16825            try {
16826                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16827                    args.abiOverride : pkg.cpuAbiOverride);
16828                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16829                        true /*extractLibs*/, mAppLib32InstallDir);
16830            } catch (PackageManagerException pme) {
16831                Slog.e(TAG, "Error deriving application ABI", pme);
16832                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16833                return;
16834            }
16835
16836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16837            // Do not run PackageDexOptimizer through the local performDexOpt
16838            // method because `pkg` may not be in `mPackages` yet.
16839            //
16840            // Also, don't fail application installs if the dexopt step fails.
16841            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16842                    null /* instructionSets */, false /* checkProfiles */,
16843                    getCompilerFilterForReason(REASON_INSTALL),
16844                    getOrCreateCompilerPackageStats(pkg),
16845                    mDexManager.isUsedByOtherApps(pkg.packageName));
16846            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16847
16848            // Notify BackgroundDexOptJobService that the package has been changed.
16849            // If this is an update of a package which used to fail to compile,
16850            // BDOS will remove it from its blacklist.
16851            // TODO: Layering violation
16852            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16853        }
16854
16855        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16856            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16857            return;
16858        }
16859
16860        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16861
16862        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16863                "installPackageLI")) {
16864            if (replace) {
16865                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16866                    // Static libs have a synthetic package name containing the version
16867                    // and cannot be updated as an update would get a new package name,
16868                    // unless this is the exact same version code which is useful for
16869                    // development.
16870                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16871                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16872                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16873                                + "static-shared libs cannot be updated");
16874                        return;
16875                    }
16876                }
16877                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16878                        installerPackageName, res, args.installReason);
16879            } else {
16880                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16881                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16882            }
16883        }
16884        synchronized (mPackages) {
16885            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16886            if (ps != null) {
16887                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16888            }
16889
16890            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16891            for (int i = 0; i < childCount; i++) {
16892                PackageParser.Package childPkg = pkg.childPackages.get(i);
16893                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16894                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16895                if (childPs != null) {
16896                    childRes.newUsers = childPs.queryInstalledUsers(
16897                            sUserManager.getUserIds(), true);
16898                }
16899            }
16900
16901            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16902                updateSequenceNumberLP(pkgName, res.newUsers);
16903            }
16904        }
16905    }
16906
16907    private void startIntentFilterVerifications(int userId, boolean replacing,
16908            PackageParser.Package pkg) {
16909        if (mIntentFilterVerifierComponent == null) {
16910            Slog.w(TAG, "No IntentFilter verification will not be done as "
16911                    + "there is no IntentFilterVerifier available!");
16912            return;
16913        }
16914
16915        final int verifierUid = getPackageUid(
16916                mIntentFilterVerifierComponent.getPackageName(),
16917                MATCH_DEBUG_TRIAGED_MISSING,
16918                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16919
16920        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16921        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16922        mHandler.sendMessage(msg);
16923
16924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16925        for (int i = 0; i < childCount; i++) {
16926            PackageParser.Package childPkg = pkg.childPackages.get(i);
16927            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16928            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16929            mHandler.sendMessage(msg);
16930        }
16931    }
16932
16933    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16934            PackageParser.Package pkg) {
16935        int size = pkg.activities.size();
16936        if (size == 0) {
16937            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16938                    "No activity, so no need to verify any IntentFilter!");
16939            return;
16940        }
16941
16942        final boolean hasDomainURLs = hasDomainURLs(pkg);
16943        if (!hasDomainURLs) {
16944            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16945                    "No domain URLs, so no need to verify any IntentFilter!");
16946            return;
16947        }
16948
16949        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16950                + " if any IntentFilter from the " + size
16951                + " Activities needs verification ...");
16952
16953        int count = 0;
16954        final String packageName = pkg.packageName;
16955
16956        synchronized (mPackages) {
16957            // If this is a new install and we see that we've already run verification for this
16958            // package, we have nothing to do: it means the state was restored from backup.
16959            if (!replacing) {
16960                IntentFilterVerificationInfo ivi =
16961                        mSettings.getIntentFilterVerificationLPr(packageName);
16962                if (ivi != null) {
16963                    if (DEBUG_DOMAIN_VERIFICATION) {
16964                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16965                                + ivi.getStatusString());
16966                    }
16967                    return;
16968                }
16969            }
16970
16971            // If any filters need to be verified, then all need to be.
16972            boolean needToVerify = false;
16973            for (PackageParser.Activity a : pkg.activities) {
16974                for (ActivityIntentInfo filter : a.intents) {
16975                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16976                        if (DEBUG_DOMAIN_VERIFICATION) {
16977                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16978                        }
16979                        needToVerify = true;
16980                        break;
16981                    }
16982                }
16983            }
16984
16985            if (needToVerify) {
16986                final int verificationId = mIntentFilterVerificationToken++;
16987                for (PackageParser.Activity a : pkg.activities) {
16988                    for (ActivityIntentInfo filter : a.intents) {
16989                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16990                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16991                                    "Verification needed for IntentFilter:" + filter.toString());
16992                            mIntentFilterVerifier.addOneIntentFilterVerification(
16993                                    verifierUid, userId, verificationId, filter, packageName);
16994                            count++;
16995                        }
16996                    }
16997                }
16998            }
16999        }
17000
17001        if (count > 0) {
17002            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17003                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17004                    +  " for userId:" + userId);
17005            mIntentFilterVerifier.startVerifications(userId);
17006        } else {
17007            if (DEBUG_DOMAIN_VERIFICATION) {
17008                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17009            }
17010        }
17011    }
17012
17013    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17014        final ComponentName cn  = filter.activity.getComponentName();
17015        final String packageName = cn.getPackageName();
17016
17017        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17018                packageName);
17019        if (ivi == null) {
17020            return true;
17021        }
17022        int status = ivi.getStatus();
17023        switch (status) {
17024            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17025            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17026                return true;
17027
17028            default:
17029                // Nothing to do
17030                return false;
17031        }
17032    }
17033
17034    private static boolean isMultiArch(ApplicationInfo info) {
17035        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17036    }
17037
17038    private static boolean isExternal(PackageParser.Package pkg) {
17039        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17040    }
17041
17042    private static boolean isExternal(PackageSetting ps) {
17043        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17044    }
17045
17046    private static boolean isSystemApp(PackageParser.Package pkg) {
17047        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17048    }
17049
17050    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17051        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17052    }
17053
17054    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17055        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17056    }
17057
17058    private static boolean isSystemApp(PackageSetting ps) {
17059        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17060    }
17061
17062    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17063        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17064    }
17065
17066    private int packageFlagsToInstallFlags(PackageSetting ps) {
17067        int installFlags = 0;
17068        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17069            // This existing package was an external ASEC install when we have
17070            // the external flag without a UUID
17071            installFlags |= PackageManager.INSTALL_EXTERNAL;
17072        }
17073        if (ps.isForwardLocked()) {
17074            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17075        }
17076        return installFlags;
17077    }
17078
17079    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17080        if (isExternal(pkg)) {
17081            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17082                return StorageManager.UUID_PRIMARY_PHYSICAL;
17083            } else {
17084                return pkg.volumeUuid;
17085            }
17086        } else {
17087            return StorageManager.UUID_PRIVATE_INTERNAL;
17088        }
17089    }
17090
17091    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17092        if (isExternal(pkg)) {
17093            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17094                return mSettings.getExternalVersion();
17095            } else {
17096                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17097            }
17098        } else {
17099            return mSettings.getInternalVersion();
17100        }
17101    }
17102
17103    private void deleteTempPackageFiles() {
17104        final FilenameFilter filter = new FilenameFilter() {
17105            public boolean accept(File dir, String name) {
17106                return name.startsWith("vmdl") && name.endsWith(".tmp");
17107            }
17108        };
17109        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17110            file.delete();
17111        }
17112    }
17113
17114    @Override
17115    public void deletePackageAsUser(String packageName, int versionCode,
17116            IPackageDeleteObserver observer, int userId, int flags) {
17117        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17118                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17119    }
17120
17121    @Override
17122    public void deletePackageVersioned(VersionedPackage versionedPackage,
17123            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17124        mContext.enforceCallingOrSelfPermission(
17125                android.Manifest.permission.DELETE_PACKAGES, null);
17126        Preconditions.checkNotNull(versionedPackage);
17127        Preconditions.checkNotNull(observer);
17128        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17129                PackageManager.VERSION_CODE_HIGHEST,
17130                Integer.MAX_VALUE, "versionCode must be >= -1");
17131
17132        final String packageName = versionedPackage.getPackageName();
17133        // TODO: We will change version code to long, so in the new API it is long
17134        final int versionCode = (int) versionedPackage.getVersionCode();
17135        final String internalPackageName;
17136        synchronized (mPackages) {
17137            // Normalize package name to handle renamed packages and static libs
17138            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17139                    // TODO: We will change version code to long, so in the new API it is long
17140                    (int) versionedPackage.getVersionCode());
17141        }
17142
17143        final int uid = Binder.getCallingUid();
17144        if (!isOrphaned(internalPackageName)
17145                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17146            try {
17147                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17148                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17149                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17150                observer.onUserActionRequired(intent);
17151            } catch (RemoteException re) {
17152            }
17153            return;
17154        }
17155        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17156        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17157        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17158            mContext.enforceCallingOrSelfPermission(
17159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17160                    "deletePackage for user " + userId);
17161        }
17162
17163        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17164            try {
17165                observer.onPackageDeleted(packageName,
17166                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17167            } catch (RemoteException re) {
17168            }
17169            return;
17170        }
17171
17172        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17173            try {
17174                observer.onPackageDeleted(packageName,
17175                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17176            } catch (RemoteException re) {
17177            }
17178            return;
17179        }
17180
17181        if (DEBUG_REMOVE) {
17182            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17183                    + " deleteAllUsers: " + deleteAllUsers + " version="
17184                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17185                    ? "VERSION_CODE_HIGHEST" : versionCode));
17186        }
17187        // Queue up an async operation since the package deletion may take a little while.
17188        mHandler.post(new Runnable() {
17189            public void run() {
17190                mHandler.removeCallbacks(this);
17191                int returnCode;
17192                if (!deleteAllUsers) {
17193                    returnCode = deletePackageX(internalPackageName, versionCode,
17194                            userId, deleteFlags);
17195                } else {
17196                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17197                            internalPackageName, users);
17198                    // If nobody is blocking uninstall, proceed with delete for all users
17199                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17200                        returnCode = deletePackageX(internalPackageName, versionCode,
17201                                userId, deleteFlags);
17202                    } else {
17203                        // Otherwise uninstall individually for users with blockUninstalls=false
17204                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17205                        for (int userId : users) {
17206                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17207                                returnCode = deletePackageX(internalPackageName, versionCode,
17208                                        userId, userFlags);
17209                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17210                                    Slog.w(TAG, "Package delete failed for user " + userId
17211                                            + ", returnCode " + returnCode);
17212                                }
17213                            }
17214                        }
17215                        // The app has only been marked uninstalled for certain users.
17216                        // We still need to report that delete was blocked
17217                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17218                    }
17219                }
17220                try {
17221                    observer.onPackageDeleted(packageName, returnCode, null);
17222                } catch (RemoteException e) {
17223                    Log.i(TAG, "Observer no longer exists.");
17224                } //end catch
17225            } //end run
17226        });
17227    }
17228
17229    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17230        if (pkg.staticSharedLibName != null) {
17231            return pkg.manifestPackageName;
17232        }
17233        return pkg.packageName;
17234    }
17235
17236    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17237        // Handle renamed packages
17238        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17239        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17240
17241        // Is this a static library?
17242        SparseArray<SharedLibraryEntry> versionedLib =
17243                mStaticLibsByDeclaringPackage.get(packageName);
17244        if (versionedLib == null || versionedLib.size() <= 0) {
17245            return packageName;
17246        }
17247
17248        // Figure out which lib versions the caller can see
17249        SparseIntArray versionsCallerCanSee = null;
17250        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17251        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17252                && callingAppId != Process.ROOT_UID) {
17253            versionsCallerCanSee = new SparseIntArray();
17254            String libName = versionedLib.valueAt(0).info.getName();
17255            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17256            if (uidPackages != null) {
17257                for (String uidPackage : uidPackages) {
17258                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17259                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17260                    if (libIdx >= 0) {
17261                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17262                        versionsCallerCanSee.append(libVersion, libVersion);
17263                    }
17264                }
17265            }
17266        }
17267
17268        // Caller can see nothing - done
17269        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17270            return packageName;
17271        }
17272
17273        // Find the version the caller can see and the app version code
17274        SharedLibraryEntry highestVersion = null;
17275        final int versionCount = versionedLib.size();
17276        for (int i = 0; i < versionCount; i++) {
17277            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17278            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17279                    libEntry.info.getVersion()) < 0) {
17280                continue;
17281            }
17282            // TODO: We will change version code to long, so in the new API it is long
17283            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17284            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17285                if (libVersionCode == versionCode) {
17286                    return libEntry.apk;
17287                }
17288            } else if (highestVersion == null) {
17289                highestVersion = libEntry;
17290            } else if (libVersionCode  > highestVersion.info
17291                    .getDeclaringPackage().getVersionCode()) {
17292                highestVersion = libEntry;
17293            }
17294        }
17295
17296        if (highestVersion != null) {
17297            return highestVersion.apk;
17298        }
17299
17300        return packageName;
17301    }
17302
17303    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17304        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17305              || callingUid == Process.SYSTEM_UID) {
17306            return true;
17307        }
17308        final int callingUserId = UserHandle.getUserId(callingUid);
17309        // If the caller installed the pkgName, then allow it to silently uninstall.
17310        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17311            return true;
17312        }
17313
17314        // Allow package verifier to silently uninstall.
17315        if (mRequiredVerifierPackage != null &&
17316                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17317            return true;
17318        }
17319
17320        // Allow package uninstaller to silently uninstall.
17321        if (mRequiredUninstallerPackage != null &&
17322                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17323            return true;
17324        }
17325
17326        // Allow storage manager to silently uninstall.
17327        if (mStorageManagerPackage != null &&
17328                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17329            return true;
17330        }
17331        return false;
17332    }
17333
17334    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17335        int[] result = EMPTY_INT_ARRAY;
17336        for (int userId : userIds) {
17337            if (getBlockUninstallForUser(packageName, userId)) {
17338                result = ArrayUtils.appendInt(result, userId);
17339            }
17340        }
17341        return result;
17342    }
17343
17344    @Override
17345    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17346        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17347    }
17348
17349    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17350        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17351                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17352        try {
17353            if (dpm != null) {
17354                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17355                        /* callingUserOnly =*/ false);
17356                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17357                        : deviceOwnerComponentName.getPackageName();
17358                // Does the package contains the device owner?
17359                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17360                // this check is probably not needed, since DO should be registered as a device
17361                // admin on some user too. (Original bug for this: b/17657954)
17362                if (packageName.equals(deviceOwnerPackageName)) {
17363                    return true;
17364                }
17365                // Does it contain a device admin for any user?
17366                int[] users;
17367                if (userId == UserHandle.USER_ALL) {
17368                    users = sUserManager.getUserIds();
17369                } else {
17370                    users = new int[]{userId};
17371                }
17372                for (int i = 0; i < users.length; ++i) {
17373                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17374                        return true;
17375                    }
17376                }
17377            }
17378        } catch (RemoteException e) {
17379        }
17380        return false;
17381    }
17382
17383    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17384        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17385    }
17386
17387    /**
17388     *  This method is an internal method that could be get invoked either
17389     *  to delete an installed package or to clean up a failed installation.
17390     *  After deleting an installed package, a broadcast is sent to notify any
17391     *  listeners that the package has been removed. For cleaning up a failed
17392     *  installation, the broadcast is not necessary since the package's
17393     *  installation wouldn't have sent the initial broadcast either
17394     *  The key steps in deleting a package are
17395     *  deleting the package information in internal structures like mPackages,
17396     *  deleting the packages base directories through installd
17397     *  updating mSettings to reflect current status
17398     *  persisting settings for later use
17399     *  sending a broadcast if necessary
17400     */
17401    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17402        final PackageRemovedInfo info = new PackageRemovedInfo();
17403        final boolean res;
17404
17405        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17406                ? UserHandle.USER_ALL : userId;
17407
17408        if (isPackageDeviceAdmin(packageName, removeUser)) {
17409            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17410            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17411        }
17412
17413        PackageSetting uninstalledPs = null;
17414
17415        // for the uninstall-updates case and restricted profiles, remember the per-
17416        // user handle installed state
17417        int[] allUsers;
17418        synchronized (mPackages) {
17419            uninstalledPs = mSettings.mPackages.get(packageName);
17420            if (uninstalledPs == null) {
17421                Slog.w(TAG, "Not removing non-existent package " + packageName);
17422                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17423            }
17424
17425            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17426                    && uninstalledPs.versionCode != versionCode) {
17427                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17428                        + uninstalledPs.versionCode + " != " + versionCode);
17429                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17430            }
17431
17432            // Static shared libs can be declared by any package, so let us not
17433            // allow removing a package if it provides a lib others depend on.
17434            PackageParser.Package pkg = mPackages.get(packageName);
17435            if (pkg != null && pkg.staticSharedLibName != null) {
17436                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17437                        pkg.staticSharedLibVersion);
17438                if (libEntry != null) {
17439                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17440                            libEntry.info, 0, userId);
17441                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17442                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17443                                + " hosting lib " + libEntry.info.getName() + " version "
17444                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17445                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17446                    }
17447                }
17448            }
17449
17450            allUsers = sUserManager.getUserIds();
17451            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17452        }
17453
17454        final int freezeUser;
17455        if (isUpdatedSystemApp(uninstalledPs)
17456                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17457            // We're downgrading a system app, which will apply to all users, so
17458            // freeze them all during the downgrade
17459            freezeUser = UserHandle.USER_ALL;
17460        } else {
17461            freezeUser = removeUser;
17462        }
17463
17464        synchronized (mInstallLock) {
17465            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17466            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17467                    deleteFlags, "deletePackageX")) {
17468                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17469                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17470            }
17471            synchronized (mPackages) {
17472                if (res) {
17473                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17474                            info.removedUsers);
17475                    updateSequenceNumberLP(packageName, info.removedUsers);
17476                }
17477            }
17478        }
17479
17480        if (res) {
17481            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17482            info.sendPackageRemovedBroadcasts(killApp);
17483            info.sendSystemPackageUpdatedBroadcasts();
17484            info.sendSystemPackageAppearedBroadcasts();
17485        }
17486        // Force a gc here.
17487        Runtime.getRuntime().gc();
17488        // Delete the resources here after sending the broadcast to let
17489        // other processes clean up before deleting resources.
17490        if (info.args != null) {
17491            synchronized (mInstallLock) {
17492                info.args.doPostDeleteLI(true);
17493            }
17494        }
17495
17496        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17497    }
17498
17499    class PackageRemovedInfo {
17500        String removedPackage;
17501        int uid = -1;
17502        int removedAppId = -1;
17503        int[] origUsers;
17504        int[] removedUsers = null;
17505        SparseArray<Integer> installReasons;
17506        boolean isRemovedPackageSystemUpdate = false;
17507        boolean isUpdate;
17508        boolean dataRemoved;
17509        boolean removedForAllUsers;
17510        boolean isStaticSharedLib;
17511        // Clean up resources deleted packages.
17512        InstallArgs args = null;
17513        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17514        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17515
17516        void sendPackageRemovedBroadcasts(boolean killApp) {
17517            sendPackageRemovedBroadcastInternal(killApp);
17518            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17519            for (int i = 0; i < childCount; i++) {
17520                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17521                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17522            }
17523        }
17524
17525        void sendSystemPackageUpdatedBroadcasts() {
17526            if (isRemovedPackageSystemUpdate) {
17527                sendSystemPackageUpdatedBroadcastsInternal();
17528                final int childCount = (removedChildPackages != null)
17529                        ? removedChildPackages.size() : 0;
17530                for (int i = 0; i < childCount; i++) {
17531                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17532                    if (childInfo.isRemovedPackageSystemUpdate) {
17533                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17534                    }
17535                }
17536            }
17537        }
17538
17539        void sendSystemPackageAppearedBroadcasts() {
17540            final int packageCount = (appearedChildPackages != null)
17541                    ? appearedChildPackages.size() : 0;
17542            for (int i = 0; i < packageCount; i++) {
17543                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17544                sendPackageAddedForNewUsers(installedInfo.name, true,
17545                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17546            }
17547        }
17548
17549        private void sendSystemPackageUpdatedBroadcastsInternal() {
17550            Bundle extras = new Bundle(2);
17551            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17552            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17553            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17554                    extras, 0, null, null, null);
17555            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17556                    extras, 0, null, null, null);
17557            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17558                    null, 0, removedPackage, null, null);
17559        }
17560
17561        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17562            // Don't send static shared library removal broadcasts as these
17563            // libs are visible only the the apps that depend on them an one
17564            // cannot remove the library if it has a dependency.
17565            if (isStaticSharedLib) {
17566                return;
17567            }
17568            Bundle extras = new Bundle(2);
17569            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17570            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17571            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17572            if (isUpdate || isRemovedPackageSystemUpdate) {
17573                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17574            }
17575            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17576            if (removedPackage != null) {
17577                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17578                        extras, 0, null, null, removedUsers);
17579                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17580                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17581                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17582                            null, null, removedUsers);
17583                }
17584            }
17585            if (removedAppId >= 0) {
17586                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17587                        removedUsers);
17588            }
17589        }
17590    }
17591
17592    /*
17593     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17594     * flag is not set, the data directory is removed as well.
17595     * make sure this flag is set for partially installed apps. If not its meaningless to
17596     * delete a partially installed application.
17597     */
17598    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17599            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17600        String packageName = ps.name;
17601        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17602        // Retrieve object to delete permissions for shared user later on
17603        final PackageParser.Package deletedPkg;
17604        final PackageSetting deletedPs;
17605        // reader
17606        synchronized (mPackages) {
17607            deletedPkg = mPackages.get(packageName);
17608            deletedPs = mSettings.mPackages.get(packageName);
17609            if (outInfo != null) {
17610                outInfo.removedPackage = packageName;
17611                outInfo.isStaticSharedLib = deletedPkg != null
17612                        && deletedPkg.staticSharedLibName != null;
17613                outInfo.removedUsers = deletedPs != null
17614                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17615                        : null;
17616            }
17617        }
17618
17619        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17620
17621        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17622            final PackageParser.Package resolvedPkg;
17623            if (deletedPkg != null) {
17624                resolvedPkg = deletedPkg;
17625            } else {
17626                // We don't have a parsed package when it lives on an ejected
17627                // adopted storage device, so fake something together
17628                resolvedPkg = new PackageParser.Package(ps.name);
17629                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17630            }
17631            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17632                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17633            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17634            if (outInfo != null) {
17635                outInfo.dataRemoved = true;
17636            }
17637            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17638        }
17639
17640        int removedAppId = -1;
17641
17642        // writer
17643        synchronized (mPackages) {
17644            boolean installedStateChanged = false;
17645            if (deletedPs != null) {
17646                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17647                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17648                    clearDefaultBrowserIfNeeded(packageName);
17649                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17650                    removedAppId = mSettings.removePackageLPw(packageName);
17651                    if (outInfo != null) {
17652                        outInfo.removedAppId = removedAppId;
17653                    }
17654                    updatePermissionsLPw(deletedPs.name, null, 0);
17655                    if (deletedPs.sharedUser != null) {
17656                        // Remove permissions associated with package. Since runtime
17657                        // permissions are per user we have to kill the removed package
17658                        // or packages running under the shared user of the removed
17659                        // package if revoking the permissions requested only by the removed
17660                        // package is successful and this causes a change in gids.
17661                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17662                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17663                                    userId);
17664                            if (userIdToKill == UserHandle.USER_ALL
17665                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17666                                // If gids changed for this user, kill all affected packages.
17667                                mHandler.post(new Runnable() {
17668                                    @Override
17669                                    public void run() {
17670                                        // This has to happen with no lock held.
17671                                        killApplication(deletedPs.name, deletedPs.appId,
17672                                                KILL_APP_REASON_GIDS_CHANGED);
17673                                    }
17674                                });
17675                                break;
17676                            }
17677                        }
17678                    }
17679                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17680                }
17681                // make sure to preserve per-user disabled state if this removal was just
17682                // a downgrade of a system app to the factory package
17683                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17684                    if (DEBUG_REMOVE) {
17685                        Slog.d(TAG, "Propagating install state across downgrade");
17686                    }
17687                    for (int userId : allUserHandles) {
17688                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17689                        if (DEBUG_REMOVE) {
17690                            Slog.d(TAG, "    user " + userId + " => " + installed);
17691                        }
17692                        if (installed != ps.getInstalled(userId)) {
17693                            installedStateChanged = true;
17694                        }
17695                        ps.setInstalled(installed, userId);
17696                    }
17697                }
17698            }
17699            // can downgrade to reader
17700            if (writeSettings) {
17701                // Save settings now
17702                mSettings.writeLPr();
17703            }
17704            if (installedStateChanged) {
17705                mSettings.writeKernelMappingLPr(ps);
17706            }
17707        }
17708        if (removedAppId != -1) {
17709            // A user ID was deleted here. Go through all users and remove it
17710            // from KeyStore.
17711            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17712        }
17713    }
17714
17715    static boolean locationIsPrivileged(File path) {
17716        try {
17717            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17718                    .getCanonicalPath();
17719            return path.getCanonicalPath().startsWith(privilegedAppDir);
17720        } catch (IOException e) {
17721            Slog.e(TAG, "Unable to access code path " + path);
17722        }
17723        return false;
17724    }
17725
17726    /*
17727     * Tries to delete system package.
17728     */
17729    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17730            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17731            boolean writeSettings) {
17732        if (deletedPs.parentPackageName != null) {
17733            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17734            return false;
17735        }
17736
17737        final boolean applyUserRestrictions
17738                = (allUserHandles != null) && (outInfo.origUsers != null);
17739        final PackageSetting disabledPs;
17740        // Confirm if the system package has been updated
17741        // An updated system app can be deleted. This will also have to restore
17742        // the system pkg from system partition
17743        // reader
17744        synchronized (mPackages) {
17745            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17746        }
17747
17748        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17749                + " disabledPs=" + disabledPs);
17750
17751        if (disabledPs == null) {
17752            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17753            return false;
17754        } else if (DEBUG_REMOVE) {
17755            Slog.d(TAG, "Deleting system pkg from data partition");
17756        }
17757
17758        if (DEBUG_REMOVE) {
17759            if (applyUserRestrictions) {
17760                Slog.d(TAG, "Remembering install states:");
17761                for (int userId : allUserHandles) {
17762                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17763                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17764                }
17765            }
17766        }
17767
17768        // Delete the updated package
17769        outInfo.isRemovedPackageSystemUpdate = true;
17770        if (outInfo.removedChildPackages != null) {
17771            final int childCount = (deletedPs.childPackageNames != null)
17772                    ? deletedPs.childPackageNames.size() : 0;
17773            for (int i = 0; i < childCount; i++) {
17774                String childPackageName = deletedPs.childPackageNames.get(i);
17775                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17776                        .contains(childPackageName)) {
17777                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17778                            childPackageName);
17779                    if (childInfo != null) {
17780                        childInfo.isRemovedPackageSystemUpdate = true;
17781                    }
17782                }
17783            }
17784        }
17785
17786        if (disabledPs.versionCode < deletedPs.versionCode) {
17787            // Delete data for downgrades
17788            flags &= ~PackageManager.DELETE_KEEP_DATA;
17789        } else {
17790            // Preserve data by setting flag
17791            flags |= PackageManager.DELETE_KEEP_DATA;
17792        }
17793
17794        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17795                outInfo, writeSettings, disabledPs.pkg);
17796        if (!ret) {
17797            return false;
17798        }
17799
17800        // writer
17801        synchronized (mPackages) {
17802            // Reinstate the old system package
17803            enableSystemPackageLPw(disabledPs.pkg);
17804            // Remove any native libraries from the upgraded package.
17805            removeNativeBinariesLI(deletedPs);
17806        }
17807
17808        // Install the system package
17809        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17810        int parseFlags = mDefParseFlags
17811                | PackageParser.PARSE_MUST_BE_APK
17812                | PackageParser.PARSE_IS_SYSTEM
17813                | PackageParser.PARSE_IS_SYSTEM_DIR;
17814        if (locationIsPrivileged(disabledPs.codePath)) {
17815            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17816        }
17817
17818        final PackageParser.Package newPkg;
17819        try {
17820            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17821                0 /* currentTime */, null);
17822        } catch (PackageManagerException e) {
17823            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17824                    + e.getMessage());
17825            return false;
17826        }
17827
17828        try {
17829            // update shared libraries for the newly re-installed system package
17830            updateSharedLibrariesLPr(newPkg, null);
17831        } catch (PackageManagerException e) {
17832            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17833        }
17834
17835        prepareAppDataAfterInstallLIF(newPkg);
17836
17837        // writer
17838        synchronized (mPackages) {
17839            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17840
17841            // Propagate the permissions state as we do not want to drop on the floor
17842            // runtime permissions. The update permissions method below will take
17843            // care of removing obsolete permissions and grant install permissions.
17844            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17845            updatePermissionsLPw(newPkg.packageName, newPkg,
17846                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17847
17848            if (applyUserRestrictions) {
17849                boolean installedStateChanged = false;
17850                if (DEBUG_REMOVE) {
17851                    Slog.d(TAG, "Propagating install state across reinstall");
17852                }
17853                for (int userId : allUserHandles) {
17854                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17855                    if (DEBUG_REMOVE) {
17856                        Slog.d(TAG, "    user " + userId + " => " + installed);
17857                    }
17858                    if (installed != ps.getInstalled(userId)) {
17859                        installedStateChanged = true;
17860                    }
17861                    ps.setInstalled(installed, userId);
17862
17863                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17864                }
17865                // Regardless of writeSettings we need to ensure that this restriction
17866                // state propagation is persisted
17867                mSettings.writeAllUsersPackageRestrictionsLPr();
17868                if (installedStateChanged) {
17869                    mSettings.writeKernelMappingLPr(ps);
17870                }
17871            }
17872            // can downgrade to reader here
17873            if (writeSettings) {
17874                mSettings.writeLPr();
17875            }
17876        }
17877        return true;
17878    }
17879
17880    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17881            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17882            PackageRemovedInfo outInfo, boolean writeSettings,
17883            PackageParser.Package replacingPackage) {
17884        synchronized (mPackages) {
17885            if (outInfo != null) {
17886                outInfo.uid = ps.appId;
17887            }
17888
17889            if (outInfo != null && outInfo.removedChildPackages != null) {
17890                final int childCount = (ps.childPackageNames != null)
17891                        ? ps.childPackageNames.size() : 0;
17892                for (int i = 0; i < childCount; i++) {
17893                    String childPackageName = ps.childPackageNames.get(i);
17894                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17895                    if (childPs == null) {
17896                        return false;
17897                    }
17898                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17899                            childPackageName);
17900                    if (childInfo != null) {
17901                        childInfo.uid = childPs.appId;
17902                    }
17903                }
17904            }
17905        }
17906
17907        // Delete package data from internal structures and also remove data if flag is set
17908        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17909
17910        // Delete the child packages data
17911        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17912        for (int i = 0; i < childCount; i++) {
17913            PackageSetting childPs;
17914            synchronized (mPackages) {
17915                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17916            }
17917            if (childPs != null) {
17918                PackageRemovedInfo childOutInfo = (outInfo != null
17919                        && outInfo.removedChildPackages != null)
17920                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17921                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17922                        && (replacingPackage != null
17923                        && !replacingPackage.hasChildPackage(childPs.name))
17924                        ? flags & ~DELETE_KEEP_DATA : flags;
17925                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17926                        deleteFlags, writeSettings);
17927            }
17928        }
17929
17930        // Delete application code and resources only for parent packages
17931        if (ps.parentPackageName == null) {
17932            if (deleteCodeAndResources && (outInfo != null)) {
17933                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17934                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17935                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17936            }
17937        }
17938
17939        return true;
17940    }
17941
17942    @Override
17943    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17944            int userId) {
17945        mContext.enforceCallingOrSelfPermission(
17946                android.Manifest.permission.DELETE_PACKAGES, null);
17947        synchronized (mPackages) {
17948            PackageSetting ps = mSettings.mPackages.get(packageName);
17949            if (ps == null) {
17950                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17951                return false;
17952            }
17953            // Cannot block uninstall of static shared libs as they are
17954            // considered a part of the using app (emulating static linking).
17955            // Also static libs are installed always on internal storage.
17956            PackageParser.Package pkg = mPackages.get(packageName);
17957            if (pkg != null && pkg.staticSharedLibName != null) {
17958                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17959                        + " providing static shared library: " + pkg.staticSharedLibName);
17960                return false;
17961            }
17962            if (!ps.getInstalled(userId)) {
17963                // Can't block uninstall for an app that is not installed or enabled.
17964                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17965                return false;
17966            }
17967            ps.setBlockUninstall(blockUninstall, userId);
17968            mSettings.writePackageRestrictionsLPr(userId);
17969        }
17970        return true;
17971    }
17972
17973    @Override
17974    public boolean getBlockUninstallForUser(String packageName, int userId) {
17975        synchronized (mPackages) {
17976            PackageSetting ps = mSettings.mPackages.get(packageName);
17977            if (ps == null) {
17978                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17979                return false;
17980            }
17981            return ps.getBlockUninstall(userId);
17982        }
17983    }
17984
17985    @Override
17986    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17987        int callingUid = Binder.getCallingUid();
17988        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17989            throw new SecurityException(
17990                    "setRequiredForSystemUser can only be run by the system or root");
17991        }
17992        synchronized (mPackages) {
17993            PackageSetting ps = mSettings.mPackages.get(packageName);
17994            if (ps == null) {
17995                Log.w(TAG, "Package doesn't exist: " + packageName);
17996                return false;
17997            }
17998            if (systemUserApp) {
17999                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18000            } else {
18001                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18002            }
18003            mSettings.writeLPr();
18004        }
18005        return true;
18006    }
18007
18008    /*
18009     * This method handles package deletion in general
18010     */
18011    private boolean deletePackageLIF(String packageName, UserHandle user,
18012            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18013            PackageRemovedInfo outInfo, boolean writeSettings,
18014            PackageParser.Package replacingPackage) {
18015        if (packageName == null) {
18016            Slog.w(TAG, "Attempt to delete null packageName.");
18017            return false;
18018        }
18019
18020        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18021
18022        PackageSetting ps;
18023        synchronized (mPackages) {
18024            ps = mSettings.mPackages.get(packageName);
18025            if (ps == null) {
18026                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18027                return false;
18028            }
18029
18030            if (ps.parentPackageName != null && (!isSystemApp(ps)
18031                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18032                if (DEBUG_REMOVE) {
18033                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18034                            + ((user == null) ? UserHandle.USER_ALL : user));
18035                }
18036                final int removedUserId = (user != null) ? user.getIdentifier()
18037                        : UserHandle.USER_ALL;
18038                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18039                    return false;
18040                }
18041                markPackageUninstalledForUserLPw(ps, user);
18042                scheduleWritePackageRestrictionsLocked(user);
18043                return true;
18044            }
18045        }
18046
18047        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18048                && user.getIdentifier() != UserHandle.USER_ALL)) {
18049            // The caller is asking that the package only be deleted for a single
18050            // user.  To do this, we just mark its uninstalled state and delete
18051            // its data. If this is a system app, we only allow this to happen if
18052            // they have set the special DELETE_SYSTEM_APP which requests different
18053            // semantics than normal for uninstalling system apps.
18054            markPackageUninstalledForUserLPw(ps, user);
18055
18056            if (!isSystemApp(ps)) {
18057                // Do not uninstall the APK if an app should be cached
18058                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18059                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18060                    // Other user still have this package installed, so all
18061                    // we need to do is clear this user's data and save that
18062                    // it is uninstalled.
18063                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18064                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18065                        return false;
18066                    }
18067                    scheduleWritePackageRestrictionsLocked(user);
18068                    return true;
18069                } else {
18070                    // We need to set it back to 'installed' so the uninstall
18071                    // broadcasts will be sent correctly.
18072                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18073                    ps.setInstalled(true, user.getIdentifier());
18074                    mSettings.writeKernelMappingLPr(ps);
18075                }
18076            } else {
18077                // This is a system app, so we assume that the
18078                // other users still have this package installed, so all
18079                // we need to do is clear this user's data and save that
18080                // it is uninstalled.
18081                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18082                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18083                    return false;
18084                }
18085                scheduleWritePackageRestrictionsLocked(user);
18086                return true;
18087            }
18088        }
18089
18090        // If we are deleting a composite package for all users, keep track
18091        // of result for each child.
18092        if (ps.childPackageNames != null && outInfo != null) {
18093            synchronized (mPackages) {
18094                final int childCount = ps.childPackageNames.size();
18095                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18096                for (int i = 0; i < childCount; i++) {
18097                    String childPackageName = ps.childPackageNames.get(i);
18098                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18099                    childInfo.removedPackage = childPackageName;
18100                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18101                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18102                    if (childPs != null) {
18103                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18104                    }
18105                }
18106            }
18107        }
18108
18109        boolean ret = false;
18110        if (isSystemApp(ps)) {
18111            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18112            // When an updated system application is deleted we delete the existing resources
18113            // as well and fall back to existing code in system partition
18114            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18115        } else {
18116            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18117            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18118                    outInfo, writeSettings, replacingPackage);
18119        }
18120
18121        // Take a note whether we deleted the package for all users
18122        if (outInfo != null) {
18123            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18124            if (outInfo.removedChildPackages != null) {
18125                synchronized (mPackages) {
18126                    final int childCount = outInfo.removedChildPackages.size();
18127                    for (int i = 0; i < childCount; i++) {
18128                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18129                        if (childInfo != null) {
18130                            childInfo.removedForAllUsers = mPackages.get(
18131                                    childInfo.removedPackage) == null;
18132                        }
18133                    }
18134                }
18135            }
18136            // If we uninstalled an update to a system app there may be some
18137            // child packages that appeared as they are declared in the system
18138            // app but were not declared in the update.
18139            if (isSystemApp(ps)) {
18140                synchronized (mPackages) {
18141                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18142                    final int childCount = (updatedPs.childPackageNames != null)
18143                            ? updatedPs.childPackageNames.size() : 0;
18144                    for (int i = 0; i < childCount; i++) {
18145                        String childPackageName = updatedPs.childPackageNames.get(i);
18146                        if (outInfo.removedChildPackages == null
18147                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18148                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18149                            if (childPs == null) {
18150                                continue;
18151                            }
18152                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18153                            installRes.name = childPackageName;
18154                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18155                            installRes.pkg = mPackages.get(childPackageName);
18156                            installRes.uid = childPs.pkg.applicationInfo.uid;
18157                            if (outInfo.appearedChildPackages == null) {
18158                                outInfo.appearedChildPackages = new ArrayMap<>();
18159                            }
18160                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18161                        }
18162                    }
18163                }
18164            }
18165        }
18166
18167        return ret;
18168    }
18169
18170    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18171        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18172                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18173        for (int nextUserId : userIds) {
18174            if (DEBUG_REMOVE) {
18175                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18176            }
18177            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18178                    false /*installed*/,
18179                    true /*stopped*/,
18180                    true /*notLaunched*/,
18181                    false /*hidden*/,
18182                    false /*suspended*/,
18183                    false /*instantApp*/,
18184                    null /*lastDisableAppCaller*/,
18185                    null /*enabledComponents*/,
18186                    null /*disabledComponents*/,
18187                    false /*blockUninstall*/,
18188                    ps.readUserState(nextUserId).domainVerificationStatus,
18189                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18190        }
18191        mSettings.writeKernelMappingLPr(ps);
18192    }
18193
18194    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18195            PackageRemovedInfo outInfo) {
18196        final PackageParser.Package pkg;
18197        synchronized (mPackages) {
18198            pkg = mPackages.get(ps.name);
18199        }
18200
18201        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18202                : new int[] {userId};
18203        for (int nextUserId : userIds) {
18204            if (DEBUG_REMOVE) {
18205                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18206                        + nextUserId);
18207            }
18208
18209            destroyAppDataLIF(pkg, userId,
18210                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18211            destroyAppProfilesLIF(pkg, userId);
18212            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18213            schedulePackageCleaning(ps.name, nextUserId, false);
18214            synchronized (mPackages) {
18215                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18216                    scheduleWritePackageRestrictionsLocked(nextUserId);
18217                }
18218                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18219            }
18220        }
18221
18222        if (outInfo != null) {
18223            outInfo.removedPackage = ps.name;
18224            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18225            outInfo.removedAppId = ps.appId;
18226            outInfo.removedUsers = userIds;
18227        }
18228
18229        return true;
18230    }
18231
18232    private final class ClearStorageConnection implements ServiceConnection {
18233        IMediaContainerService mContainerService;
18234
18235        @Override
18236        public void onServiceConnected(ComponentName name, IBinder service) {
18237            synchronized (this) {
18238                mContainerService = IMediaContainerService.Stub
18239                        .asInterface(Binder.allowBlocking(service));
18240                notifyAll();
18241            }
18242        }
18243
18244        @Override
18245        public void onServiceDisconnected(ComponentName name) {
18246        }
18247    }
18248
18249    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18250        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18251
18252        final boolean mounted;
18253        if (Environment.isExternalStorageEmulated()) {
18254            mounted = true;
18255        } else {
18256            final String status = Environment.getExternalStorageState();
18257
18258            mounted = status.equals(Environment.MEDIA_MOUNTED)
18259                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18260        }
18261
18262        if (!mounted) {
18263            return;
18264        }
18265
18266        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18267        int[] users;
18268        if (userId == UserHandle.USER_ALL) {
18269            users = sUserManager.getUserIds();
18270        } else {
18271            users = new int[] { userId };
18272        }
18273        final ClearStorageConnection conn = new ClearStorageConnection();
18274        if (mContext.bindServiceAsUser(
18275                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18276            try {
18277                for (int curUser : users) {
18278                    long timeout = SystemClock.uptimeMillis() + 5000;
18279                    synchronized (conn) {
18280                        long now;
18281                        while (conn.mContainerService == null &&
18282                                (now = SystemClock.uptimeMillis()) < timeout) {
18283                            try {
18284                                conn.wait(timeout - now);
18285                            } catch (InterruptedException e) {
18286                            }
18287                        }
18288                    }
18289                    if (conn.mContainerService == null) {
18290                        return;
18291                    }
18292
18293                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18294                    clearDirectory(conn.mContainerService,
18295                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18296                    if (allData) {
18297                        clearDirectory(conn.mContainerService,
18298                                userEnv.buildExternalStorageAppDataDirs(packageName));
18299                        clearDirectory(conn.mContainerService,
18300                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18301                    }
18302                }
18303            } finally {
18304                mContext.unbindService(conn);
18305            }
18306        }
18307    }
18308
18309    @Override
18310    public void clearApplicationProfileData(String packageName) {
18311        enforceSystemOrRoot("Only the system can clear all profile data");
18312
18313        final PackageParser.Package pkg;
18314        synchronized (mPackages) {
18315            pkg = mPackages.get(packageName);
18316        }
18317
18318        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18319            synchronized (mInstallLock) {
18320                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18321            }
18322        }
18323    }
18324
18325    @Override
18326    public void clearApplicationUserData(final String packageName,
18327            final IPackageDataObserver observer, final int userId) {
18328        mContext.enforceCallingOrSelfPermission(
18329                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18330
18331        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18332                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18333
18334        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18335            throw new SecurityException("Cannot clear data for a protected package: "
18336                    + packageName);
18337        }
18338        // Queue up an async operation since the package deletion may take a little while.
18339        mHandler.post(new Runnable() {
18340            public void run() {
18341                mHandler.removeCallbacks(this);
18342                final boolean succeeded;
18343                try (PackageFreezer freezer = freezePackage(packageName,
18344                        "clearApplicationUserData")) {
18345                    synchronized (mInstallLock) {
18346                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18347                    }
18348                    clearExternalStorageDataSync(packageName, userId, true);
18349                    synchronized (mPackages) {
18350                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18351                                packageName, userId);
18352                    }
18353                }
18354                if (succeeded) {
18355                    // invoke DeviceStorageMonitor's update method to clear any notifications
18356                    DeviceStorageMonitorInternal dsm = LocalServices
18357                            .getService(DeviceStorageMonitorInternal.class);
18358                    if (dsm != null) {
18359                        dsm.checkMemory();
18360                    }
18361                }
18362                if(observer != null) {
18363                    try {
18364                        observer.onRemoveCompleted(packageName, succeeded);
18365                    } catch (RemoteException e) {
18366                        Log.i(TAG, "Observer no longer exists.");
18367                    }
18368                } //end if observer
18369            } //end run
18370        });
18371    }
18372
18373    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18374        if (packageName == null) {
18375            Slog.w(TAG, "Attempt to delete null packageName.");
18376            return false;
18377        }
18378
18379        // Try finding details about the requested package
18380        PackageParser.Package pkg;
18381        synchronized (mPackages) {
18382            pkg = mPackages.get(packageName);
18383            if (pkg == null) {
18384                final PackageSetting ps = mSettings.mPackages.get(packageName);
18385                if (ps != null) {
18386                    pkg = ps.pkg;
18387                }
18388            }
18389
18390            if (pkg == null) {
18391                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18392                return false;
18393            }
18394
18395            PackageSetting ps = (PackageSetting) pkg.mExtras;
18396            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18397        }
18398
18399        clearAppDataLIF(pkg, userId,
18400                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18401
18402        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18403        removeKeystoreDataIfNeeded(userId, appId);
18404
18405        UserManagerInternal umInternal = getUserManagerInternal();
18406        final int flags;
18407        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18408            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18409        } else if (umInternal.isUserRunning(userId)) {
18410            flags = StorageManager.FLAG_STORAGE_DE;
18411        } else {
18412            flags = 0;
18413        }
18414        prepareAppDataContentsLIF(pkg, userId, flags);
18415
18416        return true;
18417    }
18418
18419    /**
18420     * Reverts user permission state changes (permissions and flags) in
18421     * all packages for a given user.
18422     *
18423     * @param userId The device user for which to do a reset.
18424     */
18425    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18426        final int packageCount = mPackages.size();
18427        for (int i = 0; i < packageCount; i++) {
18428            PackageParser.Package pkg = mPackages.valueAt(i);
18429            PackageSetting ps = (PackageSetting) pkg.mExtras;
18430            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18431        }
18432    }
18433
18434    private void resetNetworkPolicies(int userId) {
18435        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18436    }
18437
18438    /**
18439     * Reverts user permission state changes (permissions and flags).
18440     *
18441     * @param ps The package for which to reset.
18442     * @param userId The device user for which to do a reset.
18443     */
18444    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18445            final PackageSetting ps, final int userId) {
18446        if (ps.pkg == null) {
18447            return;
18448        }
18449
18450        // These are flags that can change base on user actions.
18451        final int userSettableMask = FLAG_PERMISSION_USER_SET
18452                | FLAG_PERMISSION_USER_FIXED
18453                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18454                | FLAG_PERMISSION_REVIEW_REQUIRED;
18455
18456        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18457                | FLAG_PERMISSION_POLICY_FIXED;
18458
18459        boolean writeInstallPermissions = false;
18460        boolean writeRuntimePermissions = false;
18461
18462        final int permissionCount = ps.pkg.requestedPermissions.size();
18463        for (int i = 0; i < permissionCount; i++) {
18464            String permission = ps.pkg.requestedPermissions.get(i);
18465
18466            BasePermission bp = mSettings.mPermissions.get(permission);
18467            if (bp == null) {
18468                continue;
18469            }
18470
18471            // If shared user we just reset the state to which only this app contributed.
18472            if (ps.sharedUser != null) {
18473                boolean used = false;
18474                final int packageCount = ps.sharedUser.packages.size();
18475                for (int j = 0; j < packageCount; j++) {
18476                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18477                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18478                            && pkg.pkg.requestedPermissions.contains(permission)) {
18479                        used = true;
18480                        break;
18481                    }
18482                }
18483                if (used) {
18484                    continue;
18485                }
18486            }
18487
18488            PermissionsState permissionsState = ps.getPermissionsState();
18489
18490            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18491
18492            // Always clear the user settable flags.
18493            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18494                    bp.name) != null;
18495            // If permission review is enabled and this is a legacy app, mark the
18496            // permission as requiring a review as this is the initial state.
18497            int flags = 0;
18498            if (mPermissionReviewRequired
18499                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18500                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18501            }
18502            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18503                if (hasInstallState) {
18504                    writeInstallPermissions = true;
18505                } else {
18506                    writeRuntimePermissions = true;
18507                }
18508            }
18509
18510            // Below is only runtime permission handling.
18511            if (!bp.isRuntime()) {
18512                continue;
18513            }
18514
18515            // Never clobber system or policy.
18516            if ((oldFlags & policyOrSystemFlags) != 0) {
18517                continue;
18518            }
18519
18520            // If this permission was granted by default, make sure it is.
18521            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18522                if (permissionsState.grantRuntimePermission(bp, userId)
18523                        != PERMISSION_OPERATION_FAILURE) {
18524                    writeRuntimePermissions = true;
18525                }
18526            // If permission review is enabled the permissions for a legacy apps
18527            // are represented as constantly granted runtime ones, so don't revoke.
18528            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18529                // Otherwise, reset the permission.
18530                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18531                switch (revokeResult) {
18532                    case PERMISSION_OPERATION_SUCCESS:
18533                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18534                        writeRuntimePermissions = true;
18535                        final int appId = ps.appId;
18536                        mHandler.post(new Runnable() {
18537                            @Override
18538                            public void run() {
18539                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18540                            }
18541                        });
18542                    } break;
18543                }
18544            }
18545        }
18546
18547        // Synchronously write as we are taking permissions away.
18548        if (writeRuntimePermissions) {
18549            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18550        }
18551
18552        // Synchronously write as we are taking permissions away.
18553        if (writeInstallPermissions) {
18554            mSettings.writeLPr();
18555        }
18556    }
18557
18558    /**
18559     * Remove entries from the keystore daemon. Will only remove it if the
18560     * {@code appId} is valid.
18561     */
18562    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18563        if (appId < 0) {
18564            return;
18565        }
18566
18567        final KeyStore keyStore = KeyStore.getInstance();
18568        if (keyStore != null) {
18569            if (userId == UserHandle.USER_ALL) {
18570                for (final int individual : sUserManager.getUserIds()) {
18571                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18572                }
18573            } else {
18574                keyStore.clearUid(UserHandle.getUid(userId, appId));
18575            }
18576        } else {
18577            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18578        }
18579    }
18580
18581    @Override
18582    public void deleteApplicationCacheFiles(final String packageName,
18583            final IPackageDataObserver observer) {
18584        final int userId = UserHandle.getCallingUserId();
18585        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18586    }
18587
18588    @Override
18589    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18590            final IPackageDataObserver observer) {
18591        mContext.enforceCallingOrSelfPermission(
18592                android.Manifest.permission.DELETE_CACHE_FILES, null);
18593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18594                /* requireFullPermission= */ true, /* checkShell= */ false,
18595                "delete application cache files");
18596
18597        final PackageParser.Package pkg;
18598        synchronized (mPackages) {
18599            pkg = mPackages.get(packageName);
18600        }
18601
18602        // Queue up an async operation since the package deletion may take a little while.
18603        mHandler.post(new Runnable() {
18604            public void run() {
18605                synchronized (mInstallLock) {
18606                    final int flags = StorageManager.FLAG_STORAGE_DE
18607                            | StorageManager.FLAG_STORAGE_CE;
18608                    // We're only clearing cache files, so we don't care if the
18609                    // app is unfrozen and still able to run
18610                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18611                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18612                }
18613                clearExternalStorageDataSync(packageName, userId, false);
18614                if (observer != null) {
18615                    try {
18616                        observer.onRemoveCompleted(packageName, true);
18617                    } catch (RemoteException e) {
18618                        Log.i(TAG, "Observer no longer exists.");
18619                    }
18620                }
18621            }
18622        });
18623    }
18624
18625    @Override
18626    public void getPackageSizeInfo(final String packageName, int userHandle,
18627            final IPackageStatsObserver observer) {
18628        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
18629        try {
18630            observer.onGetStatsCompleted(null, false);
18631        } catch (Throwable ignored) {
18632        }
18633    }
18634
18635    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18636        final PackageSetting ps;
18637        synchronized (mPackages) {
18638            ps = mSettings.mPackages.get(packageName);
18639            if (ps == null) {
18640                Slog.w(TAG, "Failed to find settings for " + packageName);
18641                return false;
18642            }
18643        }
18644
18645        final String[] packageNames = { packageName };
18646        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18647        final String[] codePaths = { ps.codePathString };
18648
18649        try {
18650            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18651                    ps.appId, ceDataInodes, codePaths, stats);
18652
18653            // For now, ignore code size of packages on system partition
18654            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18655                stats.codeSize = 0;
18656            }
18657
18658            // External clients expect these to be tracked separately
18659            stats.dataSize -= stats.cacheSize;
18660
18661        } catch (InstallerException e) {
18662            Slog.w(TAG, String.valueOf(e));
18663            return false;
18664        }
18665
18666        return true;
18667    }
18668
18669    private int getUidTargetSdkVersionLockedLPr(int uid) {
18670        Object obj = mSettings.getUserIdLPr(uid);
18671        if (obj instanceof SharedUserSetting) {
18672            final SharedUserSetting sus = (SharedUserSetting) obj;
18673            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18674            final Iterator<PackageSetting> it = sus.packages.iterator();
18675            while (it.hasNext()) {
18676                final PackageSetting ps = it.next();
18677                if (ps.pkg != null) {
18678                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18679                    if (v < vers) vers = v;
18680                }
18681            }
18682            return vers;
18683        } else if (obj instanceof PackageSetting) {
18684            final PackageSetting ps = (PackageSetting) obj;
18685            if (ps.pkg != null) {
18686                return ps.pkg.applicationInfo.targetSdkVersion;
18687            }
18688        }
18689        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18690    }
18691
18692    @Override
18693    public void addPreferredActivity(IntentFilter filter, int match,
18694            ComponentName[] set, ComponentName activity, int userId) {
18695        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18696                "Adding preferred");
18697    }
18698
18699    private void addPreferredActivityInternal(IntentFilter filter, int match,
18700            ComponentName[] set, ComponentName activity, boolean always, int userId,
18701            String opname) {
18702        // writer
18703        int callingUid = Binder.getCallingUid();
18704        enforceCrossUserPermission(callingUid, userId,
18705                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18706        if (filter.countActions() == 0) {
18707            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18708            return;
18709        }
18710        synchronized (mPackages) {
18711            if (mContext.checkCallingOrSelfPermission(
18712                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18713                    != PackageManager.PERMISSION_GRANTED) {
18714                if (getUidTargetSdkVersionLockedLPr(callingUid)
18715                        < Build.VERSION_CODES.FROYO) {
18716                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18717                            + callingUid);
18718                    return;
18719                }
18720                mContext.enforceCallingOrSelfPermission(
18721                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18722            }
18723
18724            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18725            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18726                    + userId + ":");
18727            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18728            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18729            scheduleWritePackageRestrictionsLocked(userId);
18730            postPreferredActivityChangedBroadcast(userId);
18731        }
18732    }
18733
18734    private void postPreferredActivityChangedBroadcast(int userId) {
18735        mHandler.post(() -> {
18736            final IActivityManager am = ActivityManager.getService();
18737            if (am == null) {
18738                return;
18739            }
18740
18741            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18742            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18743            try {
18744                am.broadcastIntent(null, intent, null, null,
18745                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18746                        null, false, false, userId);
18747            } catch (RemoteException e) {
18748            }
18749        });
18750    }
18751
18752    @Override
18753    public void replacePreferredActivity(IntentFilter filter, int match,
18754            ComponentName[] set, ComponentName activity, int userId) {
18755        if (filter.countActions() != 1) {
18756            throw new IllegalArgumentException(
18757                    "replacePreferredActivity expects filter to have only 1 action.");
18758        }
18759        if (filter.countDataAuthorities() != 0
18760                || filter.countDataPaths() != 0
18761                || filter.countDataSchemes() > 1
18762                || filter.countDataTypes() != 0) {
18763            throw new IllegalArgumentException(
18764                    "replacePreferredActivity expects filter to have no data authorities, " +
18765                    "paths, or types; and at most one scheme.");
18766        }
18767
18768        final int callingUid = Binder.getCallingUid();
18769        enforceCrossUserPermission(callingUid, userId,
18770                true /* requireFullPermission */, false /* checkShell */,
18771                "replace preferred activity");
18772        synchronized (mPackages) {
18773            if (mContext.checkCallingOrSelfPermission(
18774                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18775                    != PackageManager.PERMISSION_GRANTED) {
18776                if (getUidTargetSdkVersionLockedLPr(callingUid)
18777                        < Build.VERSION_CODES.FROYO) {
18778                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18779                            + Binder.getCallingUid());
18780                    return;
18781                }
18782                mContext.enforceCallingOrSelfPermission(
18783                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18784            }
18785
18786            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18787            if (pir != null) {
18788                // Get all of the existing entries that exactly match this filter.
18789                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18790                if (existing != null && existing.size() == 1) {
18791                    PreferredActivity cur = existing.get(0);
18792                    if (DEBUG_PREFERRED) {
18793                        Slog.i(TAG, "Checking replace of preferred:");
18794                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18795                        if (!cur.mPref.mAlways) {
18796                            Slog.i(TAG, "  -- CUR; not mAlways!");
18797                        } else {
18798                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18799                            Slog.i(TAG, "  -- CUR: mSet="
18800                                    + Arrays.toString(cur.mPref.mSetComponents));
18801                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18802                            Slog.i(TAG, "  -- NEW: mMatch="
18803                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18804                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18805                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18806                        }
18807                    }
18808                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18809                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18810                            && cur.mPref.sameSet(set)) {
18811                        // Setting the preferred activity to what it happens to be already
18812                        if (DEBUG_PREFERRED) {
18813                            Slog.i(TAG, "Replacing with same preferred activity "
18814                                    + cur.mPref.mShortComponent + " for user "
18815                                    + userId + ":");
18816                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18817                        }
18818                        return;
18819                    }
18820                }
18821
18822                if (existing != null) {
18823                    if (DEBUG_PREFERRED) {
18824                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18825                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18826                    }
18827                    for (int i = 0; i < existing.size(); i++) {
18828                        PreferredActivity pa = existing.get(i);
18829                        if (DEBUG_PREFERRED) {
18830                            Slog.i(TAG, "Removing existing preferred activity "
18831                                    + pa.mPref.mComponent + ":");
18832                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18833                        }
18834                        pir.removeFilter(pa);
18835                    }
18836                }
18837            }
18838            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18839                    "Replacing preferred");
18840        }
18841    }
18842
18843    @Override
18844    public void clearPackagePreferredActivities(String packageName) {
18845        final int uid = Binder.getCallingUid();
18846        // writer
18847        synchronized (mPackages) {
18848            PackageParser.Package pkg = mPackages.get(packageName);
18849            if (pkg == null || pkg.applicationInfo.uid != uid) {
18850                if (mContext.checkCallingOrSelfPermission(
18851                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18852                        != PackageManager.PERMISSION_GRANTED) {
18853                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18854                            < Build.VERSION_CODES.FROYO) {
18855                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18856                                + Binder.getCallingUid());
18857                        return;
18858                    }
18859                    mContext.enforceCallingOrSelfPermission(
18860                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18861                }
18862            }
18863
18864            int user = UserHandle.getCallingUserId();
18865            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18866                scheduleWritePackageRestrictionsLocked(user);
18867            }
18868        }
18869    }
18870
18871    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18872    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18873        ArrayList<PreferredActivity> removed = null;
18874        boolean changed = false;
18875        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18876            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18877            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18878            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18879                continue;
18880            }
18881            Iterator<PreferredActivity> it = pir.filterIterator();
18882            while (it.hasNext()) {
18883                PreferredActivity pa = it.next();
18884                // Mark entry for removal only if it matches the package name
18885                // and the entry is of type "always".
18886                if (packageName == null ||
18887                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18888                                && pa.mPref.mAlways)) {
18889                    if (removed == null) {
18890                        removed = new ArrayList<PreferredActivity>();
18891                    }
18892                    removed.add(pa);
18893                }
18894            }
18895            if (removed != null) {
18896                for (int j=0; j<removed.size(); j++) {
18897                    PreferredActivity pa = removed.get(j);
18898                    pir.removeFilter(pa);
18899                }
18900                changed = true;
18901            }
18902        }
18903        if (changed) {
18904            postPreferredActivityChangedBroadcast(userId);
18905        }
18906        return changed;
18907    }
18908
18909    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18910    private void clearIntentFilterVerificationsLPw(int userId) {
18911        final int packageCount = mPackages.size();
18912        for (int i = 0; i < packageCount; i++) {
18913            PackageParser.Package pkg = mPackages.valueAt(i);
18914            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18915        }
18916    }
18917
18918    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18919    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18920        if (userId == UserHandle.USER_ALL) {
18921            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18922                    sUserManager.getUserIds())) {
18923                for (int oneUserId : sUserManager.getUserIds()) {
18924                    scheduleWritePackageRestrictionsLocked(oneUserId);
18925                }
18926            }
18927        } else {
18928            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18929                scheduleWritePackageRestrictionsLocked(userId);
18930            }
18931        }
18932    }
18933
18934    void clearDefaultBrowserIfNeeded(String packageName) {
18935        for (int oneUserId : sUserManager.getUserIds()) {
18936            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18937            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18938            if (packageName.equals(defaultBrowserPackageName)) {
18939                setDefaultBrowserPackageName(null, oneUserId);
18940            }
18941        }
18942    }
18943
18944    @Override
18945    public void resetApplicationPreferences(int userId) {
18946        mContext.enforceCallingOrSelfPermission(
18947                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18948        final long identity = Binder.clearCallingIdentity();
18949        // writer
18950        try {
18951            synchronized (mPackages) {
18952                clearPackagePreferredActivitiesLPw(null, userId);
18953                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18954                // TODO: We have to reset the default SMS and Phone. This requires
18955                // significant refactoring to keep all default apps in the package
18956                // manager (cleaner but more work) or have the services provide
18957                // callbacks to the package manager to request a default app reset.
18958                applyFactoryDefaultBrowserLPw(userId);
18959                clearIntentFilterVerificationsLPw(userId);
18960                primeDomainVerificationsLPw(userId);
18961                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18962                scheduleWritePackageRestrictionsLocked(userId);
18963            }
18964            resetNetworkPolicies(userId);
18965        } finally {
18966            Binder.restoreCallingIdentity(identity);
18967        }
18968    }
18969
18970    @Override
18971    public int getPreferredActivities(List<IntentFilter> outFilters,
18972            List<ComponentName> outActivities, String packageName) {
18973
18974        int num = 0;
18975        final int userId = UserHandle.getCallingUserId();
18976        // reader
18977        synchronized (mPackages) {
18978            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18979            if (pir != null) {
18980                final Iterator<PreferredActivity> it = pir.filterIterator();
18981                while (it.hasNext()) {
18982                    final PreferredActivity pa = it.next();
18983                    if (packageName == null
18984                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18985                                    && pa.mPref.mAlways)) {
18986                        if (outFilters != null) {
18987                            outFilters.add(new IntentFilter(pa));
18988                        }
18989                        if (outActivities != null) {
18990                            outActivities.add(pa.mPref.mComponent);
18991                        }
18992                    }
18993                }
18994            }
18995        }
18996
18997        return num;
18998    }
18999
19000    @Override
19001    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19002            int userId) {
19003        int callingUid = Binder.getCallingUid();
19004        if (callingUid != Process.SYSTEM_UID) {
19005            throw new SecurityException(
19006                    "addPersistentPreferredActivity can only be run by the system");
19007        }
19008        if (filter.countActions() == 0) {
19009            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19010            return;
19011        }
19012        synchronized (mPackages) {
19013            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19014                    ":");
19015            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19016            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19017                    new PersistentPreferredActivity(filter, activity));
19018            scheduleWritePackageRestrictionsLocked(userId);
19019            postPreferredActivityChangedBroadcast(userId);
19020        }
19021    }
19022
19023    @Override
19024    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19025        int callingUid = Binder.getCallingUid();
19026        if (callingUid != Process.SYSTEM_UID) {
19027            throw new SecurityException(
19028                    "clearPackagePersistentPreferredActivities can only be run by the system");
19029        }
19030        ArrayList<PersistentPreferredActivity> removed = null;
19031        boolean changed = false;
19032        synchronized (mPackages) {
19033            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19034                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19035                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19036                        .valueAt(i);
19037                if (userId != thisUserId) {
19038                    continue;
19039                }
19040                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19041                while (it.hasNext()) {
19042                    PersistentPreferredActivity ppa = it.next();
19043                    // Mark entry for removal only if it matches the package name.
19044                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19045                        if (removed == null) {
19046                            removed = new ArrayList<PersistentPreferredActivity>();
19047                        }
19048                        removed.add(ppa);
19049                    }
19050                }
19051                if (removed != null) {
19052                    for (int j=0; j<removed.size(); j++) {
19053                        PersistentPreferredActivity ppa = removed.get(j);
19054                        ppir.removeFilter(ppa);
19055                    }
19056                    changed = true;
19057                }
19058            }
19059
19060            if (changed) {
19061                scheduleWritePackageRestrictionsLocked(userId);
19062                postPreferredActivityChangedBroadcast(userId);
19063            }
19064        }
19065    }
19066
19067    /**
19068     * Common machinery for picking apart a restored XML blob and passing
19069     * it to a caller-supplied functor to be applied to the running system.
19070     */
19071    private void restoreFromXml(XmlPullParser parser, int userId,
19072            String expectedStartTag, BlobXmlRestorer functor)
19073            throws IOException, XmlPullParserException {
19074        int type;
19075        while ((type = parser.next()) != XmlPullParser.START_TAG
19076                && type != XmlPullParser.END_DOCUMENT) {
19077        }
19078        if (type != XmlPullParser.START_TAG) {
19079            // oops didn't find a start tag?!
19080            if (DEBUG_BACKUP) {
19081                Slog.e(TAG, "Didn't find start tag during restore");
19082            }
19083            return;
19084        }
19085Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19086        // this is supposed to be TAG_PREFERRED_BACKUP
19087        if (!expectedStartTag.equals(parser.getName())) {
19088            if (DEBUG_BACKUP) {
19089                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19090            }
19091            return;
19092        }
19093
19094        // skip interfering stuff, then we're aligned with the backing implementation
19095        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19096Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19097        functor.apply(parser, userId);
19098    }
19099
19100    private interface BlobXmlRestorer {
19101        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19102    }
19103
19104    /**
19105     * Non-Binder method, support for the backup/restore mechanism: write the
19106     * full set of preferred activities in its canonical XML format.  Returns the
19107     * XML output as a byte array, or null if there is none.
19108     */
19109    @Override
19110    public byte[] getPreferredActivityBackup(int userId) {
19111        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19112            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19113        }
19114
19115        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19116        try {
19117            final XmlSerializer serializer = new FastXmlSerializer();
19118            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19119            serializer.startDocument(null, true);
19120            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19121
19122            synchronized (mPackages) {
19123                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19124            }
19125
19126            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19127            serializer.endDocument();
19128            serializer.flush();
19129        } catch (Exception e) {
19130            if (DEBUG_BACKUP) {
19131                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19132            }
19133            return null;
19134        }
19135
19136        return dataStream.toByteArray();
19137    }
19138
19139    @Override
19140    public void restorePreferredActivities(byte[] backup, int userId) {
19141        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19142            throw new SecurityException("Only the system may call restorePreferredActivities()");
19143        }
19144
19145        try {
19146            final XmlPullParser parser = Xml.newPullParser();
19147            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19148            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19149                    new BlobXmlRestorer() {
19150                        @Override
19151                        public void apply(XmlPullParser parser, int userId)
19152                                throws XmlPullParserException, IOException {
19153                            synchronized (mPackages) {
19154                                mSettings.readPreferredActivitiesLPw(parser, userId);
19155                            }
19156                        }
19157                    } );
19158        } catch (Exception e) {
19159            if (DEBUG_BACKUP) {
19160                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19161            }
19162        }
19163    }
19164
19165    /**
19166     * Non-Binder method, support for the backup/restore mechanism: write the
19167     * default browser (etc) settings in its canonical XML format.  Returns the default
19168     * browser XML representation as a byte array, or null if there is none.
19169     */
19170    @Override
19171    public byte[] getDefaultAppsBackup(int userId) {
19172        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19173            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19174        }
19175
19176        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19177        try {
19178            final XmlSerializer serializer = new FastXmlSerializer();
19179            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19180            serializer.startDocument(null, true);
19181            serializer.startTag(null, TAG_DEFAULT_APPS);
19182
19183            synchronized (mPackages) {
19184                mSettings.writeDefaultAppsLPr(serializer, userId);
19185            }
19186
19187            serializer.endTag(null, TAG_DEFAULT_APPS);
19188            serializer.endDocument();
19189            serializer.flush();
19190        } catch (Exception e) {
19191            if (DEBUG_BACKUP) {
19192                Slog.e(TAG, "Unable to write default apps for backup", e);
19193            }
19194            return null;
19195        }
19196
19197        return dataStream.toByteArray();
19198    }
19199
19200    @Override
19201    public void restoreDefaultApps(byte[] backup, int userId) {
19202        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19203            throw new SecurityException("Only the system may call restoreDefaultApps()");
19204        }
19205
19206        try {
19207            final XmlPullParser parser = Xml.newPullParser();
19208            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19209            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19210                    new BlobXmlRestorer() {
19211                        @Override
19212                        public void apply(XmlPullParser parser, int userId)
19213                                throws XmlPullParserException, IOException {
19214                            synchronized (mPackages) {
19215                                mSettings.readDefaultAppsLPw(parser, userId);
19216                            }
19217                        }
19218                    } );
19219        } catch (Exception e) {
19220            if (DEBUG_BACKUP) {
19221                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19222            }
19223        }
19224    }
19225
19226    @Override
19227    public byte[] getIntentFilterVerificationBackup(int userId) {
19228        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19229            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19230        }
19231
19232        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19233        try {
19234            final XmlSerializer serializer = new FastXmlSerializer();
19235            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19236            serializer.startDocument(null, true);
19237            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19238
19239            synchronized (mPackages) {
19240                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19241            }
19242
19243            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19244            serializer.endDocument();
19245            serializer.flush();
19246        } catch (Exception e) {
19247            if (DEBUG_BACKUP) {
19248                Slog.e(TAG, "Unable to write default apps for backup", e);
19249            }
19250            return null;
19251        }
19252
19253        return dataStream.toByteArray();
19254    }
19255
19256    @Override
19257    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19258        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19259            throw new SecurityException("Only the system may call restorePreferredActivities()");
19260        }
19261
19262        try {
19263            final XmlPullParser parser = Xml.newPullParser();
19264            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19265            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19266                    new BlobXmlRestorer() {
19267                        @Override
19268                        public void apply(XmlPullParser parser, int userId)
19269                                throws XmlPullParserException, IOException {
19270                            synchronized (mPackages) {
19271                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19272                                mSettings.writeLPr();
19273                            }
19274                        }
19275                    } );
19276        } catch (Exception e) {
19277            if (DEBUG_BACKUP) {
19278                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19279            }
19280        }
19281    }
19282
19283    @Override
19284    public byte[] getPermissionGrantBackup(int userId) {
19285        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19286            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19287        }
19288
19289        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19290        try {
19291            final XmlSerializer serializer = new FastXmlSerializer();
19292            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19293            serializer.startDocument(null, true);
19294            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19295
19296            synchronized (mPackages) {
19297                serializeRuntimePermissionGrantsLPr(serializer, userId);
19298            }
19299
19300            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19301            serializer.endDocument();
19302            serializer.flush();
19303        } catch (Exception e) {
19304            if (DEBUG_BACKUP) {
19305                Slog.e(TAG, "Unable to write default apps for backup", e);
19306            }
19307            return null;
19308        }
19309
19310        return dataStream.toByteArray();
19311    }
19312
19313    @Override
19314    public void restorePermissionGrants(byte[] backup, int userId) {
19315        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19316            throw new SecurityException("Only the system may call restorePermissionGrants()");
19317        }
19318
19319        try {
19320            final XmlPullParser parser = Xml.newPullParser();
19321            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19322            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19323                    new BlobXmlRestorer() {
19324                        @Override
19325                        public void apply(XmlPullParser parser, int userId)
19326                                throws XmlPullParserException, IOException {
19327                            synchronized (mPackages) {
19328                                processRestoredPermissionGrantsLPr(parser, userId);
19329                            }
19330                        }
19331                    } );
19332        } catch (Exception e) {
19333            if (DEBUG_BACKUP) {
19334                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19335            }
19336        }
19337    }
19338
19339    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19340            throws IOException {
19341        serializer.startTag(null, TAG_ALL_GRANTS);
19342
19343        final int N = mSettings.mPackages.size();
19344        for (int i = 0; i < N; i++) {
19345            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19346            boolean pkgGrantsKnown = false;
19347
19348            PermissionsState packagePerms = ps.getPermissionsState();
19349
19350            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19351                final int grantFlags = state.getFlags();
19352                // only look at grants that are not system/policy fixed
19353                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19354                    final boolean isGranted = state.isGranted();
19355                    // And only back up the user-twiddled state bits
19356                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19357                        final String packageName = mSettings.mPackages.keyAt(i);
19358                        if (!pkgGrantsKnown) {
19359                            serializer.startTag(null, TAG_GRANT);
19360                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19361                            pkgGrantsKnown = true;
19362                        }
19363
19364                        final boolean userSet =
19365                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19366                        final boolean userFixed =
19367                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19368                        final boolean revoke =
19369                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19370
19371                        serializer.startTag(null, TAG_PERMISSION);
19372                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19373                        if (isGranted) {
19374                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19375                        }
19376                        if (userSet) {
19377                            serializer.attribute(null, ATTR_USER_SET, "true");
19378                        }
19379                        if (userFixed) {
19380                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19381                        }
19382                        if (revoke) {
19383                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19384                        }
19385                        serializer.endTag(null, TAG_PERMISSION);
19386                    }
19387                }
19388            }
19389
19390            if (pkgGrantsKnown) {
19391                serializer.endTag(null, TAG_GRANT);
19392            }
19393        }
19394
19395        serializer.endTag(null, TAG_ALL_GRANTS);
19396    }
19397
19398    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19399            throws XmlPullParserException, IOException {
19400        String pkgName = null;
19401        int outerDepth = parser.getDepth();
19402        int type;
19403        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19404                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19405            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19406                continue;
19407            }
19408
19409            final String tagName = parser.getName();
19410            if (tagName.equals(TAG_GRANT)) {
19411                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19412                if (DEBUG_BACKUP) {
19413                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19414                }
19415            } else if (tagName.equals(TAG_PERMISSION)) {
19416
19417                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19418                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19419
19420                int newFlagSet = 0;
19421                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19422                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19423                }
19424                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19425                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19426                }
19427                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19428                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19429                }
19430                if (DEBUG_BACKUP) {
19431                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19432                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19433                }
19434                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19435                if (ps != null) {
19436                    // Already installed so we apply the grant immediately
19437                    if (DEBUG_BACKUP) {
19438                        Slog.v(TAG, "        + already installed; applying");
19439                    }
19440                    PermissionsState perms = ps.getPermissionsState();
19441                    BasePermission bp = mSettings.mPermissions.get(permName);
19442                    if (bp != null) {
19443                        if (isGranted) {
19444                            perms.grantRuntimePermission(bp, userId);
19445                        }
19446                        if (newFlagSet != 0) {
19447                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19448                        }
19449                    }
19450                } else {
19451                    // Need to wait for post-restore install to apply the grant
19452                    if (DEBUG_BACKUP) {
19453                        Slog.v(TAG, "        - not yet installed; saving for later");
19454                    }
19455                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19456                            isGranted, newFlagSet, userId);
19457                }
19458            } else {
19459                PackageManagerService.reportSettingsProblem(Log.WARN,
19460                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19461                XmlUtils.skipCurrentTag(parser);
19462            }
19463        }
19464
19465        scheduleWriteSettingsLocked();
19466        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19467    }
19468
19469    @Override
19470    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19471            int sourceUserId, int targetUserId, int flags) {
19472        mContext.enforceCallingOrSelfPermission(
19473                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19474        int callingUid = Binder.getCallingUid();
19475        enforceOwnerRights(ownerPackage, callingUid);
19476        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19477        if (intentFilter.countActions() == 0) {
19478            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19479            return;
19480        }
19481        synchronized (mPackages) {
19482            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19483                    ownerPackage, targetUserId, flags);
19484            CrossProfileIntentResolver resolver =
19485                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19486            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19487            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19488            if (existing != null) {
19489                int size = existing.size();
19490                for (int i = 0; i < size; i++) {
19491                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19492                        return;
19493                    }
19494                }
19495            }
19496            resolver.addFilter(newFilter);
19497            scheduleWritePackageRestrictionsLocked(sourceUserId);
19498        }
19499    }
19500
19501    @Override
19502    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19503        mContext.enforceCallingOrSelfPermission(
19504                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19505        int callingUid = Binder.getCallingUid();
19506        enforceOwnerRights(ownerPackage, callingUid);
19507        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19508        synchronized (mPackages) {
19509            CrossProfileIntentResolver resolver =
19510                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19511            ArraySet<CrossProfileIntentFilter> set =
19512                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19513            for (CrossProfileIntentFilter filter : set) {
19514                if (filter.getOwnerPackage().equals(ownerPackage)) {
19515                    resolver.removeFilter(filter);
19516                }
19517            }
19518            scheduleWritePackageRestrictionsLocked(sourceUserId);
19519        }
19520    }
19521
19522    // Enforcing that callingUid is owning pkg on userId
19523    private void enforceOwnerRights(String pkg, int callingUid) {
19524        // The system owns everything.
19525        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19526            return;
19527        }
19528        int callingUserId = UserHandle.getUserId(callingUid);
19529        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19530        if (pi == null) {
19531            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19532                    + callingUserId);
19533        }
19534        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19535            throw new SecurityException("Calling uid " + callingUid
19536                    + " does not own package " + pkg);
19537        }
19538    }
19539
19540    @Override
19541    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19542        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19543    }
19544
19545    /**
19546     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19547     * then reports the most likely home activity or null if there are more than one.
19548     */
19549    public ComponentName getDefaultHomeActivity(int userId) {
19550        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19551        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19552        if (cn != null) {
19553            return cn;
19554        }
19555
19556        // Find the launcher with the highest priority and return that component if there are no
19557        // other home activity with the same priority.
19558        int lastPriority = Integer.MIN_VALUE;
19559        ComponentName lastComponent = null;
19560        final int size = allHomeCandidates.size();
19561        for (int i = 0; i < size; i++) {
19562            final ResolveInfo ri = allHomeCandidates.get(i);
19563            if (ri.priority > lastPriority) {
19564                lastComponent = ri.activityInfo.getComponentName();
19565                lastPriority = ri.priority;
19566            } else if (ri.priority == lastPriority) {
19567                // Two components found with same priority.
19568                lastComponent = null;
19569            }
19570        }
19571        return lastComponent;
19572    }
19573
19574    private Intent getHomeIntent() {
19575        Intent intent = new Intent(Intent.ACTION_MAIN);
19576        intent.addCategory(Intent.CATEGORY_HOME);
19577        intent.addCategory(Intent.CATEGORY_DEFAULT);
19578        return intent;
19579    }
19580
19581    private IntentFilter getHomeFilter() {
19582        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19583        filter.addCategory(Intent.CATEGORY_HOME);
19584        filter.addCategory(Intent.CATEGORY_DEFAULT);
19585        return filter;
19586    }
19587
19588    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19589            int userId) {
19590        Intent intent  = getHomeIntent();
19591        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19592                PackageManager.GET_META_DATA, userId);
19593        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19594                true, false, false, userId);
19595
19596        allHomeCandidates.clear();
19597        if (list != null) {
19598            for (ResolveInfo ri : list) {
19599                allHomeCandidates.add(ri);
19600            }
19601        }
19602        return (preferred == null || preferred.activityInfo == null)
19603                ? null
19604                : new ComponentName(preferred.activityInfo.packageName,
19605                        preferred.activityInfo.name);
19606    }
19607
19608    @Override
19609    public void setHomeActivity(ComponentName comp, int userId) {
19610        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19611        getHomeActivitiesAsUser(homeActivities, userId);
19612
19613        boolean found = false;
19614
19615        final int size = homeActivities.size();
19616        final ComponentName[] set = new ComponentName[size];
19617        for (int i = 0; i < size; i++) {
19618            final ResolveInfo candidate = homeActivities.get(i);
19619            final ActivityInfo info = candidate.activityInfo;
19620            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19621            set[i] = activityName;
19622            if (!found && activityName.equals(comp)) {
19623                found = true;
19624            }
19625        }
19626        if (!found) {
19627            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19628                    + userId);
19629        }
19630        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19631                set, comp, userId);
19632    }
19633
19634    private @Nullable String getSetupWizardPackageName() {
19635        final Intent intent = new Intent(Intent.ACTION_MAIN);
19636        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19637
19638        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19639                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19640                        | MATCH_DISABLED_COMPONENTS,
19641                UserHandle.myUserId());
19642        if (matches.size() == 1) {
19643            return matches.get(0).getComponentInfo().packageName;
19644        } else {
19645            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19646                    + ": matches=" + matches);
19647            return null;
19648        }
19649    }
19650
19651    private @Nullable String getStorageManagerPackageName() {
19652        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19653
19654        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19655                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19656                        | MATCH_DISABLED_COMPONENTS,
19657                UserHandle.myUserId());
19658        if (matches.size() == 1) {
19659            return matches.get(0).getComponentInfo().packageName;
19660        } else {
19661            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19662                    + matches.size() + ": matches=" + matches);
19663            return null;
19664        }
19665    }
19666
19667    @Override
19668    public void setApplicationEnabledSetting(String appPackageName,
19669            int newState, int flags, int userId, String callingPackage) {
19670        if (!sUserManager.exists(userId)) return;
19671        if (callingPackage == null) {
19672            callingPackage = Integer.toString(Binder.getCallingUid());
19673        }
19674        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19675    }
19676
19677    @Override
19678    public void setComponentEnabledSetting(ComponentName componentName,
19679            int newState, int flags, int userId) {
19680        if (!sUserManager.exists(userId)) return;
19681        setEnabledSetting(componentName.getPackageName(),
19682                componentName.getClassName(), newState, flags, userId, null);
19683    }
19684
19685    private void setEnabledSetting(final String packageName, String className, int newState,
19686            final int flags, int userId, String callingPackage) {
19687        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19688              || newState == COMPONENT_ENABLED_STATE_ENABLED
19689              || newState == COMPONENT_ENABLED_STATE_DISABLED
19690              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19691              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19692            throw new IllegalArgumentException("Invalid new component state: "
19693                    + newState);
19694        }
19695        PackageSetting pkgSetting;
19696        final int uid = Binder.getCallingUid();
19697        final int permission;
19698        if (uid == Process.SYSTEM_UID) {
19699            permission = PackageManager.PERMISSION_GRANTED;
19700        } else {
19701            permission = mContext.checkCallingOrSelfPermission(
19702                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19703        }
19704        enforceCrossUserPermission(uid, userId,
19705                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19706        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19707        boolean sendNow = false;
19708        boolean isApp = (className == null);
19709        String componentName = isApp ? packageName : className;
19710        int packageUid = -1;
19711        ArrayList<String> components;
19712
19713        // writer
19714        synchronized (mPackages) {
19715            pkgSetting = mSettings.mPackages.get(packageName);
19716            if (pkgSetting == null) {
19717                if (className == null) {
19718                    throw new IllegalArgumentException("Unknown package: " + packageName);
19719                }
19720                throw new IllegalArgumentException(
19721                        "Unknown component: " + packageName + "/" + className);
19722            }
19723        }
19724
19725        // Limit who can change which apps
19726        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19727            // Don't allow apps that don't have permission to modify other apps
19728            if (!allowedByPermission) {
19729                throw new SecurityException(
19730                        "Permission Denial: attempt to change component state from pid="
19731                        + Binder.getCallingPid()
19732                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19733            }
19734            // Don't allow changing protected packages.
19735            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19736                throw new SecurityException("Cannot disable a protected package: " + packageName);
19737            }
19738        }
19739
19740        synchronized (mPackages) {
19741            if (uid == Process.SHELL_UID
19742                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19743                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19744                // unless it is a test package.
19745                int oldState = pkgSetting.getEnabled(userId);
19746                if (className == null
19747                    &&
19748                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19749                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19750                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19751                    &&
19752                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19753                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19754                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19755                    // ok
19756                } else {
19757                    throw new SecurityException(
19758                            "Shell cannot change component state for " + packageName + "/"
19759                            + className + " to " + newState);
19760                }
19761            }
19762            if (className == null) {
19763                // We're dealing with an application/package level state change
19764                if (pkgSetting.getEnabled(userId) == newState) {
19765                    // Nothing to do
19766                    return;
19767                }
19768                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19769                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19770                    // Don't care about who enables an app.
19771                    callingPackage = null;
19772                }
19773                pkgSetting.setEnabled(newState, userId, callingPackage);
19774                // pkgSetting.pkg.mSetEnabled = newState;
19775            } else {
19776                // We're dealing with a component level state change
19777                // First, verify that this is a valid class name.
19778                PackageParser.Package pkg = pkgSetting.pkg;
19779                if (pkg == null || !pkg.hasComponentClassName(className)) {
19780                    if (pkg != null &&
19781                            pkg.applicationInfo.targetSdkVersion >=
19782                                    Build.VERSION_CODES.JELLY_BEAN) {
19783                        throw new IllegalArgumentException("Component class " + className
19784                                + " does not exist in " + packageName);
19785                    } else {
19786                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19787                                + className + " does not exist in " + packageName);
19788                    }
19789                }
19790                switch (newState) {
19791                case COMPONENT_ENABLED_STATE_ENABLED:
19792                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19793                        return;
19794                    }
19795                    break;
19796                case COMPONENT_ENABLED_STATE_DISABLED:
19797                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19798                        return;
19799                    }
19800                    break;
19801                case COMPONENT_ENABLED_STATE_DEFAULT:
19802                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19803                        return;
19804                    }
19805                    break;
19806                default:
19807                    Slog.e(TAG, "Invalid new component state: " + newState);
19808                    return;
19809                }
19810            }
19811            scheduleWritePackageRestrictionsLocked(userId);
19812            updateSequenceNumberLP(packageName, new int[] { userId });
19813            components = mPendingBroadcasts.get(userId, packageName);
19814            final boolean newPackage = components == null;
19815            if (newPackage) {
19816                components = new ArrayList<String>();
19817            }
19818            if (!components.contains(componentName)) {
19819                components.add(componentName);
19820            }
19821            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19822                sendNow = true;
19823                // Purge entry from pending broadcast list if another one exists already
19824                // since we are sending one right away.
19825                mPendingBroadcasts.remove(userId, packageName);
19826            } else {
19827                if (newPackage) {
19828                    mPendingBroadcasts.put(userId, packageName, components);
19829                }
19830                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19831                    // Schedule a message
19832                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19833                }
19834            }
19835        }
19836
19837        long callingId = Binder.clearCallingIdentity();
19838        try {
19839            if (sendNow) {
19840                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19841                sendPackageChangedBroadcast(packageName,
19842                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19843            }
19844        } finally {
19845            Binder.restoreCallingIdentity(callingId);
19846        }
19847    }
19848
19849    @Override
19850    public void flushPackageRestrictionsAsUser(int userId) {
19851        if (!sUserManager.exists(userId)) {
19852            return;
19853        }
19854        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19855                false /* checkShell */, "flushPackageRestrictions");
19856        synchronized (mPackages) {
19857            mSettings.writePackageRestrictionsLPr(userId);
19858            mDirtyUsers.remove(userId);
19859            if (mDirtyUsers.isEmpty()) {
19860                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19861            }
19862        }
19863    }
19864
19865    private void sendPackageChangedBroadcast(String packageName,
19866            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19867        if (DEBUG_INSTALL)
19868            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19869                    + componentNames);
19870        Bundle extras = new Bundle(4);
19871        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19872        String nameList[] = new String[componentNames.size()];
19873        componentNames.toArray(nameList);
19874        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19875        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19876        extras.putInt(Intent.EXTRA_UID, packageUid);
19877        // If this is not reporting a change of the overall package, then only send it
19878        // to registered receivers.  We don't want to launch a swath of apps for every
19879        // little component state change.
19880        final int flags = !componentNames.contains(packageName)
19881                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19882        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19883                new int[] {UserHandle.getUserId(packageUid)});
19884    }
19885
19886    @Override
19887    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19888        if (!sUserManager.exists(userId)) return;
19889        final int uid = Binder.getCallingUid();
19890        final int permission = mContext.checkCallingOrSelfPermission(
19891                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19892        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19893        enforceCrossUserPermission(uid, userId,
19894                true /* requireFullPermission */, true /* checkShell */, "stop package");
19895        // writer
19896        synchronized (mPackages) {
19897            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19898                    allowedByPermission, uid, userId)) {
19899                scheduleWritePackageRestrictionsLocked(userId);
19900            }
19901        }
19902    }
19903
19904    @Override
19905    public String getInstallerPackageName(String packageName) {
19906        // reader
19907        synchronized (mPackages) {
19908            return mSettings.getInstallerPackageNameLPr(packageName);
19909        }
19910    }
19911
19912    public boolean isOrphaned(String packageName) {
19913        // reader
19914        synchronized (mPackages) {
19915            return mSettings.isOrphaned(packageName);
19916        }
19917    }
19918
19919    @Override
19920    public int getApplicationEnabledSetting(String packageName, int userId) {
19921        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19922        int uid = Binder.getCallingUid();
19923        enforceCrossUserPermission(uid, userId,
19924                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19925        // reader
19926        synchronized (mPackages) {
19927            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19928        }
19929    }
19930
19931    @Override
19932    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19933        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19934        int uid = Binder.getCallingUid();
19935        enforceCrossUserPermission(uid, userId,
19936                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19937        // reader
19938        synchronized (mPackages) {
19939            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19940        }
19941    }
19942
19943    @Override
19944    public void enterSafeMode() {
19945        enforceSystemOrRoot("Only the system can request entering safe mode");
19946
19947        if (!mSystemReady) {
19948            mSafeMode = true;
19949        }
19950    }
19951
19952    @Override
19953    public void systemReady() {
19954        mSystemReady = true;
19955
19956        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19957        // disabled after already being started.
19958        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19959                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19960
19961        // Read the compatibilty setting when the system is ready.
19962        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19963                mContext.getContentResolver(),
19964                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19965        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19966        if (DEBUG_SETTINGS) {
19967            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19968        }
19969
19970        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19971
19972        synchronized (mPackages) {
19973            // Verify that all of the preferred activity components actually
19974            // exist.  It is possible for applications to be updated and at
19975            // that point remove a previously declared activity component that
19976            // had been set as a preferred activity.  We try to clean this up
19977            // the next time we encounter that preferred activity, but it is
19978            // possible for the user flow to never be able to return to that
19979            // situation so here we do a sanity check to make sure we haven't
19980            // left any junk around.
19981            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19982            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19983                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19984                removed.clear();
19985                for (PreferredActivity pa : pir.filterSet()) {
19986                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19987                        removed.add(pa);
19988                    }
19989                }
19990                if (removed.size() > 0) {
19991                    for (int r=0; r<removed.size(); r++) {
19992                        PreferredActivity pa = removed.get(r);
19993                        Slog.w(TAG, "Removing dangling preferred activity: "
19994                                + pa.mPref.mComponent);
19995                        pir.removeFilter(pa);
19996                    }
19997                    mSettings.writePackageRestrictionsLPr(
19998                            mSettings.mPreferredActivities.keyAt(i));
19999                }
20000            }
20001
20002            for (int userId : UserManagerService.getInstance().getUserIds()) {
20003                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20004                    grantPermissionsUserIds = ArrayUtils.appendInt(
20005                            grantPermissionsUserIds, userId);
20006                }
20007            }
20008        }
20009        sUserManager.systemReady();
20010
20011        // If we upgraded grant all default permissions before kicking off.
20012        for (int userId : grantPermissionsUserIds) {
20013            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20014        }
20015
20016        // If we did not grant default permissions, we preload from this the
20017        // default permission exceptions lazily to ensure we don't hit the
20018        // disk on a new user creation.
20019        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20020            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20021        }
20022
20023        // Kick off any messages waiting for system ready
20024        if (mPostSystemReadyMessages != null) {
20025            for (Message msg : mPostSystemReadyMessages) {
20026                msg.sendToTarget();
20027            }
20028            mPostSystemReadyMessages = null;
20029        }
20030
20031        // Watch for external volumes that come and go over time
20032        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20033        storage.registerListener(mStorageListener);
20034
20035        mInstallerService.systemReady();
20036        mPackageDexOptimizer.systemReady();
20037
20038        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20039                StorageManagerInternal.class);
20040        StorageManagerInternal.addExternalStoragePolicy(
20041                new StorageManagerInternal.ExternalStorageMountPolicy() {
20042            @Override
20043            public int getMountMode(int uid, String packageName) {
20044                if (Process.isIsolated(uid)) {
20045                    return Zygote.MOUNT_EXTERNAL_NONE;
20046                }
20047                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20048                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20049                }
20050                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20051                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20052                }
20053                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20054                    return Zygote.MOUNT_EXTERNAL_READ;
20055                }
20056                return Zygote.MOUNT_EXTERNAL_WRITE;
20057            }
20058
20059            @Override
20060            public boolean hasExternalStorage(int uid, String packageName) {
20061                return true;
20062            }
20063        });
20064
20065        // Now that we're mostly running, clean up stale users and apps
20066        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20067        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20068
20069        if (mPrivappPermissionsViolations != null) {
20070            Slog.wtf(TAG,"Signature|privileged permissions not in "
20071                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20072            mPrivappPermissionsViolations = null;
20073        }
20074    }
20075
20076    public void waitForAppDataPrepared() {
20077        if (mPrepareAppDataFuture == null) {
20078            return;
20079        }
20080        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20081        mPrepareAppDataFuture = null;
20082    }
20083
20084    @Override
20085    public boolean isSafeMode() {
20086        return mSafeMode;
20087    }
20088
20089    @Override
20090    public boolean hasSystemUidErrors() {
20091        return mHasSystemUidErrors;
20092    }
20093
20094    static String arrayToString(int[] array) {
20095        StringBuffer buf = new StringBuffer(128);
20096        buf.append('[');
20097        if (array != null) {
20098            for (int i=0; i<array.length; i++) {
20099                if (i > 0) buf.append(", ");
20100                buf.append(array[i]);
20101            }
20102        }
20103        buf.append(']');
20104        return buf.toString();
20105    }
20106
20107    static class DumpState {
20108        public static final int DUMP_LIBS = 1 << 0;
20109        public static final int DUMP_FEATURES = 1 << 1;
20110        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20111        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20112        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20113        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20114        public static final int DUMP_PERMISSIONS = 1 << 6;
20115        public static final int DUMP_PACKAGES = 1 << 7;
20116        public static final int DUMP_SHARED_USERS = 1 << 8;
20117        public static final int DUMP_MESSAGES = 1 << 9;
20118        public static final int DUMP_PROVIDERS = 1 << 10;
20119        public static final int DUMP_VERIFIERS = 1 << 11;
20120        public static final int DUMP_PREFERRED = 1 << 12;
20121        public static final int DUMP_PREFERRED_XML = 1 << 13;
20122        public static final int DUMP_KEYSETS = 1 << 14;
20123        public static final int DUMP_VERSION = 1 << 15;
20124        public static final int DUMP_INSTALLS = 1 << 16;
20125        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20126        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20127        public static final int DUMP_FROZEN = 1 << 19;
20128        public static final int DUMP_DEXOPT = 1 << 20;
20129        public static final int DUMP_COMPILER_STATS = 1 << 21;
20130        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20131
20132        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20133
20134        private int mTypes;
20135
20136        private int mOptions;
20137
20138        private boolean mTitlePrinted;
20139
20140        private SharedUserSetting mSharedUser;
20141
20142        public boolean isDumping(int type) {
20143            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20144                return true;
20145            }
20146
20147            return (mTypes & type) != 0;
20148        }
20149
20150        public void setDump(int type) {
20151            mTypes |= type;
20152        }
20153
20154        public boolean isOptionEnabled(int option) {
20155            return (mOptions & option) != 0;
20156        }
20157
20158        public void setOptionEnabled(int option) {
20159            mOptions |= option;
20160        }
20161
20162        public boolean onTitlePrinted() {
20163            final boolean printed = mTitlePrinted;
20164            mTitlePrinted = true;
20165            return printed;
20166        }
20167
20168        public boolean getTitlePrinted() {
20169            return mTitlePrinted;
20170        }
20171
20172        public void setTitlePrinted(boolean enabled) {
20173            mTitlePrinted = enabled;
20174        }
20175
20176        public SharedUserSetting getSharedUser() {
20177            return mSharedUser;
20178        }
20179
20180        public void setSharedUser(SharedUserSetting user) {
20181            mSharedUser = user;
20182        }
20183    }
20184
20185    @Override
20186    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20187            FileDescriptor err, String[] args, ShellCallback callback,
20188            ResultReceiver resultReceiver) {
20189        (new PackageManagerShellCommand(this)).exec(
20190                this, in, out, err, args, callback, resultReceiver);
20191    }
20192
20193    @Override
20194    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20195        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20196                != PackageManager.PERMISSION_GRANTED) {
20197            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20198                    + Binder.getCallingPid()
20199                    + ", uid=" + Binder.getCallingUid()
20200                    + " without permission "
20201                    + android.Manifest.permission.DUMP);
20202            return;
20203        }
20204
20205        DumpState dumpState = new DumpState();
20206        boolean fullPreferred = false;
20207        boolean checkin = false;
20208
20209        String packageName = null;
20210        ArraySet<String> permissionNames = null;
20211
20212        int opti = 0;
20213        while (opti < args.length) {
20214            String opt = args[opti];
20215            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20216                break;
20217            }
20218            opti++;
20219
20220            if ("-a".equals(opt)) {
20221                // Right now we only know how to print all.
20222            } else if ("-h".equals(opt)) {
20223                pw.println("Package manager dump options:");
20224                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20225                pw.println("    --checkin: dump for a checkin");
20226                pw.println("    -f: print details of intent filters");
20227                pw.println("    -h: print this help");
20228                pw.println("  cmd may be one of:");
20229                pw.println("    l[ibraries]: list known shared libraries");
20230                pw.println("    f[eatures]: list device features");
20231                pw.println("    k[eysets]: print known keysets");
20232                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20233                pw.println("    perm[issions]: dump permissions");
20234                pw.println("    permission [name ...]: dump declaration and use of given permission");
20235                pw.println("    pref[erred]: print preferred package settings");
20236                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20237                pw.println("    prov[iders]: dump content providers");
20238                pw.println("    p[ackages]: dump installed packages");
20239                pw.println("    s[hared-users]: dump shared user IDs");
20240                pw.println("    m[essages]: print collected runtime messages");
20241                pw.println("    v[erifiers]: print package verifier info");
20242                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20243                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20244                pw.println("    version: print database version info");
20245                pw.println("    write: write current settings now");
20246                pw.println("    installs: details about install sessions");
20247                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20248                pw.println("    dexopt: dump dexopt state");
20249                pw.println("    compiler-stats: dump compiler statistics");
20250                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20251                pw.println("    <package.name>: info about given package");
20252                return;
20253            } else if ("--checkin".equals(opt)) {
20254                checkin = true;
20255            } else if ("-f".equals(opt)) {
20256                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20257            } else if ("--proto".equals(opt)) {
20258                dumpProto(fd);
20259                return;
20260            } else {
20261                pw.println("Unknown argument: " + opt + "; use -h for help");
20262            }
20263        }
20264
20265        // Is the caller requesting to dump a particular piece of data?
20266        if (opti < args.length) {
20267            String cmd = args[opti];
20268            opti++;
20269            // Is this a package name?
20270            if ("android".equals(cmd) || cmd.contains(".")) {
20271                packageName = cmd;
20272                // When dumping a single package, we always dump all of its
20273                // filter information since the amount of data will be reasonable.
20274                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20275            } else if ("check-permission".equals(cmd)) {
20276                if (opti >= args.length) {
20277                    pw.println("Error: check-permission missing permission argument");
20278                    return;
20279                }
20280                String perm = args[opti];
20281                opti++;
20282                if (opti >= args.length) {
20283                    pw.println("Error: check-permission missing package argument");
20284                    return;
20285                }
20286
20287                String pkg = args[opti];
20288                opti++;
20289                int user = UserHandle.getUserId(Binder.getCallingUid());
20290                if (opti < args.length) {
20291                    try {
20292                        user = Integer.parseInt(args[opti]);
20293                    } catch (NumberFormatException e) {
20294                        pw.println("Error: check-permission user argument is not a number: "
20295                                + args[opti]);
20296                        return;
20297                    }
20298                }
20299
20300                // Normalize package name to handle renamed packages and static libs
20301                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20302
20303                pw.println(checkPermission(perm, pkg, user));
20304                return;
20305            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20306                dumpState.setDump(DumpState.DUMP_LIBS);
20307            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20308                dumpState.setDump(DumpState.DUMP_FEATURES);
20309            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20310                if (opti >= args.length) {
20311                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20312                            | DumpState.DUMP_SERVICE_RESOLVERS
20313                            | DumpState.DUMP_RECEIVER_RESOLVERS
20314                            | DumpState.DUMP_CONTENT_RESOLVERS);
20315                } else {
20316                    while (opti < args.length) {
20317                        String name = args[opti];
20318                        if ("a".equals(name) || "activity".equals(name)) {
20319                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20320                        } else if ("s".equals(name) || "service".equals(name)) {
20321                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20322                        } else if ("r".equals(name) || "receiver".equals(name)) {
20323                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20324                        } else if ("c".equals(name) || "content".equals(name)) {
20325                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20326                        } else {
20327                            pw.println("Error: unknown resolver table type: " + name);
20328                            return;
20329                        }
20330                        opti++;
20331                    }
20332                }
20333            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20334                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20335            } else if ("permission".equals(cmd)) {
20336                if (opti >= args.length) {
20337                    pw.println("Error: permission requires permission name");
20338                    return;
20339                }
20340                permissionNames = new ArraySet<>();
20341                while (opti < args.length) {
20342                    permissionNames.add(args[opti]);
20343                    opti++;
20344                }
20345                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20346                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20347            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_PREFERRED);
20349            } else if ("preferred-xml".equals(cmd)) {
20350                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20351                if (opti < args.length && "--full".equals(args[opti])) {
20352                    fullPreferred = true;
20353                    opti++;
20354                }
20355            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20356                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20357            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20358                dumpState.setDump(DumpState.DUMP_PACKAGES);
20359            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20360                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20361            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20362                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20363            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20364                dumpState.setDump(DumpState.DUMP_MESSAGES);
20365            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20366                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20367            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20368                    || "intent-filter-verifiers".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20370            } else if ("version".equals(cmd)) {
20371                dumpState.setDump(DumpState.DUMP_VERSION);
20372            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20373                dumpState.setDump(DumpState.DUMP_KEYSETS);
20374            } else if ("installs".equals(cmd)) {
20375                dumpState.setDump(DumpState.DUMP_INSTALLS);
20376            } else if ("frozen".equals(cmd)) {
20377                dumpState.setDump(DumpState.DUMP_FROZEN);
20378            } else if ("dexopt".equals(cmd)) {
20379                dumpState.setDump(DumpState.DUMP_DEXOPT);
20380            } else if ("compiler-stats".equals(cmd)) {
20381                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20382            } else if ("enabled-overlays".equals(cmd)) {
20383                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20384            } else if ("write".equals(cmd)) {
20385                synchronized (mPackages) {
20386                    mSettings.writeLPr();
20387                    pw.println("Settings written.");
20388                    return;
20389                }
20390            }
20391        }
20392
20393        if (checkin) {
20394            pw.println("vers,1");
20395        }
20396
20397        // reader
20398        synchronized (mPackages) {
20399            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20400                if (!checkin) {
20401                    if (dumpState.onTitlePrinted())
20402                        pw.println();
20403                    pw.println("Database versions:");
20404                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20405                }
20406            }
20407
20408            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20409                if (!checkin) {
20410                    if (dumpState.onTitlePrinted())
20411                        pw.println();
20412                    pw.println("Verifiers:");
20413                    pw.print("  Required: ");
20414                    pw.print(mRequiredVerifierPackage);
20415                    pw.print(" (uid=");
20416                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20417                            UserHandle.USER_SYSTEM));
20418                    pw.println(")");
20419                } else if (mRequiredVerifierPackage != null) {
20420                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20421                    pw.print(",");
20422                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20423                            UserHandle.USER_SYSTEM));
20424                }
20425            }
20426
20427            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20428                    packageName == null) {
20429                if (mIntentFilterVerifierComponent != null) {
20430                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20431                    if (!checkin) {
20432                        if (dumpState.onTitlePrinted())
20433                            pw.println();
20434                        pw.println("Intent Filter Verifier:");
20435                        pw.print("  Using: ");
20436                        pw.print(verifierPackageName);
20437                        pw.print(" (uid=");
20438                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20439                                UserHandle.USER_SYSTEM));
20440                        pw.println(")");
20441                    } else if (verifierPackageName != null) {
20442                        pw.print("ifv,"); pw.print(verifierPackageName);
20443                        pw.print(",");
20444                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20445                                UserHandle.USER_SYSTEM));
20446                    }
20447                } else {
20448                    pw.println();
20449                    pw.println("No Intent Filter Verifier available!");
20450                }
20451            }
20452
20453            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20454                boolean printedHeader = false;
20455                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20456                while (it.hasNext()) {
20457                    String libName = it.next();
20458                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20459                    if (versionedLib == null) {
20460                        continue;
20461                    }
20462                    final int versionCount = versionedLib.size();
20463                    for (int i = 0; i < versionCount; i++) {
20464                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20465                        if (!checkin) {
20466                            if (!printedHeader) {
20467                                if (dumpState.onTitlePrinted())
20468                                    pw.println();
20469                                pw.println("Libraries:");
20470                                printedHeader = true;
20471                            }
20472                            pw.print("  ");
20473                        } else {
20474                            pw.print("lib,");
20475                        }
20476                        pw.print(libEntry.info.getName());
20477                        if (libEntry.info.isStatic()) {
20478                            pw.print(" version=" + libEntry.info.getVersion());
20479                        }
20480                        if (!checkin) {
20481                            pw.print(" -> ");
20482                        }
20483                        if (libEntry.path != null) {
20484                            pw.print(" (jar) ");
20485                            pw.print(libEntry.path);
20486                        } else {
20487                            pw.print(" (apk) ");
20488                            pw.print(libEntry.apk);
20489                        }
20490                        pw.println();
20491                    }
20492                }
20493            }
20494
20495            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20496                if (dumpState.onTitlePrinted())
20497                    pw.println();
20498                if (!checkin) {
20499                    pw.println("Features:");
20500                }
20501
20502                synchronized (mAvailableFeatures) {
20503                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20504                        if (checkin) {
20505                            pw.print("feat,");
20506                            pw.print(feat.name);
20507                            pw.print(",");
20508                            pw.println(feat.version);
20509                        } else {
20510                            pw.print("  ");
20511                            pw.print(feat.name);
20512                            if (feat.version > 0) {
20513                                pw.print(" version=");
20514                                pw.print(feat.version);
20515                            }
20516                            pw.println();
20517                        }
20518                    }
20519                }
20520            }
20521
20522            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20523                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20524                        : "Activity Resolver Table:", "  ", packageName,
20525                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20526                    dumpState.setTitlePrinted(true);
20527                }
20528            }
20529            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20530                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20531                        : "Receiver Resolver Table:", "  ", packageName,
20532                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20533                    dumpState.setTitlePrinted(true);
20534                }
20535            }
20536            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20537                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20538                        : "Service Resolver Table:", "  ", packageName,
20539                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20540                    dumpState.setTitlePrinted(true);
20541                }
20542            }
20543            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20544                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20545                        : "Provider Resolver Table:", "  ", packageName,
20546                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20547                    dumpState.setTitlePrinted(true);
20548                }
20549            }
20550
20551            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20552                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20553                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20554                    int user = mSettings.mPreferredActivities.keyAt(i);
20555                    if (pir.dump(pw,
20556                            dumpState.getTitlePrinted()
20557                                ? "\nPreferred Activities User " + user + ":"
20558                                : "Preferred Activities User " + user + ":", "  ",
20559                            packageName, true, false)) {
20560                        dumpState.setTitlePrinted(true);
20561                    }
20562                }
20563            }
20564
20565            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20566                pw.flush();
20567                FileOutputStream fout = new FileOutputStream(fd);
20568                BufferedOutputStream str = new BufferedOutputStream(fout);
20569                XmlSerializer serializer = new FastXmlSerializer();
20570                try {
20571                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20572                    serializer.startDocument(null, true);
20573                    serializer.setFeature(
20574                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20575                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20576                    serializer.endDocument();
20577                    serializer.flush();
20578                } catch (IllegalArgumentException e) {
20579                    pw.println("Failed writing: " + e);
20580                } catch (IllegalStateException e) {
20581                    pw.println("Failed writing: " + e);
20582                } catch (IOException e) {
20583                    pw.println("Failed writing: " + e);
20584                }
20585            }
20586
20587            if (!checkin
20588                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20589                    && packageName == null) {
20590                pw.println();
20591                int count = mSettings.mPackages.size();
20592                if (count == 0) {
20593                    pw.println("No applications!");
20594                    pw.println();
20595                } else {
20596                    final String prefix = "  ";
20597                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20598                    if (allPackageSettings.size() == 0) {
20599                        pw.println("No domain preferred apps!");
20600                        pw.println();
20601                    } else {
20602                        pw.println("App verification status:");
20603                        pw.println();
20604                        count = 0;
20605                        for (PackageSetting ps : allPackageSettings) {
20606                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20607                            if (ivi == null || ivi.getPackageName() == null) continue;
20608                            pw.println(prefix + "Package: " + ivi.getPackageName());
20609                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20610                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20611                            pw.println();
20612                            count++;
20613                        }
20614                        if (count == 0) {
20615                            pw.println(prefix + "No app verification established.");
20616                            pw.println();
20617                        }
20618                        for (int userId : sUserManager.getUserIds()) {
20619                            pw.println("App linkages for user " + userId + ":");
20620                            pw.println();
20621                            count = 0;
20622                            for (PackageSetting ps : allPackageSettings) {
20623                                final long status = ps.getDomainVerificationStatusForUser(userId);
20624                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20625                                        && !DEBUG_DOMAIN_VERIFICATION) {
20626                                    continue;
20627                                }
20628                                pw.println(prefix + "Package: " + ps.name);
20629                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20630                                String statusStr = IntentFilterVerificationInfo.
20631                                        getStatusStringFromValue(status);
20632                                pw.println(prefix + "Status:  " + statusStr);
20633                                pw.println();
20634                                count++;
20635                            }
20636                            if (count == 0) {
20637                                pw.println(prefix + "No configured app linkages.");
20638                                pw.println();
20639                            }
20640                        }
20641                    }
20642                }
20643            }
20644
20645            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20646                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20647                if (packageName == null && permissionNames == null) {
20648                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20649                        if (iperm == 0) {
20650                            if (dumpState.onTitlePrinted())
20651                                pw.println();
20652                            pw.println("AppOp Permissions:");
20653                        }
20654                        pw.print("  AppOp Permission ");
20655                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20656                        pw.println(":");
20657                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20658                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20659                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20660                        }
20661                    }
20662                }
20663            }
20664
20665            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20666                boolean printedSomething = false;
20667                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20668                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20669                        continue;
20670                    }
20671                    if (!printedSomething) {
20672                        if (dumpState.onTitlePrinted())
20673                            pw.println();
20674                        pw.println("Registered ContentProviders:");
20675                        printedSomething = true;
20676                    }
20677                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20678                    pw.print("    "); pw.println(p.toString());
20679                }
20680                printedSomething = false;
20681                for (Map.Entry<String, PackageParser.Provider> entry :
20682                        mProvidersByAuthority.entrySet()) {
20683                    PackageParser.Provider p = entry.getValue();
20684                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20685                        continue;
20686                    }
20687                    if (!printedSomething) {
20688                        if (dumpState.onTitlePrinted())
20689                            pw.println();
20690                        pw.println("ContentProvider Authorities:");
20691                        printedSomething = true;
20692                    }
20693                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20694                    pw.print("    "); pw.println(p.toString());
20695                    if (p.info != null && p.info.applicationInfo != null) {
20696                        final String appInfo = p.info.applicationInfo.toString();
20697                        pw.print("      applicationInfo="); pw.println(appInfo);
20698                    }
20699                }
20700            }
20701
20702            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20703                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20704            }
20705
20706            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20707                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20708            }
20709
20710            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20711                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20712            }
20713
20714            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20715                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20716            }
20717
20718            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20719                // XXX should handle packageName != null by dumping only install data that
20720                // the given package is involved with.
20721                if (dumpState.onTitlePrinted()) pw.println();
20722                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20723            }
20724
20725            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20726                // XXX should handle packageName != null by dumping only install data that
20727                // the given package is involved with.
20728                if (dumpState.onTitlePrinted()) pw.println();
20729
20730                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20731                ipw.println();
20732                ipw.println("Frozen packages:");
20733                ipw.increaseIndent();
20734                if (mFrozenPackages.size() == 0) {
20735                    ipw.println("(none)");
20736                } else {
20737                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20738                        ipw.println(mFrozenPackages.valueAt(i));
20739                    }
20740                }
20741                ipw.decreaseIndent();
20742            }
20743
20744            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20745                if (dumpState.onTitlePrinted()) pw.println();
20746                dumpDexoptStateLPr(pw, packageName);
20747            }
20748
20749            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20750                if (dumpState.onTitlePrinted()) pw.println();
20751                dumpCompilerStatsLPr(pw, packageName);
20752            }
20753
20754            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20755                if (dumpState.onTitlePrinted()) pw.println();
20756                dumpEnabledOverlaysLPr(pw);
20757            }
20758
20759            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20760                if (dumpState.onTitlePrinted()) pw.println();
20761                mSettings.dumpReadMessagesLPr(pw, dumpState);
20762
20763                pw.println();
20764                pw.println("Package warning messages:");
20765                BufferedReader in = null;
20766                String line = null;
20767                try {
20768                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20769                    while ((line = in.readLine()) != null) {
20770                        if (line.contains("ignored: updated version")) continue;
20771                        pw.println(line);
20772                    }
20773                } catch (IOException ignored) {
20774                } finally {
20775                    IoUtils.closeQuietly(in);
20776                }
20777            }
20778
20779            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20780                BufferedReader in = null;
20781                String line = null;
20782                try {
20783                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20784                    while ((line = in.readLine()) != null) {
20785                        if (line.contains("ignored: updated version")) continue;
20786                        pw.print("msg,");
20787                        pw.println(line);
20788                    }
20789                } catch (IOException ignored) {
20790                } finally {
20791                    IoUtils.closeQuietly(in);
20792                }
20793            }
20794        }
20795    }
20796
20797    private void dumpProto(FileDescriptor fd) {
20798        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20799
20800        synchronized (mPackages) {
20801            final long requiredVerifierPackageToken =
20802                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20803            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20804            proto.write(
20805                    PackageServiceDumpProto.PackageShortProto.UID,
20806                    getPackageUid(
20807                            mRequiredVerifierPackage,
20808                            MATCH_DEBUG_TRIAGED_MISSING,
20809                            UserHandle.USER_SYSTEM));
20810            proto.end(requiredVerifierPackageToken);
20811
20812            if (mIntentFilterVerifierComponent != null) {
20813                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20814                final long verifierPackageToken =
20815                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20816                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20817                proto.write(
20818                        PackageServiceDumpProto.PackageShortProto.UID,
20819                        getPackageUid(
20820                                verifierPackageName,
20821                                MATCH_DEBUG_TRIAGED_MISSING,
20822                                UserHandle.USER_SYSTEM));
20823                proto.end(verifierPackageToken);
20824            }
20825
20826            dumpSharedLibrariesProto(proto);
20827            dumpFeaturesProto(proto);
20828            mSettings.dumpPackagesProto(proto);
20829            mSettings.dumpSharedUsersProto(proto);
20830            dumpMessagesProto(proto);
20831        }
20832        proto.flush();
20833    }
20834
20835    private void dumpMessagesProto(ProtoOutputStream proto) {
20836        BufferedReader in = null;
20837        String line = null;
20838        try {
20839            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20840            while ((line = in.readLine()) != null) {
20841                if (line.contains("ignored: updated version")) continue;
20842                proto.write(PackageServiceDumpProto.MESSAGES, line);
20843            }
20844        } catch (IOException ignored) {
20845        } finally {
20846            IoUtils.closeQuietly(in);
20847        }
20848    }
20849
20850    private void dumpFeaturesProto(ProtoOutputStream proto) {
20851        synchronized (mAvailableFeatures) {
20852            final int count = mAvailableFeatures.size();
20853            for (int i = 0; i < count; i++) {
20854                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20855                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20856                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20857                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20858                proto.end(featureToken);
20859            }
20860        }
20861    }
20862
20863    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20864        final int count = mSharedLibraries.size();
20865        for (int i = 0; i < count; i++) {
20866            final String libName = mSharedLibraries.keyAt(i);
20867            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20868            if (versionedLib == null) {
20869                continue;
20870            }
20871            final int versionCount = versionedLib.size();
20872            for (int j = 0; j < versionCount; j++) {
20873                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20874                final long sharedLibraryToken =
20875                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20876                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20877                final boolean isJar = (libEntry.path != null);
20878                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20879                if (isJar) {
20880                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20881                } else {
20882                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20883                }
20884                proto.end(sharedLibraryToken);
20885            }
20886        }
20887    }
20888
20889    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20890        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20891        ipw.println();
20892        ipw.println("Dexopt state:");
20893        ipw.increaseIndent();
20894        Collection<PackageParser.Package> packages = null;
20895        if (packageName != null) {
20896            PackageParser.Package targetPackage = mPackages.get(packageName);
20897            if (targetPackage != null) {
20898                packages = Collections.singletonList(targetPackage);
20899            } else {
20900                ipw.println("Unable to find package: " + packageName);
20901                return;
20902            }
20903        } else {
20904            packages = mPackages.values();
20905        }
20906
20907        for (PackageParser.Package pkg : packages) {
20908            ipw.println("[" + pkg.packageName + "]");
20909            ipw.increaseIndent();
20910            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20911            ipw.decreaseIndent();
20912        }
20913    }
20914
20915    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20916        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20917        ipw.println();
20918        ipw.println("Compiler stats:");
20919        ipw.increaseIndent();
20920        Collection<PackageParser.Package> packages = null;
20921        if (packageName != null) {
20922            PackageParser.Package targetPackage = mPackages.get(packageName);
20923            if (targetPackage != null) {
20924                packages = Collections.singletonList(targetPackage);
20925            } else {
20926                ipw.println("Unable to find package: " + packageName);
20927                return;
20928            }
20929        } else {
20930            packages = mPackages.values();
20931        }
20932
20933        for (PackageParser.Package pkg : packages) {
20934            ipw.println("[" + pkg.packageName + "]");
20935            ipw.increaseIndent();
20936
20937            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20938            if (stats == null) {
20939                ipw.println("(No recorded stats)");
20940            } else {
20941                stats.dump(ipw);
20942            }
20943            ipw.decreaseIndent();
20944        }
20945    }
20946
20947    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20948        pw.println("Enabled overlay paths:");
20949        final int N = mEnabledOverlayPaths.size();
20950        for (int i = 0; i < N; i++) {
20951            final int userId = mEnabledOverlayPaths.keyAt(i);
20952            pw.println(String.format("    User %d:", userId));
20953            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20954                mEnabledOverlayPaths.valueAt(i);
20955            final int M = userSpecificOverlays.size();
20956            for (int j = 0; j < M; j++) {
20957                final String targetPackageName = userSpecificOverlays.keyAt(j);
20958                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20959                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20960            }
20961        }
20962    }
20963
20964    private String dumpDomainString(String packageName) {
20965        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20966                .getList();
20967        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20968
20969        ArraySet<String> result = new ArraySet<>();
20970        if (iviList.size() > 0) {
20971            for (IntentFilterVerificationInfo ivi : iviList) {
20972                for (String host : ivi.getDomains()) {
20973                    result.add(host);
20974                }
20975            }
20976        }
20977        if (filters != null && filters.size() > 0) {
20978            for (IntentFilter filter : filters) {
20979                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20980                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20981                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20982                    result.addAll(filter.getHostsList());
20983                }
20984            }
20985        }
20986
20987        StringBuilder sb = new StringBuilder(result.size() * 16);
20988        for (String domain : result) {
20989            if (sb.length() > 0) sb.append(" ");
20990            sb.append(domain);
20991        }
20992        return sb.toString();
20993    }
20994
20995    // ------- apps on sdcard specific code -------
20996    static final boolean DEBUG_SD_INSTALL = false;
20997
20998    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20999
21000    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21001
21002    private boolean mMediaMounted = false;
21003
21004    static String getEncryptKey() {
21005        try {
21006            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21007                    SD_ENCRYPTION_KEYSTORE_NAME);
21008            if (sdEncKey == null) {
21009                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21010                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21011                if (sdEncKey == null) {
21012                    Slog.e(TAG, "Failed to create encryption keys");
21013                    return null;
21014                }
21015            }
21016            return sdEncKey;
21017        } catch (NoSuchAlgorithmException nsae) {
21018            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21019            return null;
21020        } catch (IOException ioe) {
21021            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21022            return null;
21023        }
21024    }
21025
21026    /*
21027     * Update media status on PackageManager.
21028     */
21029    @Override
21030    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21031        int callingUid = Binder.getCallingUid();
21032        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21033            throw new SecurityException("Media status can only be updated by the system");
21034        }
21035        // reader; this apparently protects mMediaMounted, but should probably
21036        // be a different lock in that case.
21037        synchronized (mPackages) {
21038            Log.i(TAG, "Updating external media status from "
21039                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21040                    + (mediaStatus ? "mounted" : "unmounted"));
21041            if (DEBUG_SD_INSTALL)
21042                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21043                        + ", mMediaMounted=" + mMediaMounted);
21044            if (mediaStatus == mMediaMounted) {
21045                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21046                        : 0, -1);
21047                mHandler.sendMessage(msg);
21048                return;
21049            }
21050            mMediaMounted = mediaStatus;
21051        }
21052        // Queue up an async operation since the package installation may take a
21053        // little while.
21054        mHandler.post(new Runnable() {
21055            public void run() {
21056                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21057            }
21058        });
21059    }
21060
21061    /**
21062     * Called by StorageManagerService when the initial ASECs to scan are available.
21063     * Should block until all the ASEC containers are finished being scanned.
21064     */
21065    public void scanAvailableAsecs() {
21066        updateExternalMediaStatusInner(true, false, false);
21067    }
21068
21069    /*
21070     * Collect information of applications on external media, map them against
21071     * existing containers and update information based on current mount status.
21072     * Please note that we always have to report status if reportStatus has been
21073     * set to true especially when unloading packages.
21074     */
21075    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21076            boolean externalStorage) {
21077        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21078        int[] uidArr = EmptyArray.INT;
21079
21080        final String[] list = PackageHelper.getSecureContainerList();
21081        if (ArrayUtils.isEmpty(list)) {
21082            Log.i(TAG, "No secure containers found");
21083        } else {
21084            // Process list of secure containers and categorize them
21085            // as active or stale based on their package internal state.
21086
21087            // reader
21088            synchronized (mPackages) {
21089                for (String cid : list) {
21090                    // Leave stages untouched for now; installer service owns them
21091                    if (PackageInstallerService.isStageName(cid)) continue;
21092
21093                    if (DEBUG_SD_INSTALL)
21094                        Log.i(TAG, "Processing container " + cid);
21095                    String pkgName = getAsecPackageName(cid);
21096                    if (pkgName == null) {
21097                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21098                        continue;
21099                    }
21100                    if (DEBUG_SD_INSTALL)
21101                        Log.i(TAG, "Looking for pkg : " + pkgName);
21102
21103                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21104                    if (ps == null) {
21105                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21106                        continue;
21107                    }
21108
21109                    /*
21110                     * Skip packages that are not external if we're unmounting
21111                     * external storage.
21112                     */
21113                    if (externalStorage && !isMounted && !isExternal(ps)) {
21114                        continue;
21115                    }
21116
21117                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21118                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21119                    // The package status is changed only if the code path
21120                    // matches between settings and the container id.
21121                    if (ps.codePathString != null
21122                            && ps.codePathString.startsWith(args.getCodePath())) {
21123                        if (DEBUG_SD_INSTALL) {
21124                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21125                                    + " at code path: " + ps.codePathString);
21126                        }
21127
21128                        // We do have a valid package installed on sdcard
21129                        processCids.put(args, ps.codePathString);
21130                        final int uid = ps.appId;
21131                        if (uid != -1) {
21132                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21133                        }
21134                    } else {
21135                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21136                                + ps.codePathString);
21137                    }
21138                }
21139            }
21140
21141            Arrays.sort(uidArr);
21142        }
21143
21144        // Process packages with valid entries.
21145        if (isMounted) {
21146            if (DEBUG_SD_INSTALL)
21147                Log.i(TAG, "Loading packages");
21148            loadMediaPackages(processCids, uidArr, externalStorage);
21149            startCleaningPackages();
21150            mInstallerService.onSecureContainersAvailable();
21151        } else {
21152            if (DEBUG_SD_INSTALL)
21153                Log.i(TAG, "Unloading packages");
21154            unloadMediaPackages(processCids, uidArr, reportStatus);
21155        }
21156    }
21157
21158    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21159            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21160        final int size = infos.size();
21161        final String[] packageNames = new String[size];
21162        final int[] packageUids = new int[size];
21163        for (int i = 0; i < size; i++) {
21164            final ApplicationInfo info = infos.get(i);
21165            packageNames[i] = info.packageName;
21166            packageUids[i] = info.uid;
21167        }
21168        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21169                finishedReceiver);
21170    }
21171
21172    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21173            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21174        sendResourcesChangedBroadcast(mediaStatus, replacing,
21175                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21176    }
21177
21178    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21179            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21180        int size = pkgList.length;
21181        if (size > 0) {
21182            // Send broadcasts here
21183            Bundle extras = new Bundle();
21184            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21185            if (uidArr != null) {
21186                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21187            }
21188            if (replacing) {
21189                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21190            }
21191            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21192                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21193            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21194        }
21195    }
21196
21197   /*
21198     * Look at potentially valid container ids from processCids If package
21199     * information doesn't match the one on record or package scanning fails,
21200     * the cid is added to list of removeCids. We currently don't delete stale
21201     * containers.
21202     */
21203    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21204            boolean externalStorage) {
21205        ArrayList<String> pkgList = new ArrayList<String>();
21206        Set<AsecInstallArgs> keys = processCids.keySet();
21207
21208        for (AsecInstallArgs args : keys) {
21209            String codePath = processCids.get(args);
21210            if (DEBUG_SD_INSTALL)
21211                Log.i(TAG, "Loading container : " + args.cid);
21212            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21213            try {
21214                // Make sure there are no container errors first.
21215                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21216                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21217                            + " when installing from sdcard");
21218                    continue;
21219                }
21220                // Check code path here.
21221                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21222                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21223                            + " does not match one in settings " + codePath);
21224                    continue;
21225                }
21226                // Parse package
21227                int parseFlags = mDefParseFlags;
21228                if (args.isExternalAsec()) {
21229                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21230                }
21231                if (args.isFwdLocked()) {
21232                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21233                }
21234
21235                synchronized (mInstallLock) {
21236                    PackageParser.Package pkg = null;
21237                    try {
21238                        // Sadly we don't know the package name yet to freeze it
21239                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21240                                SCAN_IGNORE_FROZEN, 0, null);
21241                    } catch (PackageManagerException e) {
21242                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21243                    }
21244                    // Scan the package
21245                    if (pkg != null) {
21246                        /*
21247                         * TODO why is the lock being held? doPostInstall is
21248                         * called in other places without the lock. This needs
21249                         * to be straightened out.
21250                         */
21251                        // writer
21252                        synchronized (mPackages) {
21253                            retCode = PackageManager.INSTALL_SUCCEEDED;
21254                            pkgList.add(pkg.packageName);
21255                            // Post process args
21256                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21257                                    pkg.applicationInfo.uid);
21258                        }
21259                    } else {
21260                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21261                    }
21262                }
21263
21264            } finally {
21265                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21266                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21267                }
21268            }
21269        }
21270        // writer
21271        synchronized (mPackages) {
21272            // If the platform SDK has changed since the last time we booted,
21273            // we need to re-grant app permission to catch any new ones that
21274            // appear. This is really a hack, and means that apps can in some
21275            // cases get permissions that the user didn't initially explicitly
21276            // allow... it would be nice to have some better way to handle
21277            // this situation.
21278            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21279                    : mSettings.getInternalVersion();
21280            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21281                    : StorageManager.UUID_PRIVATE_INTERNAL;
21282
21283            int updateFlags = UPDATE_PERMISSIONS_ALL;
21284            if (ver.sdkVersion != mSdkVersion) {
21285                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21286                        + mSdkVersion + "; regranting permissions for external");
21287                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21288            }
21289            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21290
21291            // Yay, everything is now upgraded
21292            ver.forceCurrent();
21293
21294            // can downgrade to reader
21295            // Persist settings
21296            mSettings.writeLPr();
21297        }
21298        // Send a broadcast to let everyone know we are done processing
21299        if (pkgList.size() > 0) {
21300            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21301        }
21302    }
21303
21304   /*
21305     * Utility method to unload a list of specified containers
21306     */
21307    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21308        // Just unmount all valid containers.
21309        for (AsecInstallArgs arg : cidArgs) {
21310            synchronized (mInstallLock) {
21311                arg.doPostDeleteLI(false);
21312           }
21313       }
21314   }
21315
21316    /*
21317     * Unload packages mounted on external media. This involves deleting package
21318     * data from internal structures, sending broadcasts about disabled packages,
21319     * gc'ing to free up references, unmounting all secure containers
21320     * corresponding to packages on external media, and posting a
21321     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21322     * that we always have to post this message if status has been requested no
21323     * matter what.
21324     */
21325    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21326            final boolean reportStatus) {
21327        if (DEBUG_SD_INSTALL)
21328            Log.i(TAG, "unloading media packages");
21329        ArrayList<String> pkgList = new ArrayList<String>();
21330        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21331        final Set<AsecInstallArgs> keys = processCids.keySet();
21332        for (AsecInstallArgs args : keys) {
21333            String pkgName = args.getPackageName();
21334            if (DEBUG_SD_INSTALL)
21335                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21336            // Delete package internally
21337            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21338            synchronized (mInstallLock) {
21339                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21340                final boolean res;
21341                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21342                        "unloadMediaPackages")) {
21343                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21344                            null);
21345                }
21346                if (res) {
21347                    pkgList.add(pkgName);
21348                } else {
21349                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21350                    failedList.add(args);
21351                }
21352            }
21353        }
21354
21355        // reader
21356        synchronized (mPackages) {
21357            // We didn't update the settings after removing each package;
21358            // write them now for all packages.
21359            mSettings.writeLPr();
21360        }
21361
21362        // We have to absolutely send UPDATED_MEDIA_STATUS only
21363        // after confirming that all the receivers processed the ordered
21364        // broadcast when packages get disabled, force a gc to clean things up.
21365        // and unload all the containers.
21366        if (pkgList.size() > 0) {
21367            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21368                    new IIntentReceiver.Stub() {
21369                public void performReceive(Intent intent, int resultCode, String data,
21370                        Bundle extras, boolean ordered, boolean sticky,
21371                        int sendingUser) throws RemoteException {
21372                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21373                            reportStatus ? 1 : 0, 1, keys);
21374                    mHandler.sendMessage(msg);
21375                }
21376            });
21377        } else {
21378            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21379                    keys);
21380            mHandler.sendMessage(msg);
21381        }
21382    }
21383
21384    private void loadPrivatePackages(final VolumeInfo vol) {
21385        mHandler.post(new Runnable() {
21386            @Override
21387            public void run() {
21388                loadPrivatePackagesInner(vol);
21389            }
21390        });
21391    }
21392
21393    private void loadPrivatePackagesInner(VolumeInfo vol) {
21394        final String volumeUuid = vol.fsUuid;
21395        if (TextUtils.isEmpty(volumeUuid)) {
21396            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21397            return;
21398        }
21399
21400        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21401        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21402        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21403
21404        final VersionInfo ver;
21405        final List<PackageSetting> packages;
21406        synchronized (mPackages) {
21407            ver = mSettings.findOrCreateVersion(volumeUuid);
21408            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21409        }
21410
21411        for (PackageSetting ps : packages) {
21412            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21413            synchronized (mInstallLock) {
21414                final PackageParser.Package pkg;
21415                try {
21416                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21417                    loaded.add(pkg.applicationInfo);
21418
21419                } catch (PackageManagerException e) {
21420                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21421                }
21422
21423                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21424                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21425                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21426                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21427                }
21428            }
21429        }
21430
21431        // Reconcile app data for all started/unlocked users
21432        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21433        final UserManager um = mContext.getSystemService(UserManager.class);
21434        UserManagerInternal umInternal = getUserManagerInternal();
21435        for (UserInfo user : um.getUsers()) {
21436            final int flags;
21437            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21438                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21439            } else if (umInternal.isUserRunning(user.id)) {
21440                flags = StorageManager.FLAG_STORAGE_DE;
21441            } else {
21442                continue;
21443            }
21444
21445            try {
21446                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21447                synchronized (mInstallLock) {
21448                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21449                }
21450            } catch (IllegalStateException e) {
21451                // Device was probably ejected, and we'll process that event momentarily
21452                Slog.w(TAG, "Failed to prepare storage: " + e);
21453            }
21454        }
21455
21456        synchronized (mPackages) {
21457            int updateFlags = UPDATE_PERMISSIONS_ALL;
21458            if (ver.sdkVersion != mSdkVersion) {
21459                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21460                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21461                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21462            }
21463            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21464
21465            // Yay, everything is now upgraded
21466            ver.forceCurrent();
21467
21468            mSettings.writeLPr();
21469        }
21470
21471        for (PackageFreezer freezer : freezers) {
21472            freezer.close();
21473        }
21474
21475        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21476        sendResourcesChangedBroadcast(true, false, loaded, null);
21477    }
21478
21479    private void unloadPrivatePackages(final VolumeInfo vol) {
21480        mHandler.post(new Runnable() {
21481            @Override
21482            public void run() {
21483                unloadPrivatePackagesInner(vol);
21484            }
21485        });
21486    }
21487
21488    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21489        final String volumeUuid = vol.fsUuid;
21490        if (TextUtils.isEmpty(volumeUuid)) {
21491            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21492            return;
21493        }
21494
21495        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21496        synchronized (mInstallLock) {
21497        synchronized (mPackages) {
21498            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21499            for (PackageSetting ps : packages) {
21500                if (ps.pkg == null) continue;
21501
21502                final ApplicationInfo info = ps.pkg.applicationInfo;
21503                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21504                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21505
21506                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21507                        "unloadPrivatePackagesInner")) {
21508                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21509                            false, null)) {
21510                        unloaded.add(info);
21511                    } else {
21512                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21513                    }
21514                }
21515
21516                // Try very hard to release any references to this package
21517                // so we don't risk the system server being killed due to
21518                // open FDs
21519                AttributeCache.instance().removePackage(ps.name);
21520            }
21521
21522            mSettings.writeLPr();
21523        }
21524        }
21525
21526        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21527        sendResourcesChangedBroadcast(false, false, unloaded, null);
21528
21529        // Try very hard to release any references to this path so we don't risk
21530        // the system server being killed due to open FDs
21531        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21532
21533        for (int i = 0; i < 3; i++) {
21534            System.gc();
21535            System.runFinalization();
21536        }
21537    }
21538
21539    private void assertPackageKnown(String volumeUuid, String packageName)
21540            throws PackageManagerException {
21541        synchronized (mPackages) {
21542            // Normalize package name to handle renamed packages
21543            packageName = normalizePackageNameLPr(packageName);
21544
21545            final PackageSetting ps = mSettings.mPackages.get(packageName);
21546            if (ps == null) {
21547                throw new PackageManagerException("Package " + packageName + " is unknown");
21548            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21549                throw new PackageManagerException(
21550                        "Package " + packageName + " found on unknown volume " + volumeUuid
21551                                + "; expected volume " + ps.volumeUuid);
21552            }
21553        }
21554    }
21555
21556    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21557            throws PackageManagerException {
21558        synchronized (mPackages) {
21559            // Normalize package name to handle renamed packages
21560            packageName = normalizePackageNameLPr(packageName);
21561
21562            final PackageSetting ps = mSettings.mPackages.get(packageName);
21563            if (ps == null) {
21564                throw new PackageManagerException("Package " + packageName + " is unknown");
21565            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21566                throw new PackageManagerException(
21567                        "Package " + packageName + " found on unknown volume " + volumeUuid
21568                                + "; expected volume " + ps.volumeUuid);
21569            } else if (!ps.getInstalled(userId)) {
21570                throw new PackageManagerException(
21571                        "Package " + packageName + " not installed for user " + userId);
21572            }
21573        }
21574    }
21575
21576    private List<String> collectAbsoluteCodePaths() {
21577        synchronized (mPackages) {
21578            List<String> codePaths = new ArrayList<>();
21579            final int packageCount = mSettings.mPackages.size();
21580            for (int i = 0; i < packageCount; i++) {
21581                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21582                codePaths.add(ps.codePath.getAbsolutePath());
21583            }
21584            return codePaths;
21585        }
21586    }
21587
21588    /**
21589     * Examine all apps present on given mounted volume, and destroy apps that
21590     * aren't expected, either due to uninstallation or reinstallation on
21591     * another volume.
21592     */
21593    private void reconcileApps(String volumeUuid) {
21594        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21595        List<File> filesToDelete = null;
21596
21597        final File[] files = FileUtils.listFilesOrEmpty(
21598                Environment.getDataAppDirectory(volumeUuid));
21599        for (File file : files) {
21600            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21601                    && !PackageInstallerService.isStageName(file.getName());
21602            if (!isPackage) {
21603                // Ignore entries which are not packages
21604                continue;
21605            }
21606
21607            String absolutePath = file.getAbsolutePath();
21608
21609            boolean pathValid = false;
21610            final int absoluteCodePathCount = absoluteCodePaths.size();
21611            for (int i = 0; i < absoluteCodePathCount; i++) {
21612                String absoluteCodePath = absoluteCodePaths.get(i);
21613                if (absolutePath.startsWith(absoluteCodePath)) {
21614                    pathValid = true;
21615                    break;
21616                }
21617            }
21618
21619            if (!pathValid) {
21620                if (filesToDelete == null) {
21621                    filesToDelete = new ArrayList<>();
21622                }
21623                filesToDelete.add(file);
21624            }
21625        }
21626
21627        if (filesToDelete != null) {
21628            final int fileToDeleteCount = filesToDelete.size();
21629            for (int i = 0; i < fileToDeleteCount; i++) {
21630                File fileToDelete = filesToDelete.get(i);
21631                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21632                synchronized (mInstallLock) {
21633                    removeCodePathLI(fileToDelete);
21634                }
21635            }
21636        }
21637    }
21638
21639    /**
21640     * Reconcile all app data for the given user.
21641     * <p>
21642     * Verifies that directories exist and that ownership and labeling is
21643     * correct for all installed apps on all mounted volumes.
21644     */
21645    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21646        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21647        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21648            final String volumeUuid = vol.getFsUuid();
21649            synchronized (mInstallLock) {
21650                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21651            }
21652        }
21653    }
21654
21655    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21656            boolean migrateAppData) {
21657        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21658    }
21659
21660    /**
21661     * Reconcile all app data on given mounted volume.
21662     * <p>
21663     * Destroys app data that isn't expected, either due to uninstallation or
21664     * reinstallation on another volume.
21665     * <p>
21666     * Verifies that directories exist and that ownership and labeling is
21667     * correct for all installed apps.
21668     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21669     */
21670    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21671            boolean migrateAppData, boolean onlyCoreApps) {
21672        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21673                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21674        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21675
21676        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21677        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21678
21679        // First look for stale data that doesn't belong, and check if things
21680        // have changed since we did our last restorecon
21681        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21682            if (StorageManager.isFileEncryptedNativeOrEmulated()
21683                    && !StorageManager.isUserKeyUnlocked(userId)) {
21684                throw new RuntimeException(
21685                        "Yikes, someone asked us to reconcile CE storage while " + userId
21686                                + " was still locked; this would have caused massive data loss!");
21687            }
21688
21689            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21690            for (File file : files) {
21691                final String packageName = file.getName();
21692                try {
21693                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21694                } catch (PackageManagerException e) {
21695                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21696                    try {
21697                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21698                                StorageManager.FLAG_STORAGE_CE, 0);
21699                    } catch (InstallerException e2) {
21700                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21701                    }
21702                }
21703            }
21704        }
21705        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21706            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21707            for (File file : files) {
21708                final String packageName = file.getName();
21709                try {
21710                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21711                } catch (PackageManagerException e) {
21712                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21713                    try {
21714                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21715                                StorageManager.FLAG_STORAGE_DE, 0);
21716                    } catch (InstallerException e2) {
21717                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21718                    }
21719                }
21720            }
21721        }
21722
21723        // Ensure that data directories are ready to roll for all packages
21724        // installed for this volume and user
21725        final List<PackageSetting> packages;
21726        synchronized (mPackages) {
21727            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21728        }
21729        int preparedCount = 0;
21730        for (PackageSetting ps : packages) {
21731            final String packageName = ps.name;
21732            if (ps.pkg == null) {
21733                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21734                // TODO: might be due to legacy ASEC apps; we should circle back
21735                // and reconcile again once they're scanned
21736                continue;
21737            }
21738            // Skip non-core apps if requested
21739            if (onlyCoreApps && !ps.pkg.coreApp) {
21740                result.add(packageName);
21741                continue;
21742            }
21743
21744            if (ps.getInstalled(userId)) {
21745                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21746                preparedCount++;
21747            }
21748        }
21749
21750        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21751        return result;
21752    }
21753
21754    /**
21755     * Prepare app data for the given app just after it was installed or
21756     * upgraded. This method carefully only touches users that it's installed
21757     * for, and it forces a restorecon to handle any seinfo changes.
21758     * <p>
21759     * Verifies that directories exist and that ownership and labeling is
21760     * correct for all installed apps. If there is an ownership mismatch, it
21761     * will try recovering system apps by wiping data; third-party app data is
21762     * left intact.
21763     * <p>
21764     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21765     */
21766    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21767        final PackageSetting ps;
21768        synchronized (mPackages) {
21769            ps = mSettings.mPackages.get(pkg.packageName);
21770            mSettings.writeKernelMappingLPr(ps);
21771        }
21772
21773        final UserManager um = mContext.getSystemService(UserManager.class);
21774        UserManagerInternal umInternal = getUserManagerInternal();
21775        for (UserInfo user : um.getUsers()) {
21776            final int flags;
21777            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21778                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21779            } else if (umInternal.isUserRunning(user.id)) {
21780                flags = StorageManager.FLAG_STORAGE_DE;
21781            } else {
21782                continue;
21783            }
21784
21785            if (ps.getInstalled(user.id)) {
21786                // TODO: when user data is locked, mark that we're still dirty
21787                prepareAppDataLIF(pkg, user.id, flags);
21788            }
21789        }
21790    }
21791
21792    /**
21793     * Prepare app data for the given app.
21794     * <p>
21795     * Verifies that directories exist and that ownership and labeling is
21796     * correct for all installed apps. If there is an ownership mismatch, this
21797     * will try recovering system apps by wiping data; third-party app data is
21798     * left intact.
21799     */
21800    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21801        if (pkg == null) {
21802            Slog.wtf(TAG, "Package was null!", new Throwable());
21803            return;
21804        }
21805        prepareAppDataLeafLIF(pkg, userId, flags);
21806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21807        for (int i = 0; i < childCount; i++) {
21808            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21809        }
21810    }
21811
21812    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21813            boolean maybeMigrateAppData) {
21814        prepareAppDataLIF(pkg, userId, flags);
21815
21816        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21817            // We may have just shuffled around app data directories, so
21818            // prepare them one more time
21819            prepareAppDataLIF(pkg, userId, flags);
21820        }
21821    }
21822
21823    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21824        if (DEBUG_APP_DATA) {
21825            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21826                    + Integer.toHexString(flags));
21827        }
21828
21829        final String volumeUuid = pkg.volumeUuid;
21830        final String packageName = pkg.packageName;
21831        final ApplicationInfo app = pkg.applicationInfo;
21832        final int appId = UserHandle.getAppId(app.uid);
21833
21834        Preconditions.checkNotNull(app.seInfo);
21835
21836        long ceDataInode = -1;
21837        try {
21838            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21839                    appId, app.seInfo, app.targetSdkVersion);
21840        } catch (InstallerException e) {
21841            if (app.isSystemApp()) {
21842                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21843                        + ", but trying to recover: " + e);
21844                destroyAppDataLeafLIF(pkg, userId, flags);
21845                try {
21846                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21847                            appId, app.seInfo, app.targetSdkVersion);
21848                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21849                } catch (InstallerException e2) {
21850                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21851                }
21852            } else {
21853                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21854            }
21855        }
21856
21857        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21858            // TODO: mark this structure as dirty so we persist it!
21859            synchronized (mPackages) {
21860                final PackageSetting ps = mSettings.mPackages.get(packageName);
21861                if (ps != null) {
21862                    ps.setCeDataInode(ceDataInode, userId);
21863                }
21864            }
21865        }
21866
21867        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21868    }
21869
21870    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21871        if (pkg == null) {
21872            Slog.wtf(TAG, "Package was null!", new Throwable());
21873            return;
21874        }
21875        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21876        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21877        for (int i = 0; i < childCount; i++) {
21878            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21879        }
21880    }
21881
21882    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21883        final String volumeUuid = pkg.volumeUuid;
21884        final String packageName = pkg.packageName;
21885        final ApplicationInfo app = pkg.applicationInfo;
21886
21887        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21888            // Create a native library symlink only if we have native libraries
21889            // and if the native libraries are 32 bit libraries. We do not provide
21890            // this symlink for 64 bit libraries.
21891            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21892                final String nativeLibPath = app.nativeLibraryDir;
21893                try {
21894                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21895                            nativeLibPath, userId);
21896                } catch (InstallerException e) {
21897                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21898                }
21899            }
21900        }
21901    }
21902
21903    /**
21904     * For system apps on non-FBE devices, this method migrates any existing
21905     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21906     * requested by the app.
21907     */
21908    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21909        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21910                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21911            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21912                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21913            try {
21914                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21915                        storageTarget);
21916            } catch (InstallerException e) {
21917                logCriticalInfo(Log.WARN,
21918                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21919            }
21920            return true;
21921        } else {
21922            return false;
21923        }
21924    }
21925
21926    public PackageFreezer freezePackage(String packageName, String killReason) {
21927        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21928    }
21929
21930    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21931        return new PackageFreezer(packageName, userId, killReason);
21932    }
21933
21934    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21935            String killReason) {
21936        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21937    }
21938
21939    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21940            String killReason) {
21941        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21942            return new PackageFreezer();
21943        } else {
21944            return freezePackage(packageName, userId, killReason);
21945        }
21946    }
21947
21948    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21949            String killReason) {
21950        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21951    }
21952
21953    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21954            String killReason) {
21955        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21956            return new PackageFreezer();
21957        } else {
21958            return freezePackage(packageName, userId, killReason);
21959        }
21960    }
21961
21962    /**
21963     * Class that freezes and kills the given package upon creation, and
21964     * unfreezes it upon closing. This is typically used when doing surgery on
21965     * app code/data to prevent the app from running while you're working.
21966     */
21967    private class PackageFreezer implements AutoCloseable {
21968        private final String mPackageName;
21969        private final PackageFreezer[] mChildren;
21970
21971        private final boolean mWeFroze;
21972
21973        private final AtomicBoolean mClosed = new AtomicBoolean();
21974        private final CloseGuard mCloseGuard = CloseGuard.get();
21975
21976        /**
21977         * Create and return a stub freezer that doesn't actually do anything,
21978         * typically used when someone requested
21979         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21980         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21981         */
21982        public PackageFreezer() {
21983            mPackageName = null;
21984            mChildren = null;
21985            mWeFroze = false;
21986            mCloseGuard.open("close");
21987        }
21988
21989        public PackageFreezer(String packageName, int userId, String killReason) {
21990            synchronized (mPackages) {
21991                mPackageName = packageName;
21992                mWeFroze = mFrozenPackages.add(mPackageName);
21993
21994                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21995                if (ps != null) {
21996                    killApplication(ps.name, ps.appId, userId, killReason);
21997                }
21998
21999                final PackageParser.Package p = mPackages.get(packageName);
22000                if (p != null && p.childPackages != null) {
22001                    final int N = p.childPackages.size();
22002                    mChildren = new PackageFreezer[N];
22003                    for (int i = 0; i < N; i++) {
22004                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22005                                userId, killReason);
22006                    }
22007                } else {
22008                    mChildren = null;
22009                }
22010            }
22011            mCloseGuard.open("close");
22012        }
22013
22014        @Override
22015        protected void finalize() throws Throwable {
22016            try {
22017                mCloseGuard.warnIfOpen();
22018                close();
22019            } finally {
22020                super.finalize();
22021            }
22022        }
22023
22024        @Override
22025        public void close() {
22026            mCloseGuard.close();
22027            if (mClosed.compareAndSet(false, true)) {
22028                synchronized (mPackages) {
22029                    if (mWeFroze) {
22030                        mFrozenPackages.remove(mPackageName);
22031                    }
22032
22033                    if (mChildren != null) {
22034                        for (PackageFreezer freezer : mChildren) {
22035                            freezer.close();
22036                        }
22037                    }
22038                }
22039            }
22040        }
22041    }
22042
22043    /**
22044     * Verify that given package is currently frozen.
22045     */
22046    private void checkPackageFrozen(String packageName) {
22047        synchronized (mPackages) {
22048            if (!mFrozenPackages.contains(packageName)) {
22049                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22050            }
22051        }
22052    }
22053
22054    @Override
22055    public int movePackage(final String packageName, final String volumeUuid) {
22056        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22057
22058        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22059        final int moveId = mNextMoveId.getAndIncrement();
22060        mHandler.post(new Runnable() {
22061            @Override
22062            public void run() {
22063                try {
22064                    movePackageInternal(packageName, volumeUuid, moveId, user);
22065                } catch (PackageManagerException e) {
22066                    Slog.w(TAG, "Failed to move " + packageName, e);
22067                    mMoveCallbacks.notifyStatusChanged(moveId,
22068                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22069                }
22070            }
22071        });
22072        return moveId;
22073    }
22074
22075    private void movePackageInternal(final String packageName, final String volumeUuid,
22076            final int moveId, UserHandle user) throws PackageManagerException {
22077        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22078        final PackageManager pm = mContext.getPackageManager();
22079
22080        final boolean currentAsec;
22081        final String currentVolumeUuid;
22082        final File codeFile;
22083        final String installerPackageName;
22084        final String packageAbiOverride;
22085        final int appId;
22086        final String seinfo;
22087        final String label;
22088        final int targetSdkVersion;
22089        final PackageFreezer freezer;
22090        final int[] installedUserIds;
22091
22092        // reader
22093        synchronized (mPackages) {
22094            final PackageParser.Package pkg = mPackages.get(packageName);
22095            final PackageSetting ps = mSettings.mPackages.get(packageName);
22096            if (pkg == null || ps == null) {
22097                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22098            }
22099
22100            if (pkg.applicationInfo.isSystemApp()) {
22101                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22102                        "Cannot move system application");
22103            }
22104
22105            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22106            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22107                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22108            if (isInternalStorage && !allow3rdPartyOnInternal) {
22109                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22110                        "3rd party apps are not allowed on internal storage");
22111            }
22112
22113            if (pkg.applicationInfo.isExternalAsec()) {
22114                currentAsec = true;
22115                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22116            } else if (pkg.applicationInfo.isForwardLocked()) {
22117                currentAsec = true;
22118                currentVolumeUuid = "forward_locked";
22119            } else {
22120                currentAsec = false;
22121                currentVolumeUuid = ps.volumeUuid;
22122
22123                final File probe = new File(pkg.codePath);
22124                final File probeOat = new File(probe, "oat");
22125                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22126                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22127                            "Move only supported for modern cluster style installs");
22128                }
22129            }
22130
22131            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22132                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22133                        "Package already moved to " + volumeUuid);
22134            }
22135            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22136                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22137                        "Device admin cannot be moved");
22138            }
22139
22140            if (mFrozenPackages.contains(packageName)) {
22141                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22142                        "Failed to move already frozen package");
22143            }
22144
22145            codeFile = new File(pkg.codePath);
22146            installerPackageName = ps.installerPackageName;
22147            packageAbiOverride = ps.cpuAbiOverrideString;
22148            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22149            seinfo = pkg.applicationInfo.seInfo;
22150            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22151            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22152            freezer = freezePackage(packageName, "movePackageInternal");
22153            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22154        }
22155
22156        final Bundle extras = new Bundle();
22157        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22158        extras.putString(Intent.EXTRA_TITLE, label);
22159        mMoveCallbacks.notifyCreated(moveId, extras);
22160
22161        int installFlags;
22162        final boolean moveCompleteApp;
22163        final File measurePath;
22164
22165        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22166            installFlags = INSTALL_INTERNAL;
22167            moveCompleteApp = !currentAsec;
22168            measurePath = Environment.getDataAppDirectory(volumeUuid);
22169        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22170            installFlags = INSTALL_EXTERNAL;
22171            moveCompleteApp = false;
22172            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22173        } else {
22174            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22175            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22176                    || !volume.isMountedWritable()) {
22177                freezer.close();
22178                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22179                        "Move location not mounted private volume");
22180            }
22181
22182            Preconditions.checkState(!currentAsec);
22183
22184            installFlags = INSTALL_INTERNAL;
22185            moveCompleteApp = true;
22186            measurePath = Environment.getDataAppDirectory(volumeUuid);
22187        }
22188
22189        final PackageStats stats = new PackageStats(null, -1);
22190        synchronized (mInstaller) {
22191            for (int userId : installedUserIds) {
22192                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22193                    freezer.close();
22194                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22195                            "Failed to measure package size");
22196                }
22197            }
22198        }
22199
22200        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22201                + stats.dataSize);
22202
22203        final long startFreeBytes = measurePath.getFreeSpace();
22204        final long sizeBytes;
22205        if (moveCompleteApp) {
22206            sizeBytes = stats.codeSize + stats.dataSize;
22207        } else {
22208            sizeBytes = stats.codeSize;
22209        }
22210
22211        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22212            freezer.close();
22213            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22214                    "Not enough free space to move");
22215        }
22216
22217        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22218
22219        final CountDownLatch installedLatch = new CountDownLatch(1);
22220        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22221            @Override
22222            public void onUserActionRequired(Intent intent) throws RemoteException {
22223                throw new IllegalStateException();
22224            }
22225
22226            @Override
22227            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22228                    Bundle extras) throws RemoteException {
22229                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22230                        + PackageManager.installStatusToString(returnCode, msg));
22231
22232                installedLatch.countDown();
22233                freezer.close();
22234
22235                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22236                switch (status) {
22237                    case PackageInstaller.STATUS_SUCCESS:
22238                        mMoveCallbacks.notifyStatusChanged(moveId,
22239                                PackageManager.MOVE_SUCCEEDED);
22240                        break;
22241                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22242                        mMoveCallbacks.notifyStatusChanged(moveId,
22243                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22244                        break;
22245                    default:
22246                        mMoveCallbacks.notifyStatusChanged(moveId,
22247                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22248                        break;
22249                }
22250            }
22251        };
22252
22253        final MoveInfo move;
22254        if (moveCompleteApp) {
22255            // Kick off a thread to report progress estimates
22256            new Thread() {
22257                @Override
22258                public void run() {
22259                    while (true) {
22260                        try {
22261                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22262                                break;
22263                            }
22264                        } catch (InterruptedException ignored) {
22265                        }
22266
22267                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22268                        final int progress = 10 + (int) MathUtils.constrain(
22269                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22270                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22271                    }
22272                }
22273            }.start();
22274
22275            final String dataAppName = codeFile.getName();
22276            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22277                    dataAppName, appId, seinfo, targetSdkVersion);
22278        } else {
22279            move = null;
22280        }
22281
22282        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22283
22284        final Message msg = mHandler.obtainMessage(INIT_COPY);
22285        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22286        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22287                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22288                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22289                PackageManager.INSTALL_REASON_UNKNOWN);
22290        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22291        msg.obj = params;
22292
22293        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22294                System.identityHashCode(msg.obj));
22295        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22296                System.identityHashCode(msg.obj));
22297
22298        mHandler.sendMessage(msg);
22299    }
22300
22301    @Override
22302    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22303        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22304
22305        final int realMoveId = mNextMoveId.getAndIncrement();
22306        final Bundle extras = new Bundle();
22307        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22308        mMoveCallbacks.notifyCreated(realMoveId, extras);
22309
22310        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22311            @Override
22312            public void onCreated(int moveId, Bundle extras) {
22313                // Ignored
22314            }
22315
22316            @Override
22317            public void onStatusChanged(int moveId, int status, long estMillis) {
22318                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22319            }
22320        };
22321
22322        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22323        storage.setPrimaryStorageUuid(volumeUuid, callback);
22324        return realMoveId;
22325    }
22326
22327    @Override
22328    public int getMoveStatus(int moveId) {
22329        mContext.enforceCallingOrSelfPermission(
22330                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22331        return mMoveCallbacks.mLastStatus.get(moveId);
22332    }
22333
22334    @Override
22335    public void registerMoveCallback(IPackageMoveObserver callback) {
22336        mContext.enforceCallingOrSelfPermission(
22337                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22338        mMoveCallbacks.register(callback);
22339    }
22340
22341    @Override
22342    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22343        mContext.enforceCallingOrSelfPermission(
22344                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22345        mMoveCallbacks.unregister(callback);
22346    }
22347
22348    @Override
22349    public boolean setInstallLocation(int loc) {
22350        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22351                null);
22352        if (getInstallLocation() == loc) {
22353            return true;
22354        }
22355        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22356                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22357            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22358                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22359            return true;
22360        }
22361        return false;
22362   }
22363
22364    @Override
22365    public int getInstallLocation() {
22366        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22367                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22368                PackageHelper.APP_INSTALL_AUTO);
22369    }
22370
22371    /** Called by UserManagerService */
22372    void cleanUpUser(UserManagerService userManager, int userHandle) {
22373        synchronized (mPackages) {
22374            mDirtyUsers.remove(userHandle);
22375            mUserNeedsBadging.delete(userHandle);
22376            mSettings.removeUserLPw(userHandle);
22377            mPendingBroadcasts.remove(userHandle);
22378            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22379            removeUnusedPackagesLPw(userManager, userHandle);
22380        }
22381    }
22382
22383    /**
22384     * We're removing userHandle and would like to remove any downloaded packages
22385     * that are no longer in use by any other user.
22386     * @param userHandle the user being removed
22387     */
22388    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22389        final boolean DEBUG_CLEAN_APKS = false;
22390        int [] users = userManager.getUserIds();
22391        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22392        while (psit.hasNext()) {
22393            PackageSetting ps = psit.next();
22394            if (ps.pkg == null) {
22395                continue;
22396            }
22397            final String packageName = ps.pkg.packageName;
22398            // Skip over if system app
22399            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22400                continue;
22401            }
22402            if (DEBUG_CLEAN_APKS) {
22403                Slog.i(TAG, "Checking package " + packageName);
22404            }
22405            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22406            if (keep) {
22407                if (DEBUG_CLEAN_APKS) {
22408                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22409                }
22410            } else {
22411                for (int i = 0; i < users.length; i++) {
22412                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22413                        keep = true;
22414                        if (DEBUG_CLEAN_APKS) {
22415                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22416                                    + users[i]);
22417                        }
22418                        break;
22419                    }
22420                }
22421            }
22422            if (!keep) {
22423                if (DEBUG_CLEAN_APKS) {
22424                    Slog.i(TAG, "  Removing package " + packageName);
22425                }
22426                mHandler.post(new Runnable() {
22427                    public void run() {
22428                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22429                                userHandle, 0);
22430                    } //end run
22431                });
22432            }
22433        }
22434    }
22435
22436    /** Called by UserManagerService */
22437    void createNewUser(int userId, String[] disallowedPackages) {
22438        synchronized (mInstallLock) {
22439            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22440        }
22441        synchronized (mPackages) {
22442            scheduleWritePackageRestrictionsLocked(userId);
22443            scheduleWritePackageListLocked(userId);
22444            applyFactoryDefaultBrowserLPw(userId);
22445            primeDomainVerificationsLPw(userId);
22446        }
22447    }
22448
22449    void onNewUserCreated(final int userId) {
22450        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22451        // If permission review for legacy apps is required, we represent
22452        // dagerous permissions for such apps as always granted runtime
22453        // permissions to keep per user flag state whether review is needed.
22454        // Hence, if a new user is added we have to propagate dangerous
22455        // permission grants for these legacy apps.
22456        if (mPermissionReviewRequired) {
22457            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22458                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22459        }
22460    }
22461
22462    @Override
22463    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22464        mContext.enforceCallingOrSelfPermission(
22465                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22466                "Only package verification agents can read the verifier device identity");
22467
22468        synchronized (mPackages) {
22469            return mSettings.getVerifierDeviceIdentityLPw();
22470        }
22471    }
22472
22473    @Override
22474    public void setPermissionEnforced(String permission, boolean enforced) {
22475        // TODO: Now that we no longer change GID for storage, this should to away.
22476        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22477                "setPermissionEnforced");
22478        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22479            synchronized (mPackages) {
22480                if (mSettings.mReadExternalStorageEnforced == null
22481                        || mSettings.mReadExternalStorageEnforced != enforced) {
22482                    mSettings.mReadExternalStorageEnforced = enforced;
22483                    mSettings.writeLPr();
22484                }
22485            }
22486            // kill any non-foreground processes so we restart them and
22487            // grant/revoke the GID.
22488            final IActivityManager am = ActivityManager.getService();
22489            if (am != null) {
22490                final long token = Binder.clearCallingIdentity();
22491                try {
22492                    am.killProcessesBelowForeground("setPermissionEnforcement");
22493                } catch (RemoteException e) {
22494                } finally {
22495                    Binder.restoreCallingIdentity(token);
22496                }
22497            }
22498        } else {
22499            throw new IllegalArgumentException("No selective enforcement for " + permission);
22500        }
22501    }
22502
22503    @Override
22504    @Deprecated
22505    public boolean isPermissionEnforced(String permission) {
22506        return true;
22507    }
22508
22509    @Override
22510    public boolean isStorageLow() {
22511        final long token = Binder.clearCallingIdentity();
22512        try {
22513            final DeviceStorageMonitorInternal
22514                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22515            if (dsm != null) {
22516                return dsm.isMemoryLow();
22517            } else {
22518                return false;
22519            }
22520        } finally {
22521            Binder.restoreCallingIdentity(token);
22522        }
22523    }
22524
22525    @Override
22526    public IPackageInstaller getPackageInstaller() {
22527        return mInstallerService;
22528    }
22529
22530    private boolean userNeedsBadging(int userId) {
22531        int index = mUserNeedsBadging.indexOfKey(userId);
22532        if (index < 0) {
22533            final UserInfo userInfo;
22534            final long token = Binder.clearCallingIdentity();
22535            try {
22536                userInfo = sUserManager.getUserInfo(userId);
22537            } finally {
22538                Binder.restoreCallingIdentity(token);
22539            }
22540            final boolean b;
22541            if (userInfo != null && userInfo.isManagedProfile()) {
22542                b = true;
22543            } else {
22544                b = false;
22545            }
22546            mUserNeedsBadging.put(userId, b);
22547            return b;
22548        }
22549        return mUserNeedsBadging.valueAt(index);
22550    }
22551
22552    @Override
22553    public KeySet getKeySetByAlias(String packageName, String alias) {
22554        if (packageName == null || alias == null) {
22555            return null;
22556        }
22557        synchronized(mPackages) {
22558            final PackageParser.Package pkg = mPackages.get(packageName);
22559            if (pkg == null) {
22560                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22561                throw new IllegalArgumentException("Unknown package: " + packageName);
22562            }
22563            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22564            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22565        }
22566    }
22567
22568    @Override
22569    public KeySet getSigningKeySet(String packageName) {
22570        if (packageName == null) {
22571            return null;
22572        }
22573        synchronized(mPackages) {
22574            final PackageParser.Package pkg = mPackages.get(packageName);
22575            if (pkg == null) {
22576                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22577                throw new IllegalArgumentException("Unknown package: " + packageName);
22578            }
22579            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22580                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22581                throw new SecurityException("May not access signing KeySet of other apps.");
22582            }
22583            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22584            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22585        }
22586    }
22587
22588    @Override
22589    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22590        if (packageName == null || ks == null) {
22591            return false;
22592        }
22593        synchronized(mPackages) {
22594            final PackageParser.Package pkg = mPackages.get(packageName);
22595            if (pkg == null) {
22596                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22597                throw new IllegalArgumentException("Unknown package: " + packageName);
22598            }
22599            IBinder ksh = ks.getToken();
22600            if (ksh instanceof KeySetHandle) {
22601                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22602                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22603            }
22604            return false;
22605        }
22606    }
22607
22608    @Override
22609    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22610        if (packageName == null || ks == null) {
22611            return false;
22612        }
22613        synchronized(mPackages) {
22614            final PackageParser.Package pkg = mPackages.get(packageName);
22615            if (pkg == null) {
22616                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22617                throw new IllegalArgumentException("Unknown package: " + packageName);
22618            }
22619            IBinder ksh = ks.getToken();
22620            if (ksh instanceof KeySetHandle) {
22621                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22622                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22623            }
22624            return false;
22625        }
22626    }
22627
22628    private void deletePackageIfUnusedLPr(final String packageName) {
22629        PackageSetting ps = mSettings.mPackages.get(packageName);
22630        if (ps == null) {
22631            return;
22632        }
22633        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22634            // TODO Implement atomic delete if package is unused
22635            // It is currently possible that the package will be deleted even if it is installed
22636            // after this method returns.
22637            mHandler.post(new Runnable() {
22638                public void run() {
22639                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22640                            0, PackageManager.DELETE_ALL_USERS);
22641                }
22642            });
22643        }
22644    }
22645
22646    /**
22647     * Check and throw if the given before/after packages would be considered a
22648     * downgrade.
22649     */
22650    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22651            throws PackageManagerException {
22652        if (after.versionCode < before.mVersionCode) {
22653            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22654                    "Update version code " + after.versionCode + " is older than current "
22655                    + before.mVersionCode);
22656        } else if (after.versionCode == before.mVersionCode) {
22657            if (after.baseRevisionCode < before.baseRevisionCode) {
22658                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22659                        "Update base revision code " + after.baseRevisionCode
22660                        + " is older than current " + before.baseRevisionCode);
22661            }
22662
22663            if (!ArrayUtils.isEmpty(after.splitNames)) {
22664                for (int i = 0; i < after.splitNames.length; i++) {
22665                    final String splitName = after.splitNames[i];
22666                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22667                    if (j != -1) {
22668                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22669                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22670                                    "Update split " + splitName + " revision code "
22671                                    + after.splitRevisionCodes[i] + " is older than current "
22672                                    + before.splitRevisionCodes[j]);
22673                        }
22674                    }
22675                }
22676            }
22677        }
22678    }
22679
22680    private static class MoveCallbacks extends Handler {
22681        private static final int MSG_CREATED = 1;
22682        private static final int MSG_STATUS_CHANGED = 2;
22683
22684        private final RemoteCallbackList<IPackageMoveObserver>
22685                mCallbacks = new RemoteCallbackList<>();
22686
22687        private final SparseIntArray mLastStatus = new SparseIntArray();
22688
22689        public MoveCallbacks(Looper looper) {
22690            super(looper);
22691        }
22692
22693        public void register(IPackageMoveObserver callback) {
22694            mCallbacks.register(callback);
22695        }
22696
22697        public void unregister(IPackageMoveObserver callback) {
22698            mCallbacks.unregister(callback);
22699        }
22700
22701        @Override
22702        public void handleMessage(Message msg) {
22703            final SomeArgs args = (SomeArgs) msg.obj;
22704            final int n = mCallbacks.beginBroadcast();
22705            for (int i = 0; i < n; i++) {
22706                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22707                try {
22708                    invokeCallback(callback, msg.what, args);
22709                } catch (RemoteException ignored) {
22710                }
22711            }
22712            mCallbacks.finishBroadcast();
22713            args.recycle();
22714        }
22715
22716        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22717                throws RemoteException {
22718            switch (what) {
22719                case MSG_CREATED: {
22720                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22721                    break;
22722                }
22723                case MSG_STATUS_CHANGED: {
22724                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22725                    break;
22726                }
22727            }
22728        }
22729
22730        private void notifyCreated(int moveId, Bundle extras) {
22731            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22732
22733            final SomeArgs args = SomeArgs.obtain();
22734            args.argi1 = moveId;
22735            args.arg2 = extras;
22736            obtainMessage(MSG_CREATED, args).sendToTarget();
22737        }
22738
22739        private void notifyStatusChanged(int moveId, int status) {
22740            notifyStatusChanged(moveId, status, -1);
22741        }
22742
22743        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22744            Slog.v(TAG, "Move " + moveId + " status " + status);
22745
22746            final SomeArgs args = SomeArgs.obtain();
22747            args.argi1 = moveId;
22748            args.argi2 = status;
22749            args.arg3 = estMillis;
22750            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22751
22752            synchronized (mLastStatus) {
22753                mLastStatus.put(moveId, status);
22754            }
22755        }
22756    }
22757
22758    private final static class OnPermissionChangeListeners extends Handler {
22759        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22760
22761        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22762                new RemoteCallbackList<>();
22763
22764        public OnPermissionChangeListeners(Looper looper) {
22765            super(looper);
22766        }
22767
22768        @Override
22769        public void handleMessage(Message msg) {
22770            switch (msg.what) {
22771                case MSG_ON_PERMISSIONS_CHANGED: {
22772                    final int uid = msg.arg1;
22773                    handleOnPermissionsChanged(uid);
22774                } break;
22775            }
22776        }
22777
22778        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22779            mPermissionListeners.register(listener);
22780
22781        }
22782
22783        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22784            mPermissionListeners.unregister(listener);
22785        }
22786
22787        public void onPermissionsChanged(int uid) {
22788            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22789                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22790            }
22791        }
22792
22793        private void handleOnPermissionsChanged(int uid) {
22794            final int count = mPermissionListeners.beginBroadcast();
22795            try {
22796                for (int i = 0; i < count; i++) {
22797                    IOnPermissionsChangeListener callback = mPermissionListeners
22798                            .getBroadcastItem(i);
22799                    try {
22800                        callback.onPermissionsChanged(uid);
22801                    } catch (RemoteException e) {
22802                        Log.e(TAG, "Permission listener is dead", e);
22803                    }
22804                }
22805            } finally {
22806                mPermissionListeners.finishBroadcast();
22807            }
22808        }
22809    }
22810
22811    private class PackageManagerInternalImpl extends PackageManagerInternal {
22812        @Override
22813        public void setLocationPackagesProvider(PackagesProvider provider) {
22814            synchronized (mPackages) {
22815                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22816            }
22817        }
22818
22819        @Override
22820        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22821            synchronized (mPackages) {
22822                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22823            }
22824        }
22825
22826        @Override
22827        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22828            synchronized (mPackages) {
22829                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22830            }
22831        }
22832
22833        @Override
22834        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22835            synchronized (mPackages) {
22836                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22837            }
22838        }
22839
22840        @Override
22841        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22842            synchronized (mPackages) {
22843                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22844            }
22845        }
22846
22847        @Override
22848        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22849            synchronized (mPackages) {
22850                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22851            }
22852        }
22853
22854        @Override
22855        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22856            synchronized (mPackages) {
22857                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22858                        packageName, userId);
22859            }
22860        }
22861
22862        @Override
22863        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22864            synchronized (mPackages) {
22865                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22866                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22867                        packageName, userId);
22868            }
22869        }
22870
22871        @Override
22872        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22873            synchronized (mPackages) {
22874                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22875                        packageName, userId);
22876            }
22877        }
22878
22879        @Override
22880        public void setKeepUninstalledPackages(final List<String> packageList) {
22881            Preconditions.checkNotNull(packageList);
22882            List<String> removedFromList = null;
22883            synchronized (mPackages) {
22884                if (mKeepUninstalledPackages != null) {
22885                    final int packagesCount = mKeepUninstalledPackages.size();
22886                    for (int i = 0; i < packagesCount; i++) {
22887                        String oldPackage = mKeepUninstalledPackages.get(i);
22888                        if (packageList != null && packageList.contains(oldPackage)) {
22889                            continue;
22890                        }
22891                        if (removedFromList == null) {
22892                            removedFromList = new ArrayList<>();
22893                        }
22894                        removedFromList.add(oldPackage);
22895                    }
22896                }
22897                mKeepUninstalledPackages = new ArrayList<>(packageList);
22898                if (removedFromList != null) {
22899                    final int removedCount = removedFromList.size();
22900                    for (int i = 0; i < removedCount; i++) {
22901                        deletePackageIfUnusedLPr(removedFromList.get(i));
22902                    }
22903                }
22904            }
22905        }
22906
22907        @Override
22908        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22909            synchronized (mPackages) {
22910                // If we do not support permission review, done.
22911                if (!mPermissionReviewRequired) {
22912                    return false;
22913                }
22914
22915                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22916                if (packageSetting == null) {
22917                    return false;
22918                }
22919
22920                // Permission review applies only to apps not supporting the new permission model.
22921                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22922                    return false;
22923                }
22924
22925                // Legacy apps have the permission and get user consent on launch.
22926                PermissionsState permissionsState = packageSetting.getPermissionsState();
22927                return permissionsState.isPermissionReviewRequired(userId);
22928            }
22929        }
22930
22931        @Override
22932        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22933            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22934        }
22935
22936        @Override
22937        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22938                int userId) {
22939            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22940        }
22941
22942        @Override
22943        public void setDeviceAndProfileOwnerPackages(
22944                int deviceOwnerUserId, String deviceOwnerPackage,
22945                SparseArray<String> profileOwnerPackages) {
22946            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22947                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22948        }
22949
22950        @Override
22951        public boolean isPackageDataProtected(int userId, String packageName) {
22952            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22953        }
22954
22955        @Override
22956        public boolean isPackageEphemeral(int userId, String packageName) {
22957            synchronized (mPackages) {
22958                final PackageSetting ps = mSettings.mPackages.get(packageName);
22959                return ps != null ? ps.getInstantApp(userId) : false;
22960            }
22961        }
22962
22963        @Override
22964        public boolean wasPackageEverLaunched(String packageName, int userId) {
22965            synchronized (mPackages) {
22966                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22967            }
22968        }
22969
22970        @Override
22971        public void grantRuntimePermission(String packageName, String name, int userId,
22972                boolean overridePolicy) {
22973            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22974                    overridePolicy);
22975        }
22976
22977        @Override
22978        public void revokeRuntimePermission(String packageName, String name, int userId,
22979                boolean overridePolicy) {
22980            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22981                    overridePolicy);
22982        }
22983
22984        @Override
22985        public String getNameForUid(int uid) {
22986            return PackageManagerService.this.getNameForUid(uid);
22987        }
22988
22989        @Override
22990        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22991                Intent origIntent, String resolvedType, String callingPackage, int userId) {
22992            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22993                    responseObj, origIntent, resolvedType, callingPackage, userId);
22994        }
22995
22996        @Override
22997        public void grantEphemeralAccess(int userId, Intent intent,
22998                int targetAppId, int ephemeralAppId) {
22999            synchronized (mPackages) {
23000                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23001                        targetAppId, ephemeralAppId);
23002            }
23003        }
23004
23005        @Override
23006        public void pruneInstantApps() {
23007            synchronized (mPackages) {
23008                mInstantAppRegistry.pruneInstantAppsLPw();
23009            }
23010        }
23011
23012        @Override
23013        public String getSetupWizardPackageName() {
23014            return mSetupWizardPackage;
23015        }
23016
23017        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23018            if (policy != null) {
23019                mExternalSourcesPolicy = policy;
23020            }
23021        }
23022
23023        @Override
23024        public boolean isPackagePersistent(String packageName) {
23025            synchronized (mPackages) {
23026                PackageParser.Package pkg = mPackages.get(packageName);
23027                return pkg != null
23028                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23029                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23030                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23031                        : false;
23032            }
23033        }
23034
23035        @Override
23036        public List<PackageInfo> getOverlayPackages(int userId) {
23037            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23038            synchronized (mPackages) {
23039                for (PackageParser.Package p : mPackages.values()) {
23040                    if (p.mOverlayTarget != null) {
23041                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23042                        if (pkg != null) {
23043                            overlayPackages.add(pkg);
23044                        }
23045                    }
23046                }
23047            }
23048            return overlayPackages;
23049        }
23050
23051        @Override
23052        public List<String> getTargetPackageNames(int userId) {
23053            List<String> targetPackages = new ArrayList<>();
23054            synchronized (mPackages) {
23055                for (PackageParser.Package p : mPackages.values()) {
23056                    if (p.mOverlayTarget == null) {
23057                        targetPackages.add(p.packageName);
23058                    }
23059                }
23060            }
23061            return targetPackages;
23062        }
23063
23064        @Override
23065        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23066                @Nullable List<String> overlayPackageNames) {
23067            synchronized (mPackages) {
23068                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23069                    Slog.e(TAG, "failed to find package " + targetPackageName);
23070                    return false;
23071                }
23072
23073                ArrayList<String> paths = null;
23074                if (overlayPackageNames != null) {
23075                    final int N = overlayPackageNames.size();
23076                    paths = new ArrayList<String>(N);
23077                    for (int i = 0; i < N; i++) {
23078                        final String packageName = overlayPackageNames.get(i);
23079                        final PackageParser.Package pkg = mPackages.get(packageName);
23080                        if (pkg == null) {
23081                            Slog.e(TAG, "failed to find package " + packageName);
23082                            return false;
23083                        }
23084                        paths.add(pkg.baseCodePath);
23085                    }
23086                }
23087
23088                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23089                    mEnabledOverlayPaths.get(userId);
23090                if (userSpecificOverlays == null) {
23091                    userSpecificOverlays = new ArrayMap<String, ArrayList<String>>();
23092                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23093                }
23094
23095                if (paths != null && paths.size() > 0) {
23096                    userSpecificOverlays.put(targetPackageName, paths);
23097                } else {
23098                    userSpecificOverlays.remove(targetPackageName);
23099                }
23100                return true;
23101            }
23102        }
23103
23104        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23105                int flags, int userId) {
23106            return resolveIntentInternal(
23107                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23108        }
23109    }
23110
23111    @Override
23112    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23113        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23114        synchronized (mPackages) {
23115            final long identity = Binder.clearCallingIdentity();
23116            try {
23117                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23118                        packageNames, userId);
23119            } finally {
23120                Binder.restoreCallingIdentity(identity);
23121            }
23122        }
23123    }
23124
23125    @Override
23126    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23127        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23128        synchronized (mPackages) {
23129            final long identity = Binder.clearCallingIdentity();
23130            try {
23131                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23132                        packageNames, userId);
23133            } finally {
23134                Binder.restoreCallingIdentity(identity);
23135            }
23136        }
23137    }
23138
23139    private static void enforceSystemOrPhoneCaller(String tag) {
23140        int callingUid = Binder.getCallingUid();
23141        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23142            throw new SecurityException(
23143                    "Cannot call " + tag + " from UID " + callingUid);
23144        }
23145    }
23146
23147    boolean isHistoricalPackageUsageAvailable() {
23148        return mPackageUsage.isHistoricalPackageUsageAvailable();
23149    }
23150
23151    /**
23152     * Return a <b>copy</b> of the collection of packages known to the package manager.
23153     * @return A copy of the values of mPackages.
23154     */
23155    Collection<PackageParser.Package> getPackages() {
23156        synchronized (mPackages) {
23157            return new ArrayList<>(mPackages.values());
23158        }
23159    }
23160
23161    /**
23162     * Logs process start information (including base APK hash) to the security log.
23163     * @hide
23164     */
23165    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23166            String apkFile, int pid) {
23167        if (!SecurityLog.isLoggingEnabled()) {
23168            return;
23169        }
23170        Bundle data = new Bundle();
23171        data.putLong("startTimestamp", System.currentTimeMillis());
23172        data.putString("processName", processName);
23173        data.putInt("uid", uid);
23174        data.putString("seinfo", seinfo);
23175        data.putString("apkFile", apkFile);
23176        data.putInt("pid", pid);
23177        Message msg = mProcessLoggingHandler.obtainMessage(
23178                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23179        msg.setData(data);
23180        mProcessLoggingHandler.sendMessage(msg);
23181    }
23182
23183    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23184        return mCompilerStats.getPackageStats(pkgName);
23185    }
23186
23187    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23188        return getOrCreateCompilerPackageStats(pkg.packageName);
23189    }
23190
23191    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23192        return mCompilerStats.getOrCreatePackageStats(pkgName);
23193    }
23194
23195    public void deleteCompilerPackageStats(String pkgName) {
23196        mCompilerStats.deletePackageStats(pkgName);
23197    }
23198
23199    @Override
23200    public int getInstallReason(String packageName, int userId) {
23201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23202                true /* requireFullPermission */, false /* checkShell */,
23203                "get install reason");
23204        synchronized (mPackages) {
23205            final PackageSetting ps = mSettings.mPackages.get(packageName);
23206            if (ps != null) {
23207                return ps.getInstallReason(userId);
23208            }
23209        }
23210        return PackageManager.INSTALL_REASON_UNKNOWN;
23211    }
23212
23213    @Override
23214    public boolean canRequestPackageInstalls(String packageName, int userId) {
23215        int callingUid = Binder.getCallingUid();
23216        int uid = getPackageUid(packageName, 0, userId);
23217        if (callingUid != uid && callingUid != Process.ROOT_UID
23218                && callingUid != Process.SYSTEM_UID) {
23219            throw new SecurityException(
23220                    "Caller uid " + callingUid + " does not own package " + packageName);
23221        }
23222        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23223        if (info == null) {
23224            return false;
23225        }
23226        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23227            throw new UnsupportedOperationException(
23228                    "Operation only supported on apps targeting Android O or higher");
23229        }
23230        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23231        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23232        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23233            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23234        }
23235        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23236            return false;
23237        }
23238        if (mExternalSourcesPolicy != null) {
23239            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23240            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23241                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23242            }
23243        }
23244        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23245    }
23246}
23247