PackageManagerService.java revision aaee062899d41513840fd11fe2df73604ceb80ea
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppInfo;
132import android.content.pm.EphemeralRequest;
133import android.content.pm.EphemeralResolveInfo;
134import android.content.pm.AuxiliaryResolveInfo;
135import android.content.pm.FallbackCategoryProvider;
136import android.content.pm.FeatureInfo;
137import android.content.pm.IOnPermissionsChangeListener;
138import android.content.pm.IPackageDataObserver;
139import android.content.pm.IPackageDeleteObserver;
140import android.content.pm.IPackageDeleteObserver2;
141import android.content.pm.IPackageInstallObserver2;
142import android.content.pm.IPackageInstaller;
143import android.content.pm.IPackageManager;
144import android.content.pm.IPackageMoveObserver;
145import android.content.pm.IPackageStatsObserver;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManagerInternal;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.view.Display;
239
240import com.android.internal.R;
241import com.android.internal.annotations.GuardedBy;
242import com.android.internal.app.IMediaContainerService;
243import com.android.internal.app.ResolverActivity;
244import com.android.internal.content.NativeLibraryHelper;
245import com.android.internal.content.PackageHelper;
246import com.android.internal.logging.MetricsLogger;
247import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
248import com.android.internal.os.IParcelFileDescriptorFactory;
249import com.android.internal.os.RoSystemProperties;
250import com.android.internal.os.SomeArgs;
251import com.android.internal.os.Zygote;
252import com.android.internal.telephony.CarrierAppUtils;
253import com.android.internal.util.ArrayUtils;
254import com.android.internal.util.ConcurrentUtils;
255import com.android.internal.util.FastPrintWriter;
256import com.android.internal.util.FastXmlSerializer;
257import com.android.internal.util.IndentingPrintWriter;
258import com.android.internal.util.Preconditions;
259import com.android.internal.util.XmlUtils;
260import com.android.server.AttributeCache;
261import com.android.server.BackgroundDexOptJobService;
262import com.android.server.DeviceIdleController;
263import com.android.server.EventLogTags;
264import com.android.server.FgThread;
265import com.android.server.IntentResolver;
266import com.android.server.LocalServices;
267import com.android.server.ServiceThread;
268import com.android.server.SystemConfig;
269import com.android.server.SystemServerInitThreadPool;
270import com.android.server.Watchdog;
271import com.android.server.net.NetworkPolicyManagerInternal;
272import com.android.server.pm.Installer.InstallerException;
273import com.android.server.pm.PermissionsState.PermissionState;
274import com.android.server.pm.Settings.DatabaseVersion;
275import com.android.server.pm.Settings.VersionInfo;
276import com.android.server.pm.dex.DexManager;
277import com.android.server.storage.DeviceStorageMonitorInternal;
278
279import dalvik.system.CloseGuard;
280import dalvik.system.DexFile;
281import dalvik.system.VMRuntime;
282
283import libcore.io.IoUtils;
284import libcore.util.EmptyArray;
285
286import org.xmlpull.v1.XmlPullParser;
287import org.xmlpull.v1.XmlPullParserException;
288import org.xmlpull.v1.XmlSerializer;
289
290import java.io.BufferedOutputStream;
291import java.io.BufferedReader;
292import java.io.ByteArrayInputStream;
293import java.io.ByteArrayOutputStream;
294import java.io.File;
295import java.io.FileDescriptor;
296import java.io.FileInputStream;
297import java.io.FileNotFoundException;
298import java.io.FileOutputStream;
299import java.io.FileReader;
300import java.io.FilenameFilter;
301import java.io.IOException;
302import java.io.PrintWriter;
303import java.nio.charset.StandardCharsets;
304import java.security.DigestInputStream;
305import java.security.MessageDigest;
306import java.security.NoSuchAlgorithmException;
307import java.security.PublicKey;
308import java.security.SecureRandom;
309import java.security.cert.Certificate;
310import java.security.cert.CertificateEncodingException;
311import java.security.cert.CertificateException;
312import java.text.SimpleDateFormat;
313import java.util.ArrayList;
314import java.util.Arrays;
315import java.util.Collection;
316import java.util.Collections;
317import java.util.Comparator;
318import java.util.Date;
319import java.util.HashSet;
320import java.util.HashMap;
321import java.util.Iterator;
322import java.util.List;
323import java.util.Map;
324import java.util.Objects;
325import java.util.Set;
326import java.util.concurrent.CountDownLatch;
327import java.util.concurrent.Future;
328import java.util.concurrent.TimeUnit;
329import java.util.concurrent.atomic.AtomicBoolean;
330import java.util.concurrent.atomic.AtomicInteger;
331
332/**
333 * Keep track of all those APKs everywhere.
334 * <p>
335 * Internally there are two important locks:
336 * <ul>
337 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
338 * and other related state. It is a fine-grained lock that should only be held
339 * momentarily, as it's one of the most contended locks in the system.
340 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
341 * operations typically involve heavy lifting of application data on disk. Since
342 * {@code installd} is single-threaded, and it's operations can often be slow,
343 * this lock should never be acquired while already holding {@link #mPackages}.
344 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
345 * holding {@link #mInstallLock}.
346 * </ul>
347 * Many internal methods rely on the caller to hold the appropriate locks, and
348 * this contract is expressed through method name suffixes:
349 * <ul>
350 * <li>fooLI(): the caller must hold {@link #mInstallLock}
351 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
352 * being modified must be frozen
353 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
354 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
355 * </ul>
356 * <p>
357 * Because this class is very central to the platform's security; please run all
358 * CTS and unit tests whenever making modifications:
359 *
360 * <pre>
361 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
362 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
363 * </pre>
364 */
365public class PackageManagerService extends IPackageManager.Stub {
366    static final String TAG = "PackageManager";
367    static final boolean DEBUG_SETTINGS = false;
368    static final boolean DEBUG_PREFERRED = false;
369    static final boolean DEBUG_UPGRADE = false;
370    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
371    private static final boolean DEBUG_BACKUP = false;
372    private static final boolean DEBUG_INSTALL = false;
373    private static final boolean DEBUG_REMOVE = false;
374    private static final boolean DEBUG_BROADCASTS = false;
375    private static final boolean DEBUG_SHOW_INFO = false;
376    private static final boolean DEBUG_PACKAGE_INFO = false;
377    private static final boolean DEBUG_INTENT_MATCHING = false;
378    private static final boolean DEBUG_PACKAGE_SCANNING = false;
379    private static final boolean DEBUG_VERIFY = false;
380    private static final boolean DEBUG_FILTERS = false;
381
382    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
383    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
384    // user, but by default initialize to this.
385    public static final boolean DEBUG_DEXOPT = false;
386
387    private static final boolean DEBUG_ABI_SELECTION = false;
388    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
389    private static final boolean DEBUG_TRIAGED_MISSING = false;
390    private static final boolean DEBUG_APP_DATA = false;
391
392    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
393    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
394
395    private static final boolean DISABLE_EPHEMERAL_APPS = false;
396    private static final boolean HIDE_EPHEMERAL_APIS = false;
397
398    private static final boolean ENABLE_FREE_CACHE_V2 =
399            SystemProperties.getBoolean("fw.free_cache_v2", false);
400
401    private static final int RADIO_UID = Process.PHONE_UID;
402    private static final int LOG_UID = Process.LOG_UID;
403    private static final int NFC_UID = Process.NFC_UID;
404    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
405    private static final int SHELL_UID = Process.SHELL_UID;
406
407    // Cap the size of permission trees that 3rd party apps can define
408    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
409
410    // Suffix used during package installation when copying/moving
411    // package apks to install directory.
412    private static final String INSTALL_PACKAGE_SUFFIX = "-";
413
414    static final int SCAN_NO_DEX = 1<<1;
415    static final int SCAN_FORCE_DEX = 1<<2;
416    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
417    static final int SCAN_NEW_INSTALL = 1<<4;
418    static final int SCAN_UPDATE_TIME = 1<<5;
419    static final int SCAN_BOOTING = 1<<6;
420    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
421    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
422    static final int SCAN_REPLACING = 1<<9;
423    static final int SCAN_REQUIRE_KNOWN = 1<<10;
424    static final int SCAN_MOVE = 1<<11;
425    static final int SCAN_INITIAL = 1<<12;
426    static final int SCAN_CHECK_ONLY = 1<<13;
427    static final int SCAN_DONT_KILL_APP = 1<<14;
428    static final int SCAN_IGNORE_FROZEN = 1<<15;
429    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
430    static final int SCAN_AS_INSTANT_APP = 1<<17;
431    static final int SCAN_AS_FULL_APP = 1<<18;
432    /** Should not be with the scan flags */
433    static final int FLAGS_REMOVE_CHATTY = 1<<31;
434
435    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
436
437    private static final int[] EMPTY_INT_ARRAY = new int[0];
438
439    /**
440     * Timeout (in milliseconds) after which the watchdog should declare that
441     * our handler thread is wedged.  The usual default for such things is one
442     * minute but we sometimes do very lengthy I/O operations on this thread,
443     * such as installing multi-gigabyte applications, so ours needs to be longer.
444     */
445    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
446
447    /**
448     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
449     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
450     * settings entry if available, otherwise we use the hardcoded default.  If it's been
451     * more than this long since the last fstrim, we force one during the boot sequence.
452     *
453     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
454     * one gets run at the next available charging+idle time.  This final mandatory
455     * no-fstrim check kicks in only of the other scheduling criteria is never met.
456     */
457    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
458
459    /**
460     * Whether verification is enabled by default.
461     */
462    private static final boolean DEFAULT_VERIFY_ENABLE = true;
463
464    /**
465     * The default maximum time to wait for the verification agent to return in
466     * milliseconds.
467     */
468    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
469
470    /**
471     * The default response for package verification timeout.
472     *
473     * This can be either PackageManager.VERIFICATION_ALLOW or
474     * PackageManager.VERIFICATION_REJECT.
475     */
476    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
477
478    static final String PLATFORM_PACKAGE_NAME = "android";
479
480    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
481
482    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
483            DEFAULT_CONTAINER_PACKAGE,
484            "com.android.defcontainer.DefaultContainerService");
485
486    private static final String KILL_APP_REASON_GIDS_CHANGED =
487            "permission grant or revoke changed gids";
488
489    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
490            "permissions revoked";
491
492    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
493
494    private static final String PACKAGE_SCHEME = "package";
495
496    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
497    /**
498     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
499     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
500     * VENDOR_OVERLAY_DIR.
501     */
502    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
503    /**
504     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
505     * is in VENDOR_OVERLAY_THEME_PROPERTY.
506     */
507    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
508            = "persist.vendor.overlay.theme";
509
510    /** Permission grant: not grant the permission. */
511    private static final int GRANT_DENIED = 1;
512
513    /** Permission grant: grant the permission as an install permission. */
514    private static final int GRANT_INSTALL = 2;
515
516    /** Permission grant: grant the permission as a runtime one. */
517    private static final int GRANT_RUNTIME = 3;
518
519    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
520    private static final int GRANT_UPGRADE = 4;
521
522    /** Canonical intent used to identify what counts as a "web browser" app */
523    private static final Intent sBrowserIntent;
524    static {
525        sBrowserIntent = new Intent();
526        sBrowserIntent.setAction(Intent.ACTION_VIEW);
527        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
528        sBrowserIntent.setData(Uri.parse("http:"));
529    }
530
531    /**
532     * The set of all protected actions [i.e. those actions for which a high priority
533     * intent filter is disallowed].
534     */
535    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
536    static {
537        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
538        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
539        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
540        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
541    }
542
543    // Compilation reasons.
544    public static final int REASON_FIRST_BOOT = 0;
545    public static final int REASON_BOOT = 1;
546    public static final int REASON_INSTALL = 2;
547    public static final int REASON_BACKGROUND_DEXOPT = 3;
548    public static final int REASON_AB_OTA = 4;
549    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
550    public static final int REASON_SHARED_APK = 6;
551    public static final int REASON_FORCED_DEXOPT = 7;
552    public static final int REASON_CORE_APP = 8;
553
554    public static final int REASON_LAST = REASON_CORE_APP;
555
556    /** All dangerous permission names in the same order as the events in MetricsEvent */
557    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
558            Manifest.permission.READ_CALENDAR,
559            Manifest.permission.WRITE_CALENDAR,
560            Manifest.permission.CAMERA,
561            Manifest.permission.READ_CONTACTS,
562            Manifest.permission.WRITE_CONTACTS,
563            Manifest.permission.GET_ACCOUNTS,
564            Manifest.permission.ACCESS_FINE_LOCATION,
565            Manifest.permission.ACCESS_COARSE_LOCATION,
566            Manifest.permission.RECORD_AUDIO,
567            Manifest.permission.READ_PHONE_STATE,
568            Manifest.permission.CALL_PHONE,
569            Manifest.permission.READ_CALL_LOG,
570            Manifest.permission.WRITE_CALL_LOG,
571            Manifest.permission.ADD_VOICEMAIL,
572            Manifest.permission.USE_SIP,
573            Manifest.permission.PROCESS_OUTGOING_CALLS,
574            Manifest.permission.READ_CELL_BROADCASTS,
575            Manifest.permission.BODY_SENSORS,
576            Manifest.permission.SEND_SMS,
577            Manifest.permission.RECEIVE_SMS,
578            Manifest.permission.READ_SMS,
579            Manifest.permission.RECEIVE_WAP_PUSH,
580            Manifest.permission.RECEIVE_MMS,
581            Manifest.permission.READ_EXTERNAL_STORAGE,
582            Manifest.permission.WRITE_EXTERNAL_STORAGE,
583            Manifest.permission.READ_PHONE_NUMBER);
584
585
586    /**
587     * Version number for the package parser cache. Increment this whenever the format or
588     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
589     */
590    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
591
592    /**
593     * Whether the package parser cache is enabled.
594     */
595    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
596
597    final ServiceThread mHandlerThread;
598
599    final PackageHandler mHandler;
600
601    private final ProcessLoggingHandler mProcessLoggingHandler;
602
603    /**
604     * Messages for {@link #mHandler} that need to wait for system ready before
605     * being dispatched.
606     */
607    private ArrayList<Message> mPostSystemReadyMessages;
608
609    final int mSdkVersion = Build.VERSION.SDK_INT;
610
611    final Context mContext;
612    final boolean mFactoryTest;
613    final boolean mOnlyCore;
614    final DisplayMetrics mMetrics;
615    final int mDefParseFlags;
616    final String[] mSeparateProcesses;
617    final boolean mIsUpgrade;
618    final boolean mIsPreNUpgrade;
619    final boolean mIsPreNMR1Upgrade;
620
621    @GuardedBy("mPackages")
622    private boolean mDexOptDialogShown;
623
624    /** The location for ASEC container files on internal storage. */
625    final String mAsecInternalPath;
626
627    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
628    // LOCK HELD.  Can be called with mInstallLock held.
629    @GuardedBy("mInstallLock")
630    final Installer mInstaller;
631
632    /** Directory where installed third-party apps stored */
633    final File mAppInstallDir;
634
635    /**
636     * Directory to which applications installed internally have their
637     * 32 bit native libraries copied.
638     */
639    private File mAppLib32InstallDir;
640
641    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
642    // apps.
643    final File mDrmAppPrivateInstallDir;
644
645    // ----------------------------------------------------------------
646
647    // Lock for state used when installing and doing other long running
648    // operations.  Methods that must be called with this lock held have
649    // the suffix "LI".
650    final Object mInstallLock = new Object();
651
652    // ----------------------------------------------------------------
653
654    // Keys are String (package name), values are Package.  This also serves
655    // as the lock for the global state.  Methods that must be called with
656    // this lock held have the prefix "LP".
657    @GuardedBy("mPackages")
658    final ArrayMap<String, PackageParser.Package> mPackages =
659            new ArrayMap<String, PackageParser.Package>();
660
661    final ArrayMap<String, Set<String>> mKnownCodebase =
662            new ArrayMap<String, Set<String>>();
663
664    // List of APK paths to load for each user and package. This data is never
665    // persisted by the package manager. Instead, the overlay manager will
666    // ensure the data is up-to-date in runtime.
667    @GuardedBy("mPackages")
668    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
669        new SparseArray<ArrayMap<String, ArrayList<String>>>();
670
671    /**
672     * Tracks new system packages [received in an OTA] that we expect to
673     * find updated user-installed versions. Keys are package name, values
674     * are package location.
675     */
676    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
677    /**
678     * Tracks high priority intent filters for protected actions. During boot, certain
679     * filter actions are protected and should never be allowed to have a high priority
680     * intent filter for them. However, there is one, and only one exception -- the
681     * setup wizard. It must be able to define a high priority intent filter for these
682     * actions to ensure there are no escapes from the wizard. We need to delay processing
683     * of these during boot as we need to look at all of the system packages in order
684     * to know which component is the setup wizard.
685     */
686    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
687    /**
688     * Whether or not processing protected filters should be deferred.
689     */
690    private boolean mDeferProtectedFilters = true;
691
692    /**
693     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
694     */
695    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
696    /**
697     * Whether or not system app permissions should be promoted from install to runtime.
698     */
699    boolean mPromoteSystemApps;
700
701    @GuardedBy("mPackages")
702    final Settings mSettings;
703
704    /**
705     * Set of package names that are currently "frozen", which means active
706     * surgery is being done on the code/data for that package. The platform
707     * will refuse to launch frozen packages to avoid race conditions.
708     *
709     * @see PackageFreezer
710     */
711    @GuardedBy("mPackages")
712    final ArraySet<String> mFrozenPackages = new ArraySet<>();
713
714    final ProtectedPackages mProtectedPackages;
715
716    boolean mFirstBoot;
717
718    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
719
720    // System configuration read by SystemConfig.
721    final int[] mGlobalGids;
722    final SparseArray<ArraySet<String>> mSystemPermissions;
723    @GuardedBy("mAvailableFeatures")
724    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
725
726    // If mac_permissions.xml was found for seinfo labeling.
727    boolean mFoundPolicyFile;
728
729    private final InstantAppRegistry mInstantAppRegistry;
730
731    @GuardedBy("mPackages")
732    int mChangedPackagesSequenceNumber;
733    /**
734     * List of changed [installed, removed or updated] packages.
735     * mapping from user id -> sequence number -> package name
736     */
737    @GuardedBy("mPackages")
738    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
739    /**
740     * The sequence number of the last change to a package.
741     * mapping from user id -> package name -> sequence number
742     */
743    @GuardedBy("mPackages")
744    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
745
746    public static final class SharedLibraryEntry {
747        public final String path;
748        public final String apk;
749        public final SharedLibraryInfo info;
750
751        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
752                String declaringPackageName, int declaringPackageVersionCode) {
753            path = _path;
754            apk = _apk;
755            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
756                    declaringPackageName, declaringPackageVersionCode), null);
757        }
758    }
759
760    // Currently known shared libraries.
761    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
762    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
763            new ArrayMap<>();
764
765    // All available activities, for your resolving pleasure.
766    final ActivityIntentResolver mActivities =
767            new ActivityIntentResolver();
768
769    // All available receivers, for your resolving pleasure.
770    final ActivityIntentResolver mReceivers =
771            new ActivityIntentResolver();
772
773    // All available services, for your resolving pleasure.
774    final ServiceIntentResolver mServices = new ServiceIntentResolver();
775
776    // All available providers, for your resolving pleasure.
777    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
778
779    // Mapping from provider base names (first directory in content URI codePath)
780    // to the provider information.
781    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
782            new ArrayMap<String, PackageParser.Provider>();
783
784    // Mapping from instrumentation class names to info about them.
785    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
786            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
787
788    // Mapping from permission names to info about them.
789    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
790            new ArrayMap<String, PackageParser.PermissionGroup>();
791
792    // Packages whose data we have transfered into another package, thus
793    // should no longer exist.
794    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
795
796    // Broadcast actions that are only available to the system.
797    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
798
799    /** List of packages waiting for verification. */
800    final SparseArray<PackageVerificationState> mPendingVerification
801            = new SparseArray<PackageVerificationState>();
802
803    /** Set of packages associated with each app op permission. */
804    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
805
806    final PackageInstallerService mInstallerService;
807
808    private final PackageDexOptimizer mPackageDexOptimizer;
809    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
810    // is used by other apps).
811    private final DexManager mDexManager;
812
813    private AtomicInteger mNextMoveId = new AtomicInteger();
814    private final MoveCallbacks mMoveCallbacks;
815
816    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
817
818    // Cache of users who need badging.
819    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
820
821    /** Token for keys in mPendingVerification. */
822    private int mPendingVerificationToken = 0;
823
824    volatile boolean mSystemReady;
825    volatile boolean mSafeMode;
826    volatile boolean mHasSystemUidErrors;
827
828    ApplicationInfo mAndroidApplication;
829    final ActivityInfo mResolveActivity = new ActivityInfo();
830    final ResolveInfo mResolveInfo = new ResolveInfo();
831    ComponentName mResolveComponentName;
832    PackageParser.Package mPlatformPackage;
833    ComponentName mCustomResolverComponentName;
834
835    boolean mResolverReplaced = false;
836
837    private final @Nullable ComponentName mIntentFilterVerifierComponent;
838    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
839
840    private int mIntentFilterVerificationToken = 0;
841
842    /** The service connection to the ephemeral resolver */
843    final EphemeralResolverConnection mInstantAppResolverConnection;
844
845    /** Component used to install ephemeral applications */
846    ComponentName mInstantAppInstallerComponent;
847    final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo();
848    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
849
850    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
851            = new SparseArray<IntentFilterVerificationState>();
852
853    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
854
855    // List of packages names to keep cached, even if they are uninstalled for all users
856    private List<String> mKeepUninstalledPackages;
857
858    private UserManagerInternal mUserManagerInternal;
859
860    private DeviceIdleController.LocalService mDeviceIdleController;
861
862    private File mCacheDir;
863
864    private ArraySet<String> mPrivappPermissionsViolations;
865
866    private Future<?> mPrepareAppDataFuture;
867
868    private static class IFVerificationParams {
869        PackageParser.Package pkg;
870        boolean replacing;
871        int userId;
872        int verifierUid;
873
874        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
875                int _userId, int _verifierUid) {
876            pkg = _pkg;
877            replacing = _replacing;
878            userId = _userId;
879            replacing = _replacing;
880            verifierUid = _verifierUid;
881        }
882    }
883
884    private interface IntentFilterVerifier<T extends IntentFilter> {
885        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
886                                               T filter, String packageName);
887        void startVerifications(int userId);
888        void receiveVerificationResponse(int verificationId);
889    }
890
891    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
892        private Context mContext;
893        private ComponentName mIntentFilterVerifierComponent;
894        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
895
896        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
897            mContext = context;
898            mIntentFilterVerifierComponent = verifierComponent;
899        }
900
901        private String getDefaultScheme() {
902            return IntentFilter.SCHEME_HTTPS;
903        }
904
905        @Override
906        public void startVerifications(int userId) {
907            // Launch verifications requests
908            int count = mCurrentIntentFilterVerifications.size();
909            for (int n=0; n<count; n++) {
910                int verificationId = mCurrentIntentFilterVerifications.get(n);
911                final IntentFilterVerificationState ivs =
912                        mIntentFilterVerificationStates.get(verificationId);
913
914                String packageName = ivs.getPackageName();
915
916                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
917                final int filterCount = filters.size();
918                ArraySet<String> domainsSet = new ArraySet<>();
919                for (int m=0; m<filterCount; m++) {
920                    PackageParser.ActivityIntentInfo filter = filters.get(m);
921                    domainsSet.addAll(filter.getHostsList());
922                }
923                synchronized (mPackages) {
924                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
925                            packageName, domainsSet) != null) {
926                        scheduleWriteSettingsLocked();
927                    }
928                }
929                sendVerificationRequest(userId, verificationId, ivs);
930            }
931            mCurrentIntentFilterVerifications.clear();
932        }
933
934        private void sendVerificationRequest(int userId, int verificationId,
935                IntentFilterVerificationState ivs) {
936
937            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
938            verificationIntent.putExtra(
939                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
940                    verificationId);
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
943                    getDefaultScheme());
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
946                    ivs.getHostsString());
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
949                    ivs.getPackageName());
950            verificationIntent.setComponent(mIntentFilterVerifierComponent);
951            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
952
953            UserHandle user = new UserHandle(userId);
954            mContext.sendBroadcastAsUser(verificationIntent, user);
955            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
956                    "Sending IntentFilter verification broadcast");
957        }
958
959        public void receiveVerificationResponse(int verificationId) {
960            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
961
962            final boolean verified = ivs.isVerified();
963
964            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
965            final int count = filters.size();
966            if (DEBUG_DOMAIN_VERIFICATION) {
967                Slog.i(TAG, "Received verification response " + verificationId
968                        + " for " + count + " filters, verified=" + verified);
969            }
970            for (int n=0; n<count; n++) {
971                PackageParser.ActivityIntentInfo filter = filters.get(n);
972                filter.setVerified(verified);
973
974                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
975                        + " verified with result:" + verified + " and hosts:"
976                        + ivs.getHostsString());
977            }
978
979            mIntentFilterVerificationStates.remove(verificationId);
980
981            final String packageName = ivs.getPackageName();
982            IntentFilterVerificationInfo ivi = null;
983
984            synchronized (mPackages) {
985                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
986            }
987            if (ivi == null) {
988                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
989                        + verificationId + " packageName:" + packageName);
990                return;
991            }
992            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
993                    "Updating IntentFilterVerificationInfo for package " + packageName
994                            +" verificationId:" + verificationId);
995
996            synchronized (mPackages) {
997                if (verified) {
998                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
999                } else {
1000                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1001                }
1002                scheduleWriteSettingsLocked();
1003
1004                final int userId = ivs.getUserId();
1005                if (userId != UserHandle.USER_ALL) {
1006                    final int userStatus =
1007                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1008
1009                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1010                    boolean needUpdate = false;
1011
1012                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1013                    // already been set by the User thru the Disambiguation dialog
1014                    switch (userStatus) {
1015                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1016                            if (verified) {
1017                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1018                            } else {
1019                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1020                            }
1021                            needUpdate = true;
1022                            break;
1023
1024                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1025                            if (verified) {
1026                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1027                                needUpdate = true;
1028                            }
1029                            break;
1030
1031                        default:
1032                            // Nothing to do
1033                    }
1034
1035                    if (needUpdate) {
1036                        mSettings.updateIntentFilterVerificationStatusLPw(
1037                                packageName, updatedStatus, userId);
1038                        scheduleWritePackageRestrictionsLocked(userId);
1039                    }
1040                }
1041            }
1042        }
1043
1044        @Override
1045        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1046                    ActivityIntentInfo filter, String packageName) {
1047            if (!hasValidDomains(filter)) {
1048                return false;
1049            }
1050            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1051            if (ivs == null) {
1052                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1053                        packageName);
1054            }
1055            if (DEBUG_DOMAIN_VERIFICATION) {
1056                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1057            }
1058            ivs.addFilter(filter);
1059            return true;
1060        }
1061
1062        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1063                int userId, int verificationId, String packageName) {
1064            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1065                    verifierUid, userId, packageName);
1066            ivs.setPendingState();
1067            synchronized (mPackages) {
1068                mIntentFilterVerificationStates.append(verificationId, ivs);
1069                mCurrentIntentFilterVerifications.add(verificationId);
1070            }
1071            return ivs;
1072        }
1073    }
1074
1075    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1076        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1077                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1078                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1079    }
1080
1081    // Set of pending broadcasts for aggregating enable/disable of components.
1082    static class PendingPackageBroadcasts {
1083        // for each user id, a map of <package name -> components within that package>
1084        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1085
1086        public PendingPackageBroadcasts() {
1087            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1088        }
1089
1090        public ArrayList<String> get(int userId, String packageName) {
1091            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1092            return packages.get(packageName);
1093        }
1094
1095        public void put(int userId, String packageName, ArrayList<String> components) {
1096            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1097            packages.put(packageName, components);
1098        }
1099
1100        public void remove(int userId, String packageName) {
1101            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1102            if (packages != null) {
1103                packages.remove(packageName);
1104            }
1105        }
1106
1107        public void remove(int userId) {
1108            mUidMap.remove(userId);
1109        }
1110
1111        public int userIdCount() {
1112            return mUidMap.size();
1113        }
1114
1115        public int userIdAt(int n) {
1116            return mUidMap.keyAt(n);
1117        }
1118
1119        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1120            return mUidMap.get(userId);
1121        }
1122
1123        public int size() {
1124            // total number of pending broadcast entries across all userIds
1125            int num = 0;
1126            for (int i = 0; i< mUidMap.size(); i++) {
1127                num += mUidMap.valueAt(i).size();
1128            }
1129            return num;
1130        }
1131
1132        public void clear() {
1133            mUidMap.clear();
1134        }
1135
1136        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1137            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1138            if (map == null) {
1139                map = new ArrayMap<String, ArrayList<String>>();
1140                mUidMap.put(userId, map);
1141            }
1142            return map;
1143        }
1144    }
1145    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1146
1147    // Service Connection to remote media container service to copy
1148    // package uri's from external media onto secure containers
1149    // or internal storage.
1150    private IMediaContainerService mContainerService = null;
1151
1152    static final int SEND_PENDING_BROADCAST = 1;
1153    static final int MCS_BOUND = 3;
1154    static final int END_COPY = 4;
1155    static final int INIT_COPY = 5;
1156    static final int MCS_UNBIND = 6;
1157    static final int START_CLEANING_PACKAGE = 7;
1158    static final int FIND_INSTALL_LOC = 8;
1159    static final int POST_INSTALL = 9;
1160    static final int MCS_RECONNECT = 10;
1161    static final int MCS_GIVE_UP = 11;
1162    static final int UPDATED_MEDIA_STATUS = 12;
1163    static final int WRITE_SETTINGS = 13;
1164    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1165    static final int PACKAGE_VERIFIED = 15;
1166    static final int CHECK_PENDING_VERIFICATION = 16;
1167    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1168    static final int INTENT_FILTER_VERIFIED = 18;
1169    static final int WRITE_PACKAGE_LIST = 19;
1170    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1171
1172    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1173
1174    // Delay time in millisecs
1175    static final int BROADCAST_DELAY = 10 * 1000;
1176
1177    static UserManagerService sUserManager;
1178
1179    // Stores a list of users whose package restrictions file needs to be updated
1180    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1181
1182    final private DefaultContainerConnection mDefContainerConn =
1183            new DefaultContainerConnection();
1184    class DefaultContainerConnection implements ServiceConnection {
1185        public void onServiceConnected(ComponentName name, IBinder service) {
1186            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1187            final IMediaContainerService imcs = IMediaContainerService.Stub
1188                    .asInterface(Binder.allowBlocking(service));
1189            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1190        }
1191
1192        public void onServiceDisconnected(ComponentName name) {
1193            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1194        }
1195    }
1196
1197    // Recordkeeping of restore-after-install operations that are currently in flight
1198    // between the Package Manager and the Backup Manager
1199    static class PostInstallData {
1200        public InstallArgs args;
1201        public PackageInstalledInfo res;
1202
1203        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1204            args = _a;
1205            res = _r;
1206        }
1207    }
1208
1209    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1210    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1211
1212    // XML tags for backup/restore of various bits of state
1213    private static final String TAG_PREFERRED_BACKUP = "pa";
1214    private static final String TAG_DEFAULT_APPS = "da";
1215    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1216
1217    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1218    private static final String TAG_ALL_GRANTS = "rt-grants";
1219    private static final String TAG_GRANT = "grant";
1220    private static final String ATTR_PACKAGE_NAME = "pkg";
1221
1222    private static final String TAG_PERMISSION = "perm";
1223    private static final String ATTR_PERMISSION_NAME = "name";
1224    private static final String ATTR_IS_GRANTED = "g";
1225    private static final String ATTR_USER_SET = "set";
1226    private static final String ATTR_USER_FIXED = "fixed";
1227    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1228
1229    // System/policy permission grants are not backed up
1230    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1231            FLAG_PERMISSION_POLICY_FIXED
1232            | FLAG_PERMISSION_SYSTEM_FIXED
1233            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1234
1235    // And we back up these user-adjusted states
1236    private static final int USER_RUNTIME_GRANT_MASK =
1237            FLAG_PERMISSION_USER_SET
1238            | FLAG_PERMISSION_USER_FIXED
1239            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1240
1241    final @Nullable String mRequiredVerifierPackage;
1242    final @NonNull String mRequiredInstallerPackage;
1243    final @NonNull String mRequiredUninstallerPackage;
1244    final @Nullable String mSetupWizardPackage;
1245    final @Nullable String mStorageManagerPackage;
1246    final @NonNull String mServicesSystemSharedLibraryPackageName;
1247    final @NonNull String mSharedSystemSharedLibraryPackageName;
1248
1249    final boolean mPermissionReviewRequired;
1250
1251    private final PackageUsage mPackageUsage = new PackageUsage();
1252    private final CompilerStats mCompilerStats = new CompilerStats();
1253
1254    class PackageHandler extends Handler {
1255        private boolean mBound = false;
1256        final ArrayList<HandlerParams> mPendingInstalls =
1257            new ArrayList<HandlerParams>();
1258
1259        private boolean connectToService() {
1260            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1261                    " DefaultContainerService");
1262            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1263            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1264            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1265                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1266                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1267                mBound = true;
1268                return true;
1269            }
1270            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1271            return false;
1272        }
1273
1274        private void disconnectService() {
1275            mContainerService = null;
1276            mBound = false;
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1278            mContext.unbindService(mDefContainerConn);
1279            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1280        }
1281
1282        PackageHandler(Looper looper) {
1283            super(looper);
1284        }
1285
1286        public void handleMessage(Message msg) {
1287            try {
1288                doHandleMessage(msg);
1289            } finally {
1290                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1291            }
1292        }
1293
1294        void doHandleMessage(Message msg) {
1295            switch (msg.what) {
1296                case INIT_COPY: {
1297                    HandlerParams params = (HandlerParams) msg.obj;
1298                    int idx = mPendingInstalls.size();
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1300                    // If a bind was already initiated we dont really
1301                    // need to do anything. The pending install
1302                    // will be processed later on.
1303                    if (!mBound) {
1304                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1305                                System.identityHashCode(mHandler));
1306                        // If this is the only one pending we might
1307                        // have to bind to the service again.
1308                        if (!connectToService()) {
1309                            Slog.e(TAG, "Failed to bind to media container service");
1310                            params.serviceError();
1311                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1312                                    System.identityHashCode(mHandler));
1313                            if (params.traceMethod != null) {
1314                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1315                                        params.traceCookie);
1316                            }
1317                            return;
1318                        } else {
1319                            // Once we bind to the service, the first
1320                            // pending request will be processed.
1321                            mPendingInstalls.add(idx, params);
1322                        }
1323                    } else {
1324                        mPendingInstalls.add(idx, params);
1325                        // Already bound to the service. Just make
1326                        // sure we trigger off processing the first request.
1327                        if (idx == 0) {
1328                            mHandler.sendEmptyMessage(MCS_BOUND);
1329                        }
1330                    }
1331                    break;
1332                }
1333                case MCS_BOUND: {
1334                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1335                    if (msg.obj != null) {
1336                        mContainerService = (IMediaContainerService) msg.obj;
1337                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1338                                System.identityHashCode(mHandler));
1339                    }
1340                    if (mContainerService == null) {
1341                        if (!mBound) {
1342                            // Something seriously wrong since we are not bound and we are not
1343                            // waiting for connection. Bail out.
1344                            Slog.e(TAG, "Cannot bind to media container service");
1345                            for (HandlerParams params : mPendingInstalls) {
1346                                // Indicate service bind error
1347                                params.serviceError();
1348                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1349                                        System.identityHashCode(params));
1350                                if (params.traceMethod != null) {
1351                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1352                                            params.traceMethod, params.traceCookie);
1353                                }
1354                                return;
1355                            }
1356                            mPendingInstalls.clear();
1357                        } else {
1358                            Slog.w(TAG, "Waiting to connect to media container service");
1359                        }
1360                    } else if (mPendingInstalls.size() > 0) {
1361                        HandlerParams params = mPendingInstalls.get(0);
1362                        if (params != null) {
1363                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1364                                    System.identityHashCode(params));
1365                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1366                            if (params.startCopy()) {
1367                                // We are done...  look for more work or to
1368                                // go idle.
1369                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1370                                        "Checking for more work or unbind...");
1371                                // Delete pending install
1372                                if (mPendingInstalls.size() > 0) {
1373                                    mPendingInstalls.remove(0);
1374                                }
1375                                if (mPendingInstalls.size() == 0) {
1376                                    if (mBound) {
1377                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1378                                                "Posting delayed MCS_UNBIND");
1379                                        removeMessages(MCS_UNBIND);
1380                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1381                                        // Unbind after a little delay, to avoid
1382                                        // continual thrashing.
1383                                        sendMessageDelayed(ubmsg, 10000);
1384                                    }
1385                                } else {
1386                                    // There are more pending requests in queue.
1387                                    // Just post MCS_BOUND message to trigger processing
1388                                    // of next pending install.
1389                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1390                                            "Posting MCS_BOUND for next work");
1391                                    mHandler.sendEmptyMessage(MCS_BOUND);
1392                                }
1393                            }
1394                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1395                        }
1396                    } else {
1397                        // Should never happen ideally.
1398                        Slog.w(TAG, "Empty queue");
1399                    }
1400                    break;
1401                }
1402                case MCS_RECONNECT: {
1403                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1404                    if (mPendingInstalls.size() > 0) {
1405                        if (mBound) {
1406                            disconnectService();
1407                        }
1408                        if (!connectToService()) {
1409                            Slog.e(TAG, "Failed to bind to media container service");
1410                            for (HandlerParams params : mPendingInstalls) {
1411                                // Indicate service bind error
1412                                params.serviceError();
1413                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1414                                        System.identityHashCode(params));
1415                            }
1416                            mPendingInstalls.clear();
1417                        }
1418                    }
1419                    break;
1420                }
1421                case MCS_UNBIND: {
1422                    // If there is no actual work left, then time to unbind.
1423                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1424
1425                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1426                        if (mBound) {
1427                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1428
1429                            disconnectService();
1430                        }
1431                    } else if (mPendingInstalls.size() > 0) {
1432                        // There are more pending requests in queue.
1433                        // Just post MCS_BOUND message to trigger processing
1434                        // of next pending install.
1435                        mHandler.sendEmptyMessage(MCS_BOUND);
1436                    }
1437
1438                    break;
1439                }
1440                case MCS_GIVE_UP: {
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1442                    HandlerParams params = mPendingInstalls.remove(0);
1443                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1444                            System.identityHashCode(params));
1445                    break;
1446                }
1447                case SEND_PENDING_BROADCAST: {
1448                    String packages[];
1449                    ArrayList<String> components[];
1450                    int size = 0;
1451                    int uids[];
1452                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1453                    synchronized (mPackages) {
1454                        if (mPendingBroadcasts == null) {
1455                            return;
1456                        }
1457                        size = mPendingBroadcasts.size();
1458                        if (size <= 0) {
1459                            // Nothing to be done. Just return
1460                            return;
1461                        }
1462                        packages = new String[size];
1463                        components = new ArrayList[size];
1464                        uids = new int[size];
1465                        int i = 0;  // filling out the above arrays
1466
1467                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1468                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1469                            Iterator<Map.Entry<String, ArrayList<String>>> it
1470                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1471                                            .entrySet().iterator();
1472                            while (it.hasNext() && i < size) {
1473                                Map.Entry<String, ArrayList<String>> ent = it.next();
1474                                packages[i] = ent.getKey();
1475                                components[i] = ent.getValue();
1476                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1477                                uids[i] = (ps != null)
1478                                        ? UserHandle.getUid(packageUserId, ps.appId)
1479                                        : -1;
1480                                i++;
1481                            }
1482                        }
1483                        size = i;
1484                        mPendingBroadcasts.clear();
1485                    }
1486                    // Send broadcasts
1487                    for (int i = 0; i < size; i++) {
1488                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1489                    }
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1491                    break;
1492                }
1493                case START_CLEANING_PACKAGE: {
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1495                    final String packageName = (String)msg.obj;
1496                    final int userId = msg.arg1;
1497                    final boolean andCode = msg.arg2 != 0;
1498                    synchronized (mPackages) {
1499                        if (userId == UserHandle.USER_ALL) {
1500                            int[] users = sUserManager.getUserIds();
1501                            for (int user : users) {
1502                                mSettings.addPackageToCleanLPw(
1503                                        new PackageCleanItem(user, packageName, andCode));
1504                            }
1505                        } else {
1506                            mSettings.addPackageToCleanLPw(
1507                                    new PackageCleanItem(userId, packageName, andCode));
1508                        }
1509                    }
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1511                    startCleaningPackages();
1512                } break;
1513                case POST_INSTALL: {
1514                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1515
1516                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1517                    final boolean didRestore = (msg.arg2 != 0);
1518                    mRunningInstalls.delete(msg.arg1);
1519
1520                    if (data != null) {
1521                        InstallArgs args = data.args;
1522                        PackageInstalledInfo parentRes = data.res;
1523
1524                        final boolean grantPermissions = (args.installFlags
1525                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1526                        final boolean killApp = (args.installFlags
1527                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1528                        final String[] grantedPermissions = args.installGrantPermissions;
1529
1530                        // Handle the parent package
1531                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1532                                grantedPermissions, didRestore, args.installerPackageName,
1533                                args.observer);
1534
1535                        // Handle the child packages
1536                        final int childCount = (parentRes.addedChildPackages != null)
1537                                ? parentRes.addedChildPackages.size() : 0;
1538                        for (int i = 0; i < childCount; i++) {
1539                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1540                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1541                                    grantedPermissions, false, args.installerPackageName,
1542                                    args.observer);
1543                        }
1544
1545                        // Log tracing if needed
1546                        if (args.traceMethod != null) {
1547                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1548                                    args.traceCookie);
1549                        }
1550                    } else {
1551                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1552                    }
1553
1554                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1555                } break;
1556                case UPDATED_MEDIA_STATUS: {
1557                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1558                    boolean reportStatus = msg.arg1 == 1;
1559                    boolean doGc = msg.arg2 == 1;
1560                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1561                    if (doGc) {
1562                        // Force a gc to clear up stale containers.
1563                        Runtime.getRuntime().gc();
1564                    }
1565                    if (msg.obj != null) {
1566                        @SuppressWarnings("unchecked")
1567                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1568                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1569                        // Unload containers
1570                        unloadAllContainers(args);
1571                    }
1572                    if (reportStatus) {
1573                        try {
1574                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1575                                    "Invoking StorageManagerService call back");
1576                            PackageHelper.getStorageManager().finishMediaUpdate();
1577                        } catch (RemoteException e) {
1578                            Log.e(TAG, "StorageManagerService not running?");
1579                        }
1580                    }
1581                } break;
1582                case WRITE_SETTINGS: {
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1584                    synchronized (mPackages) {
1585                        removeMessages(WRITE_SETTINGS);
1586                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1587                        mSettings.writeLPr();
1588                        mDirtyUsers.clear();
1589                    }
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1591                } break;
1592                case WRITE_PACKAGE_RESTRICTIONS: {
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1596                        for (int userId : mDirtyUsers) {
1597                            mSettings.writePackageRestrictionsLPr(userId);
1598                        }
1599                        mDirtyUsers.clear();
1600                    }
1601                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1602                } break;
1603                case WRITE_PACKAGE_LIST: {
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        removeMessages(WRITE_PACKAGE_LIST);
1607                        mSettings.writePackageListLPr(msg.arg1);
1608                    }
1609                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1610                } break;
1611                case CHECK_PENDING_VERIFICATION: {
1612                    final int verificationId = msg.arg1;
1613                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1614
1615                    if ((state != null) && !state.timeoutExtended()) {
1616                        final InstallArgs args = state.getInstallArgs();
1617                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1618
1619                        Slog.i(TAG, "Verification timed out for " + originUri);
1620                        mPendingVerification.remove(verificationId);
1621
1622                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1623
1624                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1625                            Slog.i(TAG, "Continuing with installation of " + originUri);
1626                            state.setVerifierResponse(Binder.getCallingUid(),
1627                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1628                            broadcastPackageVerified(verificationId, originUri,
1629                                    PackageManager.VERIFICATION_ALLOW,
1630                                    state.getInstallArgs().getUser());
1631                            try {
1632                                ret = args.copyApk(mContainerService, true);
1633                            } catch (RemoteException e) {
1634                                Slog.e(TAG, "Could not contact the ContainerService");
1635                            }
1636                        } else {
1637                            broadcastPackageVerified(verificationId, originUri,
1638                                    PackageManager.VERIFICATION_REJECT,
1639                                    state.getInstallArgs().getUser());
1640                        }
1641
1642                        Trace.asyncTraceEnd(
1643                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1644
1645                        processPendingInstall(args, ret);
1646                        mHandler.sendEmptyMessage(MCS_UNBIND);
1647                    }
1648                    break;
1649                }
1650                case PACKAGE_VERIFIED: {
1651                    final int verificationId = msg.arg1;
1652
1653                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1654                    if (state == null) {
1655                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1656                        break;
1657                    }
1658
1659                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1660
1661                    state.setVerifierResponse(response.callerUid, response.code);
1662
1663                    if (state.isVerificationComplete()) {
1664                        mPendingVerification.remove(verificationId);
1665
1666                        final InstallArgs args = state.getInstallArgs();
1667                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1668
1669                        int ret;
1670                        if (state.isInstallAllowed()) {
1671                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1672                            broadcastPackageVerified(verificationId, originUri,
1673                                    response.code, state.getInstallArgs().getUser());
1674                            try {
1675                                ret = args.copyApk(mContainerService, true);
1676                            } catch (RemoteException e) {
1677                                Slog.e(TAG, "Could not contact the ContainerService");
1678                            }
1679                        } else {
1680                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1681                        }
1682
1683                        Trace.asyncTraceEnd(
1684                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1685
1686                        processPendingInstall(args, ret);
1687                        mHandler.sendEmptyMessage(MCS_UNBIND);
1688                    }
1689
1690                    break;
1691                }
1692                case START_INTENT_FILTER_VERIFICATIONS: {
1693                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1694                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1695                            params.replacing, params.pkg);
1696                    break;
1697                }
1698                case INTENT_FILTER_VERIFIED: {
1699                    final int verificationId = msg.arg1;
1700
1701                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1702                            verificationId);
1703                    if (state == null) {
1704                        Slog.w(TAG, "Invalid IntentFilter verification token "
1705                                + verificationId + " received");
1706                        break;
1707                    }
1708
1709                    final int userId = state.getUserId();
1710
1711                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1712                            "Processing IntentFilter verification with token:"
1713                            + verificationId + " and userId:" + userId);
1714
1715                    final IntentFilterVerificationResponse response =
1716                            (IntentFilterVerificationResponse) msg.obj;
1717
1718                    state.setVerifierResponse(response.callerUid, response.code);
1719
1720                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1721                            "IntentFilter verification with token:" + verificationId
1722                            + " and userId:" + userId
1723                            + " is settings verifier response with response code:"
1724                            + response.code);
1725
1726                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1727                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1728                                + response.getFailedDomainsString());
1729                    }
1730
1731                    if (state.isVerificationComplete()) {
1732                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1733                    } else {
1734                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1735                                "IntentFilter verification with token:" + verificationId
1736                                + " was not said to be complete");
1737                    }
1738
1739                    break;
1740                }
1741                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1742                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1743                            mInstantAppResolverConnection,
1744                            (EphemeralRequest) msg.obj,
1745                            mInstantAppInstallerActivity,
1746                            mHandler);
1747                }
1748            }
1749        }
1750    }
1751
1752    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1753            boolean killApp, String[] grantedPermissions,
1754            boolean launchedForRestore, String installerPackage,
1755            IPackageInstallObserver2 installObserver) {
1756        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1757            // Send the removed broadcasts
1758            if (res.removedInfo != null) {
1759                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1760            }
1761
1762            // Now that we successfully installed the package, grant runtime
1763            // permissions if requested before broadcasting the install. Also
1764            // for legacy apps in permission review mode we clear the permission
1765            // review flag which is used to emulate runtime permissions for
1766            // legacy apps.
1767            if (grantPermissions) {
1768                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1769            }
1770
1771            final boolean update = res.removedInfo != null
1772                    && res.removedInfo.removedPackage != null;
1773
1774            // If this is the first time we have child packages for a disabled privileged
1775            // app that had no children, we grant requested runtime permissions to the new
1776            // children if the parent on the system image had them already granted.
1777            if (res.pkg.parentPackage != null) {
1778                synchronized (mPackages) {
1779                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1780                }
1781            }
1782
1783            synchronized (mPackages) {
1784                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1785            }
1786
1787            final String packageName = res.pkg.applicationInfo.packageName;
1788
1789            // Determine the set of users who are adding this package for
1790            // the first time vs. those who are seeing an update.
1791            int[] firstUsers = EMPTY_INT_ARRAY;
1792            int[] updateUsers = EMPTY_INT_ARRAY;
1793            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1794            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1795            for (int newUser : res.newUsers) {
1796                if (ps.getInstantApp(newUser)) {
1797                    continue;
1798                }
1799                if (allNewUsers) {
1800                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1801                    continue;
1802                }
1803                boolean isNew = true;
1804                for (int origUser : res.origUsers) {
1805                    if (origUser == newUser) {
1806                        isNew = false;
1807                        break;
1808                    }
1809                }
1810                if (isNew) {
1811                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1812                } else {
1813                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1814                }
1815            }
1816
1817            // Send installed broadcasts if the package is not a static shared lib.
1818            if (res.pkg.staticSharedLibName == null) {
1819                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1820
1821                // Send added for users that see the package for the first time
1822                // sendPackageAddedForNewUsers also deals with system apps
1823                int appId = UserHandle.getAppId(res.uid);
1824                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1825                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1826
1827                // Send added for users that don't see the package for the first time
1828                Bundle extras = new Bundle(1);
1829                extras.putInt(Intent.EXTRA_UID, res.uid);
1830                if (update) {
1831                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1832                }
1833                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1834                        extras, 0 /*flags*/, null /*targetPackage*/,
1835                        null /*finishedReceiver*/, updateUsers);
1836
1837                // Send replaced for users that don't see the package for the first time
1838                if (update) {
1839                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1840                            packageName, extras, 0 /*flags*/,
1841                            null /*targetPackage*/, null /*finishedReceiver*/,
1842                            updateUsers);
1843                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1844                            null /*package*/, null /*extras*/, 0 /*flags*/,
1845                            packageName /*targetPackage*/,
1846                            null /*finishedReceiver*/, updateUsers);
1847                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1848                    // First-install and we did a restore, so we're responsible for the
1849                    // first-launch broadcast.
1850                    if (DEBUG_BACKUP) {
1851                        Slog.i(TAG, "Post-restore of " + packageName
1852                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1853                    }
1854                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1855                }
1856
1857                // Send broadcast package appeared if forward locked/external for all users
1858                // treat asec-hosted packages like removable media on upgrade
1859                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1860                    if (DEBUG_INSTALL) {
1861                        Slog.i(TAG, "upgrading pkg " + res.pkg
1862                                + " is ASEC-hosted -> AVAILABLE");
1863                    }
1864                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1865                    ArrayList<String> pkgList = new ArrayList<>(1);
1866                    pkgList.add(packageName);
1867                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1868                }
1869            }
1870
1871            // Work that needs to happen on first install within each user
1872            if (firstUsers != null && firstUsers.length > 0) {
1873                synchronized (mPackages) {
1874                    for (int userId : firstUsers) {
1875                        // If this app is a browser and it's newly-installed for some
1876                        // users, clear any default-browser state in those users. The
1877                        // app's nature doesn't depend on the user, so we can just check
1878                        // its browser nature in any user and generalize.
1879                        if (packageIsBrowser(packageName, userId)) {
1880                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1881                        }
1882
1883                        // We may also need to apply pending (restored) runtime
1884                        // permission grants within these users.
1885                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1886                    }
1887                }
1888            }
1889
1890            // Log current value of "unknown sources" setting
1891            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1892                    getUnknownSourcesSettings());
1893
1894            // Force a gc to clear up things
1895            Runtime.getRuntime().gc();
1896
1897            // Remove the replaced package's older resources safely now
1898            // We delete after a gc for applications  on sdcard.
1899            if (res.removedInfo != null && res.removedInfo.args != null) {
1900                synchronized (mInstallLock) {
1901                    res.removedInfo.args.doPostDeleteLI(true);
1902                }
1903            }
1904
1905            // Notify DexManager that the package was installed for new users.
1906            // The updated users should already be indexed and the package code paths
1907            // should not change.
1908            // Don't notify the manager for ephemeral apps as they are not expected to
1909            // survive long enough to benefit of background optimizations.
1910            for (int userId : firstUsers) {
1911                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1912                mDexManager.notifyPackageInstalled(info, userId);
1913            }
1914        }
1915
1916        // If someone is watching installs - notify them
1917        if (installObserver != null) {
1918            try {
1919                Bundle extras = extrasForInstallResult(res);
1920                installObserver.onPackageInstalled(res.name, res.returnCode,
1921                        res.returnMsg, extras);
1922            } catch (RemoteException e) {
1923                Slog.i(TAG, "Observer no longer exists.");
1924            }
1925        }
1926    }
1927
1928    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1929            PackageParser.Package pkg) {
1930        if (pkg.parentPackage == null) {
1931            return;
1932        }
1933        if (pkg.requestedPermissions == null) {
1934            return;
1935        }
1936        final PackageSetting disabledSysParentPs = mSettings
1937                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1938        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1939                || !disabledSysParentPs.isPrivileged()
1940                || (disabledSysParentPs.childPackageNames != null
1941                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1942            return;
1943        }
1944        final int[] allUserIds = sUserManager.getUserIds();
1945        final int permCount = pkg.requestedPermissions.size();
1946        for (int i = 0; i < permCount; i++) {
1947            String permission = pkg.requestedPermissions.get(i);
1948            BasePermission bp = mSettings.mPermissions.get(permission);
1949            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1950                continue;
1951            }
1952            for (int userId : allUserIds) {
1953                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1954                        permission, userId)) {
1955                    grantRuntimePermission(pkg.packageName, permission, userId);
1956                }
1957            }
1958        }
1959    }
1960
1961    private StorageEventListener mStorageListener = new StorageEventListener() {
1962        @Override
1963        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1964            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1965                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1966                    final String volumeUuid = vol.getFsUuid();
1967
1968                    // Clean up any users or apps that were removed or recreated
1969                    // while this volume was missing
1970                    sUserManager.reconcileUsers(volumeUuid);
1971                    reconcileApps(volumeUuid);
1972
1973                    // Clean up any install sessions that expired or were
1974                    // cancelled while this volume was missing
1975                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1976
1977                    loadPrivatePackages(vol);
1978
1979                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1980                    unloadPrivatePackages(vol);
1981                }
1982            }
1983
1984            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1985                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1986                    updateExternalMediaStatus(true, false);
1987                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1988                    updateExternalMediaStatus(false, false);
1989                }
1990            }
1991        }
1992
1993        @Override
1994        public void onVolumeForgotten(String fsUuid) {
1995            if (TextUtils.isEmpty(fsUuid)) {
1996                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1997                return;
1998            }
1999
2000            // Remove any apps installed on the forgotten volume
2001            synchronized (mPackages) {
2002                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2003                for (PackageSetting ps : packages) {
2004                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2005                    deletePackageVersioned(new VersionedPackage(ps.name,
2006                            PackageManager.VERSION_CODE_HIGHEST),
2007                            new LegacyPackageDeleteObserver(null).getBinder(),
2008                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2009                    // Try very hard to release any references to this package
2010                    // so we don't risk the system server being killed due to
2011                    // open FDs
2012                    AttributeCache.instance().removePackage(ps.name);
2013                }
2014
2015                mSettings.onVolumeForgotten(fsUuid);
2016                mSettings.writeLPr();
2017            }
2018        }
2019    };
2020
2021    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2022            String[] grantedPermissions) {
2023        for (int userId : userIds) {
2024            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2025        }
2026    }
2027
2028    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2029            String[] grantedPermissions) {
2030        SettingBase sb = (SettingBase) pkg.mExtras;
2031        if (sb == null) {
2032            return;
2033        }
2034
2035        PermissionsState permissionsState = sb.getPermissionsState();
2036
2037        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2038                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2039
2040        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2041                >= Build.VERSION_CODES.M;
2042
2043        for (String permission : pkg.requestedPermissions) {
2044            final BasePermission bp;
2045            synchronized (mPackages) {
2046                bp = mSettings.mPermissions.get(permission);
2047            }
2048            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2049                    && (grantedPermissions == null
2050                           || ArrayUtils.contains(grantedPermissions, permission))) {
2051                final int flags = permissionsState.getPermissionFlags(permission, userId);
2052                if (supportsRuntimePermissions) {
2053                    // Installer cannot change immutable permissions.
2054                    if ((flags & immutableFlags) == 0) {
2055                        grantRuntimePermission(pkg.packageName, permission, userId);
2056                    }
2057                } else if (mPermissionReviewRequired) {
2058                    // In permission review mode we clear the review flag when we
2059                    // are asked to install the app with all permissions granted.
2060                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2061                        updatePermissionFlags(permission, pkg.packageName,
2062                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2063                    }
2064                }
2065            }
2066        }
2067    }
2068
2069    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2070        Bundle extras = null;
2071        switch (res.returnCode) {
2072            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2073                extras = new Bundle();
2074                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2075                        res.origPermission);
2076                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2077                        res.origPackage);
2078                break;
2079            }
2080            case PackageManager.INSTALL_SUCCEEDED: {
2081                extras = new Bundle();
2082                extras.putBoolean(Intent.EXTRA_REPLACING,
2083                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2084                break;
2085            }
2086        }
2087        return extras;
2088    }
2089
2090    void scheduleWriteSettingsLocked() {
2091        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2092            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2093        }
2094    }
2095
2096    void scheduleWritePackageListLocked(int userId) {
2097        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2098            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2099            msg.arg1 = userId;
2100            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2101        }
2102    }
2103
2104    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2105        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2106        scheduleWritePackageRestrictionsLocked(userId);
2107    }
2108
2109    void scheduleWritePackageRestrictionsLocked(int userId) {
2110        final int[] userIds = (userId == UserHandle.USER_ALL)
2111                ? sUserManager.getUserIds() : new int[]{userId};
2112        for (int nextUserId : userIds) {
2113            if (!sUserManager.exists(nextUserId)) return;
2114            mDirtyUsers.add(nextUserId);
2115            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2116                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2117            }
2118        }
2119    }
2120
2121    public static PackageManagerService main(Context context, Installer installer,
2122            boolean factoryTest, boolean onlyCore) {
2123        // Self-check for initial settings.
2124        PackageManagerServiceCompilerMapping.checkProperties();
2125
2126        PackageManagerService m = new PackageManagerService(context, installer,
2127                factoryTest, onlyCore);
2128        m.enableSystemUserPackages();
2129        ServiceManager.addService("package", m);
2130        return m;
2131    }
2132
2133    private void enableSystemUserPackages() {
2134        if (!UserManager.isSplitSystemUser()) {
2135            return;
2136        }
2137        // For system user, enable apps based on the following conditions:
2138        // - app is whitelisted or belong to one of these groups:
2139        //   -- system app which has no launcher icons
2140        //   -- system app which has INTERACT_ACROSS_USERS permission
2141        //   -- system IME app
2142        // - app is not in the blacklist
2143        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2144        Set<String> enableApps = new ArraySet<>();
2145        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2146                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2147                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2148        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2149        enableApps.addAll(wlApps);
2150        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2151                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2152        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2153        enableApps.removeAll(blApps);
2154        Log.i(TAG, "Applications installed for system user: " + enableApps);
2155        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2156                UserHandle.SYSTEM);
2157        final int allAppsSize = allAps.size();
2158        synchronized (mPackages) {
2159            for (int i = 0; i < allAppsSize; i++) {
2160                String pName = allAps.get(i);
2161                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2162                // Should not happen, but we shouldn't be failing if it does
2163                if (pkgSetting == null) {
2164                    continue;
2165                }
2166                boolean install = enableApps.contains(pName);
2167                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2168                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2169                            + " for system user");
2170                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2171                }
2172            }
2173            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2174        }
2175    }
2176
2177    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2178        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2179                Context.DISPLAY_SERVICE);
2180        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2181    }
2182
2183    /**
2184     * Requests that files preopted on a secondary system partition be copied to the data partition
2185     * if possible.  Note that the actual copying of the files is accomplished by init for security
2186     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2187     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2188     */
2189    private static void requestCopyPreoptedFiles() {
2190        final int WAIT_TIME_MS = 100;
2191        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2192        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2193            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2194            // We will wait for up to 100 seconds.
2195            final long timeStart = SystemClock.uptimeMillis();
2196            final long timeEnd = timeStart + 100 * 1000;
2197            long timeNow = timeStart;
2198            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2199                try {
2200                    Thread.sleep(WAIT_TIME_MS);
2201                } catch (InterruptedException e) {
2202                    // Do nothing
2203                }
2204                timeNow = SystemClock.uptimeMillis();
2205                if (timeNow > timeEnd) {
2206                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2207                    Slog.wtf(TAG, "cppreopt did not finish!");
2208                    break;
2209                }
2210            }
2211
2212            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2213        }
2214    }
2215
2216    public PackageManagerService(Context context, Installer installer,
2217            boolean factoryTest, boolean onlyCore) {
2218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2219        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2220                SystemClock.uptimeMillis());
2221
2222        if (mSdkVersion <= 0) {
2223            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2224        }
2225
2226        mContext = context;
2227
2228        mPermissionReviewRequired = context.getResources().getBoolean(
2229                R.bool.config_permissionReviewRequired);
2230
2231        mFactoryTest = factoryTest;
2232        mOnlyCore = onlyCore;
2233        mMetrics = new DisplayMetrics();
2234        mSettings = new Settings(mPackages);
2235        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2236                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2237        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2238                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2239        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2240                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2241        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2242                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2243        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247
2248        String separateProcesses = SystemProperties.get("debug.separate_processes");
2249        if (separateProcesses != null && separateProcesses.length() > 0) {
2250            if ("*".equals(separateProcesses)) {
2251                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2252                mSeparateProcesses = null;
2253                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2254            } else {
2255                mDefParseFlags = 0;
2256                mSeparateProcesses = separateProcesses.split(",");
2257                Slog.w(TAG, "Running with debug.separate_processes: "
2258                        + separateProcesses);
2259            }
2260        } else {
2261            mDefParseFlags = 0;
2262            mSeparateProcesses = null;
2263        }
2264
2265        mInstaller = installer;
2266        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2267                "*dexopt*");
2268        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2269        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2270
2271        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2272                FgThread.get().getLooper());
2273
2274        getDefaultDisplayMetrics(context, mMetrics);
2275
2276        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2277        SystemConfig systemConfig = SystemConfig.getInstance();
2278        mGlobalGids = systemConfig.getGlobalGids();
2279        mSystemPermissions = systemConfig.getSystemPermissions();
2280        mAvailableFeatures = systemConfig.getAvailableFeatures();
2281        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2282
2283        mProtectedPackages = new ProtectedPackages(mContext);
2284
2285        synchronized (mInstallLock) {
2286        // writer
2287        synchronized (mPackages) {
2288            mHandlerThread = new ServiceThread(TAG,
2289                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2290            mHandlerThread.start();
2291            mHandler = new PackageHandler(mHandlerThread.getLooper());
2292            mProcessLoggingHandler = new ProcessLoggingHandler();
2293            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2294
2295            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2296            mInstantAppRegistry = new InstantAppRegistry(this);
2297
2298            File dataDir = Environment.getDataDirectory();
2299            mAppInstallDir = new File(dataDir, "app");
2300            mAppLib32InstallDir = new File(dataDir, "app-lib");
2301            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2302            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2303            sUserManager = new UserManagerService(context, this,
2304                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2305
2306            // Propagate permission configuration in to package manager.
2307            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2308                    = systemConfig.getPermissions();
2309            for (int i=0; i<permConfig.size(); i++) {
2310                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2311                BasePermission bp = mSettings.mPermissions.get(perm.name);
2312                if (bp == null) {
2313                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2314                    mSettings.mPermissions.put(perm.name, bp);
2315                }
2316                if (perm.gids != null) {
2317                    bp.setGids(perm.gids, perm.perUser);
2318                }
2319            }
2320
2321            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2322            final int builtInLibCount = libConfig.size();
2323            for (int i = 0; i < builtInLibCount; i++) {
2324                String name = libConfig.keyAt(i);
2325                String path = libConfig.valueAt(i);
2326                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2327                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2328            }
2329
2330            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2331
2332            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2333            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2334            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2335
2336            // Clean up orphaned packages for which the code path doesn't exist
2337            // and they are an update to a system app - caused by bug/32321269
2338            final int packageSettingCount = mSettings.mPackages.size();
2339            for (int i = packageSettingCount - 1; i >= 0; i--) {
2340                PackageSetting ps = mSettings.mPackages.valueAt(i);
2341                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2342                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2343                    mSettings.mPackages.removeAt(i);
2344                    mSettings.enableSystemPackageLPw(ps.name);
2345                }
2346            }
2347
2348            if (mFirstBoot) {
2349                requestCopyPreoptedFiles();
2350            }
2351
2352            String customResolverActivity = Resources.getSystem().getString(
2353                    R.string.config_customResolverActivity);
2354            if (TextUtils.isEmpty(customResolverActivity)) {
2355                customResolverActivity = null;
2356            } else {
2357                mCustomResolverComponentName = ComponentName.unflattenFromString(
2358                        customResolverActivity);
2359            }
2360
2361            long startTime = SystemClock.uptimeMillis();
2362
2363            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2364                    startTime);
2365
2366            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2367            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2368
2369            if (bootClassPath == null) {
2370                Slog.w(TAG, "No BOOTCLASSPATH found!");
2371            }
2372
2373            if (systemServerClassPath == null) {
2374                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2375            }
2376
2377            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2378            final String[] dexCodeInstructionSets =
2379                    getDexCodeInstructionSets(
2380                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2381
2382            /**
2383             * Ensure all external libraries have had dexopt run on them.
2384             */
2385            if (mSharedLibraries.size() > 0) {
2386                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2387                // NOTE: For now, we're compiling these system "shared libraries"
2388                // (and framework jars) into all available architectures. It's possible
2389                // to compile them only when we come across an app that uses them (there's
2390                // already logic for that in scanPackageLI) but that adds some complexity.
2391                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2392                    final int libCount = mSharedLibraries.size();
2393                    for (int i = 0; i < libCount; i++) {
2394                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2395                        final int versionCount = versionedLib.size();
2396                        for (int j = 0; j < versionCount; j++) {
2397                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2398                            final String libPath = libEntry.path != null
2399                                    ? libEntry.path : libEntry.apk;
2400                            if (libPath == null) {
2401                                continue;
2402                            }
2403                            try {
2404                                // Shared libraries do not have profiles so we perform a full
2405                                // AOT compilation (if needed).
2406                                int dexoptNeeded = DexFile.getDexOptNeeded(
2407                                        libPath, dexCodeInstructionSet,
2408                                        getCompilerFilterForReason(REASON_SHARED_APK),
2409                                        false /* newProfile */);
2410                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2411                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2412                                            dexCodeInstructionSet, dexoptNeeded, null,
2413                                            DEXOPT_PUBLIC,
2414                                            getCompilerFilterForReason(REASON_SHARED_APK),
2415                                            StorageManager.UUID_PRIVATE_INTERNAL,
2416                                            PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK);
2417                                }
2418                            } catch (FileNotFoundException e) {
2419                                Slog.w(TAG, "Library not found: " + libPath);
2420                            } catch (IOException | InstallerException e) {
2421                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2422                                        + e.getMessage());
2423                            }
2424                        }
2425                    }
2426                }
2427                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2428            }
2429
2430            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2431
2432            final VersionInfo ver = mSettings.getInternalVersion();
2433            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2434
2435            // when upgrading from pre-M, promote system app permissions from install to runtime
2436            mPromoteSystemApps =
2437                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2438
2439            // When upgrading from pre-N, we need to handle package extraction like first boot,
2440            // as there is no profiling data available.
2441            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2442
2443            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2444
2445            // save off the names of pre-existing system packages prior to scanning; we don't
2446            // want to automatically grant runtime permissions for new system apps
2447            if (mPromoteSystemApps) {
2448                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2449                while (pkgSettingIter.hasNext()) {
2450                    PackageSetting ps = pkgSettingIter.next();
2451                    if (isSystemApp(ps)) {
2452                        mExistingSystemPackages.add(ps.name);
2453                    }
2454                }
2455            }
2456
2457            mCacheDir = preparePackageParserCache(mIsUpgrade);
2458
2459            // Set flag to monitor and not change apk file paths when
2460            // scanning install directories.
2461            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2462
2463            if (mIsUpgrade || mFirstBoot) {
2464                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2465            }
2466
2467            // Collect vendor overlay packages. (Do this before scanning any apps.)
2468            // For security and version matching reason, only consider
2469            // overlay packages if they reside in the right directory.
2470            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2471            if (overlayThemeDir.isEmpty()) {
2472                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2473            }
2474            if (!overlayThemeDir.isEmpty()) {
2475                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2476                        | PackageParser.PARSE_IS_SYSTEM
2477                        | PackageParser.PARSE_IS_SYSTEM_DIR
2478                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2479            }
2480            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2481                    | PackageParser.PARSE_IS_SYSTEM
2482                    | PackageParser.PARSE_IS_SYSTEM_DIR
2483                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2484
2485            // Find base frameworks (resource packages without code).
2486            scanDirTracedLI(frameworkDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR
2489                    | PackageParser.PARSE_IS_PRIVILEGED,
2490                    scanFlags | SCAN_NO_DEX, 0);
2491
2492            // Collected privileged system packages.
2493            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2494            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2495                    | PackageParser.PARSE_IS_SYSTEM
2496                    | PackageParser.PARSE_IS_SYSTEM_DIR
2497                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2498
2499            // Collect ordinary system packages.
2500            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2501            scanDirTracedLI(systemAppDir, mDefParseFlags
2502                    | PackageParser.PARSE_IS_SYSTEM
2503                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2504
2505            // Collect all vendor packages.
2506            File vendorAppDir = new File("/vendor/app");
2507            try {
2508                vendorAppDir = vendorAppDir.getCanonicalFile();
2509            } catch (IOException e) {
2510                // failed to look up canonical path, continue with original one
2511            }
2512            scanDirTracedLI(vendorAppDir, mDefParseFlags
2513                    | PackageParser.PARSE_IS_SYSTEM
2514                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2515
2516            // Collect all OEM packages.
2517            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2518            scanDirTracedLI(oemAppDir, mDefParseFlags
2519                    | PackageParser.PARSE_IS_SYSTEM
2520                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2521
2522            // Prune any system packages that no longer exist.
2523            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2524            if (!mOnlyCore) {
2525                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2526                while (psit.hasNext()) {
2527                    PackageSetting ps = psit.next();
2528
2529                    /*
2530                     * If this is not a system app, it can't be a
2531                     * disable system app.
2532                     */
2533                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2534                        continue;
2535                    }
2536
2537                    /*
2538                     * If the package is scanned, it's not erased.
2539                     */
2540                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2541                    if (scannedPkg != null) {
2542                        /*
2543                         * If the system app is both scanned and in the
2544                         * disabled packages list, then it must have been
2545                         * added via OTA. Remove it from the currently
2546                         * scanned package so the previously user-installed
2547                         * application can be scanned.
2548                         */
2549                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2550                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2551                                    + ps.name + "; removing system app.  Last known codePath="
2552                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2553                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2554                                    + scannedPkg.mVersionCode);
2555                            removePackageLI(scannedPkg, true);
2556                            mExpectingBetter.put(ps.name, ps.codePath);
2557                        }
2558
2559                        continue;
2560                    }
2561
2562                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2563                        psit.remove();
2564                        logCriticalInfo(Log.WARN, "System package " + ps.name
2565                                + " no longer exists; it's data will be wiped");
2566                        // Actual deletion of code and data will be handled by later
2567                        // reconciliation step
2568                    } else {
2569                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2570                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2571                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2572                        }
2573                    }
2574                }
2575            }
2576
2577            //look for any incomplete package installations
2578            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2579            for (int i = 0; i < deletePkgsList.size(); i++) {
2580                // Actual deletion of code and data will be handled by later
2581                // reconciliation step
2582                final String packageName = deletePkgsList.get(i).name;
2583                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2584                synchronized (mPackages) {
2585                    mSettings.removePackageLPw(packageName);
2586                }
2587            }
2588
2589            //delete tmp files
2590            deleteTempPackageFiles();
2591
2592            // Remove any shared userIDs that have no associated packages
2593            mSettings.pruneSharedUsersLPw();
2594
2595            if (!mOnlyCore) {
2596                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2597                        SystemClock.uptimeMillis());
2598                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2599
2600                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2601                        | PackageParser.PARSE_FORWARD_LOCK,
2602                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2603
2604                /**
2605                 * Remove disable package settings for any updated system
2606                 * apps that were removed via an OTA. If they're not a
2607                 * previously-updated app, remove them completely.
2608                 * Otherwise, just revoke their system-level permissions.
2609                 */
2610                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2611                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2612                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2613
2614                    String msg;
2615                    if (deletedPkg == null) {
2616                        msg = "Updated system package " + deletedAppName
2617                                + " no longer exists; it's data will be wiped";
2618                        // Actual deletion of code and data will be handled by later
2619                        // reconciliation step
2620                    } else {
2621                        msg = "Updated system app + " + deletedAppName
2622                                + " no longer present; removing system privileges for "
2623                                + deletedAppName;
2624
2625                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2626
2627                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2628                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2629                    }
2630                    logCriticalInfo(Log.WARN, msg);
2631                }
2632
2633                /**
2634                 * Make sure all system apps that we expected to appear on
2635                 * the userdata partition actually showed up. If they never
2636                 * appeared, crawl back and revive the system version.
2637                 */
2638                for (int i = 0; i < mExpectingBetter.size(); i++) {
2639                    final String packageName = mExpectingBetter.keyAt(i);
2640                    if (!mPackages.containsKey(packageName)) {
2641                        final File scanFile = mExpectingBetter.valueAt(i);
2642
2643                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2644                                + " but never showed up; reverting to system");
2645
2646                        int reparseFlags = mDefParseFlags;
2647                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2648                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2649                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2650                                    | PackageParser.PARSE_IS_PRIVILEGED;
2651                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2652                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2653                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2654                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2655                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2656                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2657                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2658                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2659                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2660                        } else {
2661                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2662                            continue;
2663                        }
2664
2665                        mSettings.enableSystemPackageLPw(packageName);
2666
2667                        try {
2668                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2669                        } catch (PackageManagerException e) {
2670                            Slog.e(TAG, "Failed to parse original system package: "
2671                                    + e.getMessage());
2672                        }
2673                    }
2674                }
2675            }
2676            mExpectingBetter.clear();
2677
2678            // Resolve the storage manager.
2679            mStorageManagerPackage = getStorageManagerPackageName();
2680
2681            // Resolve protected action filters. Only the setup wizard is allowed to
2682            // have a high priority filter for these actions.
2683            mSetupWizardPackage = getSetupWizardPackageName();
2684            if (mProtectedFilters.size() > 0) {
2685                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2686                    Slog.i(TAG, "No setup wizard;"
2687                        + " All protected intents capped to priority 0");
2688                }
2689                for (ActivityIntentInfo filter : mProtectedFilters) {
2690                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2691                        if (DEBUG_FILTERS) {
2692                            Slog.i(TAG, "Found setup wizard;"
2693                                + " allow priority " + filter.getPriority() + ";"
2694                                + " package: " + filter.activity.info.packageName
2695                                + " activity: " + filter.activity.className
2696                                + " priority: " + filter.getPriority());
2697                        }
2698                        // skip setup wizard; allow it to keep the high priority filter
2699                        continue;
2700                    }
2701                    Slog.w(TAG, "Protected action; cap priority to 0;"
2702                            + " package: " + filter.activity.info.packageName
2703                            + " activity: " + filter.activity.className
2704                            + " origPrio: " + filter.getPriority());
2705                    filter.setPriority(0);
2706                }
2707            }
2708            mDeferProtectedFilters = false;
2709            mProtectedFilters.clear();
2710
2711            // Now that we know all of the shared libraries, update all clients to have
2712            // the correct library paths.
2713            updateAllSharedLibrariesLPw(null);
2714
2715            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2716                // NOTE: We ignore potential failures here during a system scan (like
2717                // the rest of the commands above) because there's precious little we
2718                // can do about it. A settings error is reported, though.
2719                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2720            }
2721
2722            // Now that we know all the packages we are keeping,
2723            // read and update their last usage times.
2724            mPackageUsage.read(mPackages);
2725            mCompilerStats.read();
2726
2727            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2728                    SystemClock.uptimeMillis());
2729            Slog.i(TAG, "Time to scan packages: "
2730                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2731                    + " seconds");
2732
2733            // If the platform SDK has changed since the last time we booted,
2734            // we need to re-grant app permission to catch any new ones that
2735            // appear.  This is really a hack, and means that apps can in some
2736            // cases get permissions that the user didn't initially explicitly
2737            // allow...  it would be nice to have some better way to handle
2738            // this situation.
2739            int updateFlags = UPDATE_PERMISSIONS_ALL;
2740            if (ver.sdkVersion != mSdkVersion) {
2741                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2742                        + mSdkVersion + "; regranting permissions for internal storage");
2743                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2744            }
2745            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2746            ver.sdkVersion = mSdkVersion;
2747
2748            // If this is the first boot or an update from pre-M, and it is a normal
2749            // boot, then we need to initialize the default preferred apps across
2750            // all defined users.
2751            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2752                for (UserInfo user : sUserManager.getUsers(true)) {
2753                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2754                    applyFactoryDefaultBrowserLPw(user.id);
2755                    primeDomainVerificationsLPw(user.id);
2756                }
2757            }
2758
2759            // Prepare storage for system user really early during boot,
2760            // since core system apps like SettingsProvider and SystemUI
2761            // can't wait for user to start
2762            final int storageFlags;
2763            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2764                storageFlags = StorageManager.FLAG_STORAGE_DE;
2765            } else {
2766                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2767            }
2768            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2769                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2770                    true /* onlyCoreApps */);
2771            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2772                if (deferPackages == null || deferPackages.isEmpty()) {
2773                    return;
2774                }
2775                int count = 0;
2776                for (String pkgName : deferPackages) {
2777                    PackageParser.Package pkg = null;
2778                    synchronized (mPackages) {
2779                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2780                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2781                            pkg = ps.pkg;
2782                        }
2783                    }
2784                    if (pkg != null) {
2785                        synchronized (mInstallLock) {
2786                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2787                                    true /* maybeMigrateAppData */);
2788                        }
2789                        count++;
2790                    }
2791                }
2792                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2793            }, "prepareAppData");
2794
2795            // If this is first boot after an OTA, and a normal boot, then
2796            // we need to clear code cache directories.
2797            // Note that we do *not* clear the application profiles. These remain valid
2798            // across OTAs and are used to drive profile verification (post OTA) and
2799            // profile compilation (without waiting to collect a fresh set of profiles).
2800            if (mIsUpgrade && !onlyCore) {
2801                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2802                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2803                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2804                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2805                        // No apps are running this early, so no need to freeze
2806                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2807                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2808                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2809                    }
2810                }
2811                ver.fingerprint = Build.FINGERPRINT;
2812            }
2813
2814            checkDefaultBrowser();
2815
2816            // clear only after permissions and other defaults have been updated
2817            mExistingSystemPackages.clear();
2818            mPromoteSystemApps = false;
2819
2820            // All the changes are done during package scanning.
2821            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2822
2823            // can downgrade to reader
2824            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2825            mSettings.writeLPr();
2826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2827
2828            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2829            // early on (before the package manager declares itself as early) because other
2830            // components in the system server might ask for package contexts for these apps.
2831            //
2832            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2833            // (i.e, that the data partition is unavailable).
2834            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2835                long start = System.nanoTime();
2836                List<PackageParser.Package> coreApps = new ArrayList<>();
2837                for (PackageParser.Package pkg : mPackages.values()) {
2838                    if (pkg.coreApp) {
2839                        coreApps.add(pkg);
2840                    }
2841                }
2842
2843                int[] stats = performDexOptUpgrade(coreApps, false,
2844                        getCompilerFilterForReason(REASON_CORE_APP));
2845
2846                final int elapsedTimeSeconds =
2847                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2848                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2849
2850                if (DEBUG_DEXOPT) {
2851                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2852                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2853                }
2854
2855
2856                // TODO: Should we log these stats to tron too ?
2857                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2858                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2859                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2860                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2861            }
2862
2863            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2864                    SystemClock.uptimeMillis());
2865
2866            if (!mOnlyCore) {
2867                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2868                mRequiredInstallerPackage = getRequiredInstallerLPr();
2869                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2870                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2871                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2872                        mIntentFilterVerifierComponent);
2873                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2874                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2875                        SharedLibraryInfo.VERSION_UNDEFINED);
2876                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2877                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2878                        SharedLibraryInfo.VERSION_UNDEFINED);
2879            } else {
2880                mRequiredVerifierPackage = null;
2881                mRequiredInstallerPackage = null;
2882                mRequiredUninstallerPackage = null;
2883                mIntentFilterVerifierComponent = null;
2884                mIntentFilterVerifier = null;
2885                mServicesSystemSharedLibraryPackageName = null;
2886                mSharedSystemSharedLibraryPackageName = null;
2887            }
2888
2889            mInstallerService = new PackageInstallerService(context, this);
2890
2891            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2892            if (ephemeralResolverComponent != null) {
2893                if (DEBUG_EPHEMERAL) {
2894                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2895                }
2896                mInstantAppResolverConnection =
2897                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2898            } else {
2899                mInstantAppResolverConnection = null;
2900            }
2901            mInstantAppInstallerComponent = getEphemeralInstallerLPr();
2902            if (mInstantAppInstallerComponent != null) {
2903                if (DEBUG_EPHEMERAL) {
2904                    Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent);
2905                }
2906                setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent);
2907            }
2908
2909            // Read and update the usage of dex files.
2910            // Do this at the end of PM init so that all the packages have their
2911            // data directory reconciled.
2912            // At this point we know the code paths of the packages, so we can validate
2913            // the disk file and build the internal cache.
2914            // The usage file is expected to be small so loading and verifying it
2915            // should take a fairly small time compare to the other activities (e.g. package
2916            // scanning).
2917            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2918            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2919            for (int userId : currentUserIds) {
2920                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2921            }
2922            mDexManager.load(userPackages);
2923        } // synchronized (mPackages)
2924        } // synchronized (mInstallLock)
2925
2926        // Now after opening every single application zip, make sure they
2927        // are all flushed.  Not really needed, but keeps things nice and
2928        // tidy.
2929        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2930        Runtime.getRuntime().gc();
2931        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2932
2933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2934        FallbackCategoryProvider.loadFallbacks();
2935        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2936
2937        // The initial scanning above does many calls into installd while
2938        // holding the mPackages lock, but we're mostly interested in yelling
2939        // once we have a booted system.
2940        mInstaller.setWarnIfHeld(mPackages);
2941
2942        // Expose private service for system components to use.
2943        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2944        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945    }
2946
2947    private static File preparePackageParserCache(boolean isUpgrade) {
2948        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2949            return null;
2950        }
2951
2952        // Disable package parsing on eng builds to allow for faster incremental development.
2953        if ("eng".equals(Build.TYPE)) {
2954            return null;
2955        }
2956
2957        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2958            Slog.i(TAG, "Disabling package parser cache due to system property.");
2959            return null;
2960        }
2961
2962        // The base directory for the package parser cache lives under /data/system/.
2963        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2964                "package_cache");
2965        if (cacheBaseDir == null) {
2966            return null;
2967        }
2968
2969        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2970        // This also serves to "GC" unused entries when the package cache version changes (which
2971        // can only happen during upgrades).
2972        if (isUpgrade) {
2973            FileUtils.deleteContents(cacheBaseDir);
2974        }
2975
2976
2977        // Return the versioned package cache directory. This is something like
2978        // "/data/system/package_cache/1"
2979        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2980
2981        // The following is a workaround to aid development on non-numbered userdebug
2982        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2983        // the system partition is newer.
2984        //
2985        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2986        // that starts with "eng." to signify that this is an engineering build and not
2987        // destined for release.
2988        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2989            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2990
2991            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2992            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2993            // in general and should not be used for production changes. In this specific case,
2994            // we know that they will work.
2995            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2996            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2997                FileUtils.deleteContents(cacheBaseDir);
2998                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2999            }
3000        }
3001
3002        return cacheDir;
3003    }
3004
3005    @Override
3006    public boolean isFirstBoot() {
3007        return mFirstBoot;
3008    }
3009
3010    @Override
3011    public boolean isOnlyCoreApps() {
3012        return mOnlyCore;
3013    }
3014
3015    @Override
3016    public boolean isUpgrade() {
3017        return mIsUpgrade;
3018    }
3019
3020    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3021        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3022
3023        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3024                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3025                UserHandle.USER_SYSTEM);
3026        if (matches.size() == 1) {
3027            return matches.get(0).getComponentInfo().packageName;
3028        } else if (matches.size() == 0) {
3029            Log.e(TAG, "There should probably be a verifier, but, none were found");
3030            return null;
3031        }
3032        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3033    }
3034
3035    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3036        synchronized (mPackages) {
3037            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3038            if (libraryEntry == null) {
3039                throw new IllegalStateException("Missing required shared library:" + name);
3040            }
3041            return libraryEntry.apk;
3042        }
3043    }
3044
3045    private @NonNull String getRequiredInstallerLPr() {
3046        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3047        intent.addCategory(Intent.CATEGORY_DEFAULT);
3048        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3049
3050        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3051                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3052                UserHandle.USER_SYSTEM);
3053        if (matches.size() == 1) {
3054            ResolveInfo resolveInfo = matches.get(0);
3055            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3056                throw new RuntimeException("The installer must be a privileged app");
3057            }
3058            return matches.get(0).getComponentInfo().packageName;
3059        } else {
3060            throw new RuntimeException("There must be exactly one installer; found " + matches);
3061        }
3062    }
3063
3064    private @NonNull String getRequiredUninstallerLPr() {
3065        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3066        intent.addCategory(Intent.CATEGORY_DEFAULT);
3067        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3068
3069        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3070                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3071                UserHandle.USER_SYSTEM);
3072        if (resolveInfo == null ||
3073                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3074            throw new RuntimeException("There must be exactly one uninstaller; found "
3075                    + resolveInfo);
3076        }
3077        return resolveInfo.getComponentInfo().packageName;
3078    }
3079
3080    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3081        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3082
3083        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3084                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3085                UserHandle.USER_SYSTEM);
3086        ResolveInfo best = null;
3087        final int N = matches.size();
3088        for (int i = 0; i < N; i++) {
3089            final ResolveInfo cur = matches.get(i);
3090            final String packageName = cur.getComponentInfo().packageName;
3091            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3092                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3093                continue;
3094            }
3095
3096            if (best == null || cur.priority > best.priority) {
3097                best = cur;
3098            }
3099        }
3100
3101        if (best != null) {
3102            return best.getComponentInfo().getComponentName();
3103        } else {
3104            throw new RuntimeException("There must be at least one intent filter verifier");
3105        }
3106    }
3107
3108    private @Nullable ComponentName getEphemeralResolverLPr() {
3109        final String[] packageArray =
3110                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3111        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3112            if (DEBUG_EPHEMERAL) {
3113                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3114            }
3115            return null;
3116        }
3117
3118        final int resolveFlags =
3119                MATCH_DIRECT_BOOT_AWARE
3120                | MATCH_DIRECT_BOOT_UNAWARE
3121                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3122        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3123        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3124                resolveFlags, UserHandle.USER_SYSTEM);
3125
3126        final int N = resolvers.size();
3127        if (N == 0) {
3128            if (DEBUG_EPHEMERAL) {
3129                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3130            }
3131            return null;
3132        }
3133
3134        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3135        for (int i = 0; i < N; i++) {
3136            final ResolveInfo info = resolvers.get(i);
3137
3138            if (info.serviceInfo == null) {
3139                continue;
3140            }
3141
3142            final String packageName = info.serviceInfo.packageName;
3143            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3144                if (DEBUG_EPHEMERAL) {
3145                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3146                            + " pkg: " + packageName + ", info:" + info);
3147                }
3148                continue;
3149            }
3150
3151            if (DEBUG_EPHEMERAL) {
3152                Slog.v(TAG, "Ephemeral resolver found;"
3153                        + " pkg: " + packageName + ", info:" + info);
3154            }
3155            return new ComponentName(packageName, info.serviceInfo.name);
3156        }
3157        if (DEBUG_EPHEMERAL) {
3158            Slog.v(TAG, "Ephemeral resolver NOT found");
3159        }
3160        return null;
3161    }
3162
3163    private @Nullable ComponentName getEphemeralInstallerLPr() {
3164        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3165        intent.addCategory(Intent.CATEGORY_DEFAULT);
3166        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3167
3168        final int resolveFlags =
3169                MATCH_DIRECT_BOOT_AWARE
3170                | MATCH_DIRECT_BOOT_UNAWARE
3171                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3172        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3173                resolveFlags, UserHandle.USER_SYSTEM);
3174        Iterator<ResolveInfo> iter = matches.iterator();
3175        while (iter.hasNext()) {
3176            final ResolveInfo rInfo = iter.next();
3177            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3178            if (ps != null) {
3179                final PermissionsState permissionsState = ps.getPermissionsState();
3180                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3181                    continue;
3182                }
3183            }
3184            iter.remove();
3185        }
3186        if (matches.size() == 0) {
3187            return null;
3188        } else if (matches.size() == 1) {
3189            return matches.get(0).getComponentInfo().getComponentName();
3190        } else {
3191            throw new RuntimeException(
3192                    "There must be at most one ephemeral installer; found " + matches);
3193        }
3194    }
3195
3196    private void primeDomainVerificationsLPw(int userId) {
3197        if (DEBUG_DOMAIN_VERIFICATION) {
3198            Slog.d(TAG, "Priming domain verifications in user " + userId);
3199        }
3200
3201        SystemConfig systemConfig = SystemConfig.getInstance();
3202        ArraySet<String> packages = systemConfig.getLinkedApps();
3203
3204        for (String packageName : packages) {
3205            PackageParser.Package pkg = mPackages.get(packageName);
3206            if (pkg != null) {
3207                if (!pkg.isSystemApp()) {
3208                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3209                    continue;
3210                }
3211
3212                ArraySet<String> domains = null;
3213                for (PackageParser.Activity a : pkg.activities) {
3214                    for (ActivityIntentInfo filter : a.intents) {
3215                        if (hasValidDomains(filter)) {
3216                            if (domains == null) {
3217                                domains = new ArraySet<String>();
3218                            }
3219                            domains.addAll(filter.getHostsList());
3220                        }
3221                    }
3222                }
3223
3224                if (domains != null && domains.size() > 0) {
3225                    if (DEBUG_DOMAIN_VERIFICATION) {
3226                        Slog.v(TAG, "      + " + packageName);
3227                    }
3228                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3229                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3230                    // and then 'always' in the per-user state actually used for intent resolution.
3231                    final IntentFilterVerificationInfo ivi;
3232                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3233                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3234                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3235                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3236                } else {
3237                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3238                            + "' does not handle web links");
3239                }
3240            } else {
3241                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3242            }
3243        }
3244
3245        scheduleWritePackageRestrictionsLocked(userId);
3246        scheduleWriteSettingsLocked();
3247    }
3248
3249    private void applyFactoryDefaultBrowserLPw(int userId) {
3250        // The default browser app's package name is stored in a string resource,
3251        // with a product-specific overlay used for vendor customization.
3252        String browserPkg = mContext.getResources().getString(
3253                com.android.internal.R.string.default_browser);
3254        if (!TextUtils.isEmpty(browserPkg)) {
3255            // non-empty string => required to be a known package
3256            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3257            if (ps == null) {
3258                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3259                browserPkg = null;
3260            } else {
3261                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3262            }
3263        }
3264
3265        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3266        // default.  If there's more than one, just leave everything alone.
3267        if (browserPkg == null) {
3268            calculateDefaultBrowserLPw(userId);
3269        }
3270    }
3271
3272    private void calculateDefaultBrowserLPw(int userId) {
3273        List<String> allBrowsers = resolveAllBrowserApps(userId);
3274        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3275        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3276    }
3277
3278    private List<String> resolveAllBrowserApps(int userId) {
3279        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3280        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3281                PackageManager.MATCH_ALL, userId);
3282
3283        final int count = list.size();
3284        List<String> result = new ArrayList<String>(count);
3285        for (int i=0; i<count; i++) {
3286            ResolveInfo info = list.get(i);
3287            if (info.activityInfo == null
3288                    || !info.handleAllWebDataURI
3289                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3290                    || result.contains(info.activityInfo.packageName)) {
3291                continue;
3292            }
3293            result.add(info.activityInfo.packageName);
3294        }
3295
3296        return result;
3297    }
3298
3299    private boolean packageIsBrowser(String packageName, int userId) {
3300        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3301                PackageManager.MATCH_ALL, userId);
3302        final int N = list.size();
3303        for (int i = 0; i < N; i++) {
3304            ResolveInfo info = list.get(i);
3305            if (packageName.equals(info.activityInfo.packageName)) {
3306                return true;
3307            }
3308        }
3309        return false;
3310    }
3311
3312    private void checkDefaultBrowser() {
3313        final int myUserId = UserHandle.myUserId();
3314        final String packageName = getDefaultBrowserPackageName(myUserId);
3315        if (packageName != null) {
3316            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3317            if (info == null) {
3318                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3319                synchronized (mPackages) {
3320                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3321                }
3322            }
3323        }
3324    }
3325
3326    @Override
3327    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3328            throws RemoteException {
3329        try {
3330            return super.onTransact(code, data, reply, flags);
3331        } catch (RuntimeException e) {
3332            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3333                Slog.wtf(TAG, "Package Manager Crash", e);
3334            }
3335            throw e;
3336        }
3337    }
3338
3339    static int[] appendInts(int[] cur, int[] add) {
3340        if (add == null) return cur;
3341        if (cur == null) return add;
3342        final int N = add.length;
3343        for (int i=0; i<N; i++) {
3344            cur = appendInt(cur, add[i]);
3345        }
3346        return cur;
3347    }
3348
3349    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3350        if (!sUserManager.exists(userId)) return null;
3351        if (ps == null) {
3352            return null;
3353        }
3354        final PackageParser.Package p = ps.pkg;
3355        if (p == null) {
3356            return null;
3357        }
3358        // Filter out ephemeral app metadata:
3359        //   * The system/shell/root can see metadata for any app
3360        //   * An installed app can see metadata for 1) other installed apps
3361        //     and 2) ephemeral apps that have explicitly interacted with it
3362        //   * Ephemeral apps can only see their own metadata
3363        //   * Holding a signature permission allows seeing instant apps
3364        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3365        if (callingAppId != Process.SYSTEM_UID
3366                && callingAppId != Process.SHELL_UID
3367                && callingAppId != Process.ROOT_UID
3368                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3369                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3370            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3371            if (instantAppPackageName != null) {
3372                // ephemeral apps can only get information on themselves
3373                if (!instantAppPackageName.equals(p.packageName)) {
3374                    return null;
3375                }
3376            } else {
3377                if (ps.getInstantApp(userId)) {
3378                    // only get access to the ephemeral app if we've been granted access
3379                    if (!mInstantAppRegistry.isInstantAccessGranted(
3380                            userId, callingAppId, ps.appId)) {
3381                        return null;
3382                    }
3383                }
3384            }
3385        }
3386
3387        final PermissionsState permissionsState = ps.getPermissionsState();
3388
3389        // Compute GIDs only if requested
3390        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3391                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3392        // Compute granted permissions only if package has requested permissions
3393        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3394                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3395        final PackageUserState state = ps.readUserState(userId);
3396
3397        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3398                && ps.isSystem()) {
3399            flags |= MATCH_ANY_USER;
3400        }
3401
3402        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3403                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3404
3405        if (packageInfo == null) {
3406            return null;
3407        }
3408
3409        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3410                resolveExternalPackageNameLPr(p);
3411
3412        return packageInfo;
3413    }
3414
3415    @Override
3416    public void checkPackageStartable(String packageName, int userId) {
3417        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3418
3419        synchronized (mPackages) {
3420            final PackageSetting ps = mSettings.mPackages.get(packageName);
3421            if (ps == null) {
3422                throw new SecurityException("Package " + packageName + " was not found!");
3423            }
3424
3425            if (!ps.getInstalled(userId)) {
3426                throw new SecurityException(
3427                        "Package " + packageName + " was not installed for user " + userId + "!");
3428            }
3429
3430            if (mSafeMode && !ps.isSystem()) {
3431                throw new SecurityException("Package " + packageName + " not a system app!");
3432            }
3433
3434            if (mFrozenPackages.contains(packageName)) {
3435                throw new SecurityException("Package " + packageName + " is currently frozen!");
3436            }
3437
3438            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3439                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3440                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3441            }
3442        }
3443    }
3444
3445    @Override
3446    public boolean isPackageAvailable(String packageName, int userId) {
3447        if (!sUserManager.exists(userId)) return false;
3448        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3449                false /* requireFullPermission */, false /* checkShell */, "is package available");
3450        synchronized (mPackages) {
3451            PackageParser.Package p = mPackages.get(packageName);
3452            if (p != null) {
3453                final PackageSetting ps = (PackageSetting) p.mExtras;
3454                if (ps != null) {
3455                    final PackageUserState state = ps.readUserState(userId);
3456                    if (state != null) {
3457                        return PackageParser.isAvailable(state);
3458                    }
3459                }
3460            }
3461        }
3462        return false;
3463    }
3464
3465    @Override
3466    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3467        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3468                flags, userId);
3469    }
3470
3471    @Override
3472    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3473            int flags, int userId) {
3474        return getPackageInfoInternal(versionedPackage.getPackageName(),
3475                // TODO: We will change version code to long, so in the new API it is long
3476                (int) versionedPackage.getVersionCode(), flags, userId);
3477    }
3478
3479    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3480            int flags, int userId) {
3481        if (!sUserManager.exists(userId)) return null;
3482        flags = updateFlagsForPackage(flags, userId, packageName);
3483        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3484                false /* requireFullPermission */, false /* checkShell */, "get package info");
3485
3486        // reader
3487        synchronized (mPackages) {
3488            // Normalize package name to handle renamed packages and static libs
3489            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3490
3491            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3492            if (matchFactoryOnly) {
3493                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3494                if (ps != null) {
3495                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3496                        return null;
3497                    }
3498                    return generatePackageInfo(ps, flags, userId);
3499                }
3500            }
3501
3502            PackageParser.Package p = mPackages.get(packageName);
3503            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3504                return null;
3505            }
3506            if (DEBUG_PACKAGE_INFO)
3507                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3508            if (p != null) {
3509                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3510                        Binder.getCallingUid(), userId)) {
3511                    return null;
3512                }
3513                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3514            }
3515            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3516                final PackageSetting ps = mSettings.mPackages.get(packageName);
3517                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3518                    return null;
3519                }
3520                return generatePackageInfo(ps, flags, userId);
3521            }
3522        }
3523        return null;
3524    }
3525
3526
3527    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3528        // System/shell/root get to see all static libs
3529        final int appId = UserHandle.getAppId(uid);
3530        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3531                || appId == Process.ROOT_UID) {
3532            return false;
3533        }
3534
3535        // No package means no static lib as it is always on internal storage
3536        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3537            return false;
3538        }
3539
3540        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3541                ps.pkg.staticSharedLibVersion);
3542        if (libEntry == null) {
3543            return false;
3544        }
3545
3546        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3547        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3548        if (uidPackageNames == null) {
3549            return true;
3550        }
3551
3552        for (String uidPackageName : uidPackageNames) {
3553            if (ps.name.equals(uidPackageName)) {
3554                return false;
3555            }
3556            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3557            if (uidPs != null) {
3558                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3559                        libEntry.info.getName());
3560                if (index < 0) {
3561                    continue;
3562                }
3563                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3564                    return false;
3565                }
3566            }
3567        }
3568        return true;
3569    }
3570
3571    @Override
3572    public String[] currentToCanonicalPackageNames(String[] names) {
3573        String[] out = new String[names.length];
3574        // reader
3575        synchronized (mPackages) {
3576            for (int i=names.length-1; i>=0; i--) {
3577                PackageSetting ps = mSettings.mPackages.get(names[i]);
3578                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3579            }
3580        }
3581        return out;
3582    }
3583
3584    @Override
3585    public String[] canonicalToCurrentPackageNames(String[] names) {
3586        String[] out = new String[names.length];
3587        // reader
3588        synchronized (mPackages) {
3589            for (int i=names.length-1; i>=0; i--) {
3590                String cur = mSettings.getRenamedPackageLPr(names[i]);
3591                out[i] = cur != null ? cur : names[i];
3592            }
3593        }
3594        return out;
3595    }
3596
3597    @Override
3598    public int getPackageUid(String packageName, int flags, int userId) {
3599        if (!sUserManager.exists(userId)) return -1;
3600        flags = updateFlagsForPackage(flags, userId, packageName);
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3602                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3603
3604        // reader
3605        synchronized (mPackages) {
3606            final PackageParser.Package p = mPackages.get(packageName);
3607            if (p != null && p.isMatch(flags)) {
3608                return UserHandle.getUid(userId, p.applicationInfo.uid);
3609            }
3610            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3611                final PackageSetting ps = mSettings.mPackages.get(packageName);
3612                if (ps != null && ps.isMatch(flags)) {
3613                    return UserHandle.getUid(userId, ps.appId);
3614                }
3615            }
3616        }
3617
3618        return -1;
3619    }
3620
3621    @Override
3622    public int[] getPackageGids(String packageName, int flags, int userId) {
3623        if (!sUserManager.exists(userId)) return null;
3624        flags = updateFlagsForPackage(flags, userId, packageName);
3625        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3626                false /* requireFullPermission */, false /* checkShell */,
3627                "getPackageGids");
3628
3629        // reader
3630        synchronized (mPackages) {
3631            final PackageParser.Package p = mPackages.get(packageName);
3632            if (p != null && p.isMatch(flags)) {
3633                PackageSetting ps = (PackageSetting) p.mExtras;
3634                // TODO: Shouldn't this be checking for package installed state for userId and
3635                // return null?
3636                return ps.getPermissionsState().computeGids(userId);
3637            }
3638            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3639                final PackageSetting ps = mSettings.mPackages.get(packageName);
3640                if (ps != null && ps.isMatch(flags)) {
3641                    return ps.getPermissionsState().computeGids(userId);
3642                }
3643            }
3644        }
3645
3646        return null;
3647    }
3648
3649    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3650        if (bp.perm != null) {
3651            return PackageParser.generatePermissionInfo(bp.perm, flags);
3652        }
3653        PermissionInfo pi = new PermissionInfo();
3654        pi.name = bp.name;
3655        pi.packageName = bp.sourcePackage;
3656        pi.nonLocalizedLabel = bp.name;
3657        pi.protectionLevel = bp.protectionLevel;
3658        return pi;
3659    }
3660
3661    @Override
3662    public PermissionInfo getPermissionInfo(String name, int flags) {
3663        // reader
3664        synchronized (mPackages) {
3665            final BasePermission p = mSettings.mPermissions.get(name);
3666            if (p != null) {
3667                return generatePermissionInfo(p, flags);
3668            }
3669            return null;
3670        }
3671    }
3672
3673    @Override
3674    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3675            int flags) {
3676        // reader
3677        synchronized (mPackages) {
3678            if (group != null && !mPermissionGroups.containsKey(group)) {
3679                // This is thrown as NameNotFoundException
3680                return null;
3681            }
3682
3683            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3684            for (BasePermission p : mSettings.mPermissions.values()) {
3685                if (group == null) {
3686                    if (p.perm == null || p.perm.info.group == null) {
3687                        out.add(generatePermissionInfo(p, flags));
3688                    }
3689                } else {
3690                    if (p.perm != null && group.equals(p.perm.info.group)) {
3691                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3692                    }
3693                }
3694            }
3695            return new ParceledListSlice<>(out);
3696        }
3697    }
3698
3699    @Override
3700    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3701        // reader
3702        synchronized (mPackages) {
3703            return PackageParser.generatePermissionGroupInfo(
3704                    mPermissionGroups.get(name), flags);
3705        }
3706    }
3707
3708    @Override
3709    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3710        // reader
3711        synchronized (mPackages) {
3712            final int N = mPermissionGroups.size();
3713            ArrayList<PermissionGroupInfo> out
3714                    = new ArrayList<PermissionGroupInfo>(N);
3715            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3716                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3717            }
3718            return new ParceledListSlice<>(out);
3719        }
3720    }
3721
3722    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3723            int uid, int userId) {
3724        if (!sUserManager.exists(userId)) return null;
3725        PackageSetting ps = mSettings.mPackages.get(packageName);
3726        if (ps != null) {
3727            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3728                return null;
3729            }
3730            if (ps.pkg == null) {
3731                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3732                if (pInfo != null) {
3733                    return pInfo.applicationInfo;
3734                }
3735                return null;
3736            }
3737            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3738                    ps.readUserState(userId), userId);
3739            if (ai != null) {
3740                rebaseEnabledOverlays(ai, userId);
3741                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3742            }
3743            return ai;
3744        }
3745        return null;
3746    }
3747
3748    @Override
3749    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3750        if (!sUserManager.exists(userId)) return null;
3751        flags = updateFlagsForApplication(flags, userId, packageName);
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3753                false /* requireFullPermission */, false /* checkShell */, "get application info");
3754
3755        // writer
3756        synchronized (mPackages) {
3757            // Normalize package name to handle renamed packages and static libs
3758            packageName = resolveInternalPackageNameLPr(packageName,
3759                    PackageManager.VERSION_CODE_HIGHEST);
3760
3761            PackageParser.Package p = mPackages.get(packageName);
3762            if (DEBUG_PACKAGE_INFO) Log.v(
3763                    TAG, "getApplicationInfo " + packageName
3764                    + ": " + p);
3765            if (p != null) {
3766                PackageSetting ps = mSettings.mPackages.get(packageName);
3767                if (ps == null) return null;
3768                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3769                    return null;
3770                }
3771                // Note: isEnabledLP() does not apply here - always return info
3772                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3773                        p, flags, ps.readUserState(userId), userId);
3774                if (ai != null) {
3775                    rebaseEnabledOverlays(ai, userId);
3776                    ai.packageName = resolveExternalPackageNameLPr(p);
3777                }
3778                return ai;
3779            }
3780            if ("android".equals(packageName)||"system".equals(packageName)) {
3781                return mAndroidApplication;
3782            }
3783            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3784                // Already generates the external package name
3785                return generateApplicationInfoFromSettingsLPw(packageName,
3786                        Binder.getCallingUid(), flags, userId);
3787            }
3788        }
3789        return null;
3790    }
3791
3792    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3793        List<String> paths = new ArrayList<>();
3794        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3795            mEnabledOverlayPaths.get(userId);
3796        if (userSpecificOverlays != null) {
3797            if (!"android".equals(ai.packageName)) {
3798                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3799                if (frameworkOverlays != null) {
3800                    paths.addAll(frameworkOverlays);
3801                }
3802            }
3803
3804            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3805            if (appOverlays != null) {
3806                paths.addAll(appOverlays);
3807            }
3808        }
3809        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3810    }
3811
3812    private String normalizePackageNameLPr(String packageName) {
3813        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3814        return normalizedPackageName != null ? normalizedPackageName : packageName;
3815    }
3816
3817    @Override
3818    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3819            final IPackageDataObserver observer) {
3820        mContext.enforceCallingOrSelfPermission(
3821                android.Manifest.permission.CLEAR_APP_CACHE, null);
3822        mHandler.post(() -> {
3823            boolean success = false;
3824            try {
3825                freeStorage(volumeUuid, freeStorageSize, 0);
3826                success = true;
3827            } catch (IOException e) {
3828                Slog.w(TAG, e);
3829            }
3830            if (observer != null) {
3831                try {
3832                    observer.onRemoveCompleted(null, success);
3833                } catch (RemoteException e) {
3834                    Slog.w(TAG, e);
3835                }
3836            }
3837        });
3838    }
3839
3840    @Override
3841    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3842            final IntentSender pi) {
3843        mContext.enforceCallingOrSelfPermission(
3844                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3845        mHandler.post(() -> {
3846            boolean success = false;
3847            try {
3848                freeStorage(volumeUuid, freeStorageSize, 0);
3849                success = true;
3850            } catch (IOException e) {
3851                Slog.w(TAG, e);
3852            }
3853            if (pi != null) {
3854                try {
3855                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3856                } catch (SendIntentException e) {
3857                    Slog.w(TAG, e);
3858                }
3859            }
3860        });
3861    }
3862
3863    /**
3864     * Blocking call to clear various types of cached data across the system
3865     * until the requested bytes are available.
3866     */
3867    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3868        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3869        final File file = storage.findPathForUuid(volumeUuid);
3870
3871        if (ENABLE_FREE_CACHE_V2) {
3872            final boolean aggressive = (storageFlags
3873                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3874
3875            // 1. Pre-flight to determine if we have any chance to succeed
3876            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3877
3878            // 3. Consider parsed APK data (aggressive only)
3879            if (aggressive) {
3880                FileUtils.deleteContents(mCacheDir);
3881            }
3882            if (file.getUsableSpace() >= bytes) return;
3883
3884            // 4. Consider cached app data (above quotas)
3885            try {
3886                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3887            } catch (InstallerException ignored) {
3888            }
3889            if (file.getUsableSpace() >= bytes) return;
3890
3891            // 5. Consider shared libraries with refcount=0 and age>2h
3892            // 6. Consider dexopt output (aggressive only)
3893            // 7. Consider ephemeral apps not used in last week
3894
3895            // 8. Consider cached app data (below quotas)
3896            try {
3897                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3898                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3899            } catch (InstallerException ignored) {
3900            }
3901            if (file.getUsableSpace() >= bytes) return;
3902
3903            // 9. Consider DropBox entries
3904            // 10. Consider ephemeral cookies
3905
3906        } else {
3907            try {
3908                mInstaller.freeCache(volumeUuid, bytes, 0);
3909            } catch (InstallerException ignored) {
3910            }
3911            if (file.getUsableSpace() >= bytes) return;
3912        }
3913
3914        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3915    }
3916
3917    /**
3918     * Update given flags based on encryption status of current user.
3919     */
3920    private int updateFlags(int flags, int userId) {
3921        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3922                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3923            // Caller expressed an explicit opinion about what encryption
3924            // aware/unaware components they want to see, so fall through and
3925            // give them what they want
3926        } else {
3927            // Caller expressed no opinion, so match based on user state
3928            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3929                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3930            } else {
3931                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3932            }
3933        }
3934        return flags;
3935    }
3936
3937    private UserManagerInternal getUserManagerInternal() {
3938        if (mUserManagerInternal == null) {
3939            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3940        }
3941        return mUserManagerInternal;
3942    }
3943
3944    private DeviceIdleController.LocalService getDeviceIdleController() {
3945        if (mDeviceIdleController == null) {
3946            mDeviceIdleController =
3947                    LocalServices.getService(DeviceIdleController.LocalService.class);
3948        }
3949        return mDeviceIdleController;
3950    }
3951
3952    /**
3953     * Update given flags when being used to request {@link PackageInfo}.
3954     */
3955    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3956        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3957        boolean triaged = true;
3958        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3959                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3960            // Caller is asking for component details, so they'd better be
3961            // asking for specific encryption matching behavior, or be triaged
3962            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3963                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3964                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3965                triaged = false;
3966            }
3967        }
3968        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3969                | PackageManager.MATCH_SYSTEM_ONLY
3970                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3971            triaged = false;
3972        }
3973        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3974            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3975                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3976                    + Debug.getCallers(5));
3977        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3978                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3979            // If the caller wants all packages and has a restricted profile associated with it,
3980            // then match all users. This is to make sure that launchers that need to access work
3981            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3982            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3983            flags |= PackageManager.MATCH_ANY_USER;
3984        }
3985        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3986            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3987                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3988        }
3989        return updateFlags(flags, userId);
3990    }
3991
3992    /**
3993     * Update given flags when being used to request {@link ApplicationInfo}.
3994     */
3995    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3996        return updateFlagsForPackage(flags, userId, cookie);
3997    }
3998
3999    /**
4000     * Update given flags when being used to request {@link ComponentInfo}.
4001     */
4002    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4003        if (cookie instanceof Intent) {
4004            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4005                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4006            }
4007        }
4008
4009        boolean triaged = true;
4010        // Caller is asking for component details, so they'd better be
4011        // asking for specific encryption matching behavior, or be triaged
4012        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4013                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4014                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4015            triaged = false;
4016        }
4017        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4018            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4019                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4020        }
4021
4022        return updateFlags(flags, userId);
4023    }
4024
4025    /**
4026     * Update given intent when being used to request {@link ResolveInfo}.
4027     */
4028    private Intent updateIntentForResolve(Intent intent) {
4029        if (intent.getSelector() != null) {
4030            intent = intent.getSelector();
4031        }
4032        if (DEBUG_PREFERRED) {
4033            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4034        }
4035        return intent;
4036    }
4037
4038    /**
4039     * Update given flags when being used to request {@link ResolveInfo}.
4040     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4041     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4042     * flag set. However, this flag is only honoured in three circumstances:
4043     * <ul>
4044     * <li>when called from a system process</li>
4045     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4046     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4047     * action and a {@code android.intent.category.BROWSABLE} category</li>
4048     * </ul>
4049     */
4050    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4051        // Safe mode means we shouldn't match any third-party components
4052        if (mSafeMode) {
4053            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4054        }
4055        final int callingUid = Binder.getCallingUid();
4056        if (getInstantAppPackageName(callingUid) != null) {
4057            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4058            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4059            flags |= PackageManager.MATCH_INSTANT;
4060        } else {
4061            // Otherwise, prevent leaking ephemeral components
4062            final boolean isSpecialProcess =
4063                    callingUid == Process.SYSTEM_UID
4064                    || callingUid == Process.SHELL_UID
4065                    || callingUid == 0;
4066            final boolean allowMatchInstant =
4067                    (includeInstantApp
4068                            && Intent.ACTION_VIEW.equals(intent.getAction())
4069                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4070                            && hasWebURI(intent))
4071                    || isSpecialProcess
4072                    || mContext.checkCallingOrSelfPermission(
4073                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4074            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4075            if (!allowMatchInstant) {
4076                flags &= ~PackageManager.MATCH_INSTANT;
4077            }
4078        }
4079        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4080    }
4081
4082    @Override
4083    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4084        if (!sUserManager.exists(userId)) return null;
4085        flags = updateFlagsForComponent(flags, userId, component);
4086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4087                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4088        synchronized (mPackages) {
4089            PackageParser.Activity a = mActivities.mActivities.get(component);
4090
4091            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4092            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4093                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4094                if (ps == null) return null;
4095                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4096                        userId);
4097            }
4098            if (mResolveComponentName.equals(component)) {
4099                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4100                        new PackageUserState(), userId);
4101            }
4102        }
4103        return null;
4104    }
4105
4106    @Override
4107    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4108            String resolvedType) {
4109        synchronized (mPackages) {
4110            if (component.equals(mResolveComponentName)) {
4111                // The resolver supports EVERYTHING!
4112                return true;
4113            }
4114            PackageParser.Activity a = mActivities.mActivities.get(component);
4115            if (a == null) {
4116                return false;
4117            }
4118            for (int i=0; i<a.intents.size(); i++) {
4119                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4120                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4121                    return true;
4122                }
4123            }
4124            return false;
4125        }
4126    }
4127
4128    @Override
4129    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4130        if (!sUserManager.exists(userId)) return null;
4131        flags = updateFlagsForComponent(flags, userId, component);
4132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4133                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4134        synchronized (mPackages) {
4135            PackageParser.Activity a = mReceivers.mActivities.get(component);
4136            if (DEBUG_PACKAGE_INFO) Log.v(
4137                TAG, "getReceiverInfo " + component + ": " + a);
4138            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4139                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4140                if (ps == null) return null;
4141                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4142                        userId);
4143            }
4144        }
4145        return null;
4146    }
4147
4148    @Override
4149    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4150        if (!sUserManager.exists(userId)) return null;
4151        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4152
4153        flags = updateFlagsForPackage(flags, userId, null);
4154
4155        final boolean canSeeStaticLibraries =
4156                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4157                        == PERMISSION_GRANTED
4158                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4159                        == PERMISSION_GRANTED
4160                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4161                        == PERMISSION_GRANTED
4162                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4163                        == PERMISSION_GRANTED;
4164
4165        synchronized (mPackages) {
4166            List<SharedLibraryInfo> result = null;
4167
4168            final int libCount = mSharedLibraries.size();
4169            for (int i = 0; i < libCount; i++) {
4170                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4171                if (versionedLib == null) {
4172                    continue;
4173                }
4174
4175                final int versionCount = versionedLib.size();
4176                for (int j = 0; j < versionCount; j++) {
4177                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4178                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4179                        break;
4180                    }
4181                    final long identity = Binder.clearCallingIdentity();
4182                    try {
4183                        // TODO: We will change version code to long, so in the new API it is long
4184                        PackageInfo packageInfo = getPackageInfoVersioned(
4185                                libInfo.getDeclaringPackage(), flags, userId);
4186                        if (packageInfo == null) {
4187                            continue;
4188                        }
4189                    } finally {
4190                        Binder.restoreCallingIdentity(identity);
4191                    }
4192
4193                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4194                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4195                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4196
4197                    if (result == null) {
4198                        result = new ArrayList<>();
4199                    }
4200                    result.add(resLibInfo);
4201                }
4202            }
4203
4204            return result != null ? new ParceledListSlice<>(result) : null;
4205        }
4206    }
4207
4208    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4209            SharedLibraryInfo libInfo, int flags, int userId) {
4210        List<VersionedPackage> versionedPackages = null;
4211        final int packageCount = mSettings.mPackages.size();
4212        for (int i = 0; i < packageCount; i++) {
4213            PackageSetting ps = mSettings.mPackages.valueAt(i);
4214
4215            if (ps == null) {
4216                continue;
4217            }
4218
4219            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4220                continue;
4221            }
4222
4223            final String libName = libInfo.getName();
4224            if (libInfo.isStatic()) {
4225                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4226                if (libIdx < 0) {
4227                    continue;
4228                }
4229                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4230                    continue;
4231                }
4232                if (versionedPackages == null) {
4233                    versionedPackages = new ArrayList<>();
4234                }
4235                // If the dependent is a static shared lib, use the public package name
4236                String dependentPackageName = ps.name;
4237                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4238                    dependentPackageName = ps.pkg.manifestPackageName;
4239                }
4240                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4241            } else if (ps.pkg != null) {
4242                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4243                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4244                    if (versionedPackages == null) {
4245                        versionedPackages = new ArrayList<>();
4246                    }
4247                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4248                }
4249            }
4250        }
4251
4252        return versionedPackages;
4253    }
4254
4255    @Override
4256    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4257        if (!sUserManager.exists(userId)) return null;
4258        flags = updateFlagsForComponent(flags, userId, component);
4259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4260                false /* requireFullPermission */, false /* checkShell */, "get service info");
4261        synchronized (mPackages) {
4262            PackageParser.Service s = mServices.mServices.get(component);
4263            if (DEBUG_PACKAGE_INFO) Log.v(
4264                TAG, "getServiceInfo " + component + ": " + s);
4265            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4266                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4267                if (ps == null) return null;
4268                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4269                        userId);
4270            }
4271        }
4272        return null;
4273    }
4274
4275    @Override
4276    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4277        if (!sUserManager.exists(userId)) return null;
4278        flags = updateFlagsForComponent(flags, userId, component);
4279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4280                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4281        synchronized (mPackages) {
4282            PackageParser.Provider p = mProviders.mProviders.get(component);
4283            if (DEBUG_PACKAGE_INFO) Log.v(
4284                TAG, "getProviderInfo " + component + ": " + p);
4285            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4286                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4287                if (ps == null) return null;
4288                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4289                        userId);
4290            }
4291        }
4292        return null;
4293    }
4294
4295    @Override
4296    public String[] getSystemSharedLibraryNames() {
4297        synchronized (mPackages) {
4298            Set<String> libs = null;
4299            final int libCount = mSharedLibraries.size();
4300            for (int i = 0; i < libCount; i++) {
4301                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4302                if (versionedLib == null) {
4303                    continue;
4304                }
4305                final int versionCount = versionedLib.size();
4306                for (int j = 0; j < versionCount; j++) {
4307                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4308                    if (!libEntry.info.isStatic()) {
4309                        if (libs == null) {
4310                            libs = new ArraySet<>();
4311                        }
4312                        libs.add(libEntry.info.getName());
4313                        break;
4314                    }
4315                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4316                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4317                            UserHandle.getUserId(Binder.getCallingUid()))) {
4318                        if (libs == null) {
4319                            libs = new ArraySet<>();
4320                        }
4321                        libs.add(libEntry.info.getName());
4322                        break;
4323                    }
4324                }
4325            }
4326
4327            if (libs != null) {
4328                String[] libsArray = new String[libs.size()];
4329                libs.toArray(libsArray);
4330                return libsArray;
4331            }
4332
4333            return null;
4334        }
4335    }
4336
4337    @Override
4338    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4339        synchronized (mPackages) {
4340            return mServicesSystemSharedLibraryPackageName;
4341        }
4342    }
4343
4344    @Override
4345    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4346        synchronized (mPackages) {
4347            return mSharedSystemSharedLibraryPackageName;
4348        }
4349    }
4350
4351    private void updateSequenceNumberLP(String packageName, int[] userList) {
4352        for (int i = userList.length - 1; i >= 0; --i) {
4353            final int userId = userList[i];
4354            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4355            if (changedPackages == null) {
4356                changedPackages = new SparseArray<>();
4357                mChangedPackages.put(userId, changedPackages);
4358            }
4359            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4360            if (sequenceNumbers == null) {
4361                sequenceNumbers = new HashMap<>();
4362                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4363            }
4364            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4365            if (sequenceNumber != null) {
4366                changedPackages.remove(sequenceNumber);
4367            }
4368            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4369            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4370        }
4371        mChangedPackagesSequenceNumber++;
4372    }
4373
4374    @Override
4375    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4376        synchronized (mPackages) {
4377            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4378                return null;
4379            }
4380            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4381            if (changedPackages == null) {
4382                return null;
4383            }
4384            final List<String> packageNames =
4385                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4386            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4387                final String packageName = changedPackages.get(i);
4388                if (packageName != null) {
4389                    packageNames.add(packageName);
4390                }
4391            }
4392            return packageNames.isEmpty()
4393                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4394        }
4395    }
4396
4397    @Override
4398    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4399        ArrayList<FeatureInfo> res;
4400        synchronized (mAvailableFeatures) {
4401            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4402            res.addAll(mAvailableFeatures.values());
4403        }
4404        final FeatureInfo fi = new FeatureInfo();
4405        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4406                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4407        res.add(fi);
4408
4409        return new ParceledListSlice<>(res);
4410    }
4411
4412    @Override
4413    public boolean hasSystemFeature(String name, int version) {
4414        synchronized (mAvailableFeatures) {
4415            final FeatureInfo feat = mAvailableFeatures.get(name);
4416            if (feat == null) {
4417                return false;
4418            } else {
4419                return feat.version >= version;
4420            }
4421        }
4422    }
4423
4424    @Override
4425    public int checkPermission(String permName, String pkgName, int userId) {
4426        if (!sUserManager.exists(userId)) {
4427            return PackageManager.PERMISSION_DENIED;
4428        }
4429
4430        synchronized (mPackages) {
4431            final PackageParser.Package p = mPackages.get(pkgName);
4432            if (p != null && p.mExtras != null) {
4433                final PackageSetting ps = (PackageSetting) p.mExtras;
4434                final PermissionsState permissionsState = ps.getPermissionsState();
4435                if (permissionsState.hasPermission(permName, userId)) {
4436                    return PackageManager.PERMISSION_GRANTED;
4437                }
4438                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4439                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4440                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4441                    return PackageManager.PERMISSION_GRANTED;
4442                }
4443            }
4444        }
4445
4446        return PackageManager.PERMISSION_DENIED;
4447    }
4448
4449    @Override
4450    public int checkUidPermission(String permName, int uid) {
4451        final int userId = UserHandle.getUserId(uid);
4452
4453        if (!sUserManager.exists(userId)) {
4454            return PackageManager.PERMISSION_DENIED;
4455        }
4456
4457        synchronized (mPackages) {
4458            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4459            if (obj != null) {
4460                final SettingBase ps = (SettingBase) obj;
4461                final PermissionsState permissionsState = ps.getPermissionsState();
4462                if (permissionsState.hasPermission(permName, userId)) {
4463                    return PackageManager.PERMISSION_GRANTED;
4464                }
4465                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4466                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4467                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4468                    return PackageManager.PERMISSION_GRANTED;
4469                }
4470            } else {
4471                ArraySet<String> perms = mSystemPermissions.get(uid);
4472                if (perms != null) {
4473                    if (perms.contains(permName)) {
4474                        return PackageManager.PERMISSION_GRANTED;
4475                    }
4476                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4477                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4478                        return PackageManager.PERMISSION_GRANTED;
4479                    }
4480                }
4481            }
4482        }
4483
4484        return PackageManager.PERMISSION_DENIED;
4485    }
4486
4487    @Override
4488    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4489        if (UserHandle.getCallingUserId() != userId) {
4490            mContext.enforceCallingPermission(
4491                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4492                    "isPermissionRevokedByPolicy for user " + userId);
4493        }
4494
4495        if (checkPermission(permission, packageName, userId)
4496                == PackageManager.PERMISSION_GRANTED) {
4497            return false;
4498        }
4499
4500        final long identity = Binder.clearCallingIdentity();
4501        try {
4502            final int flags = getPermissionFlags(permission, packageName, userId);
4503            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4504        } finally {
4505            Binder.restoreCallingIdentity(identity);
4506        }
4507    }
4508
4509    @Override
4510    public String getPermissionControllerPackageName() {
4511        synchronized (mPackages) {
4512            return mRequiredInstallerPackage;
4513        }
4514    }
4515
4516    /**
4517     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4518     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4519     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4520     * @param message the message to log on security exception
4521     */
4522    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4523            boolean checkShell, String message) {
4524        if (userId < 0) {
4525            throw new IllegalArgumentException("Invalid userId " + userId);
4526        }
4527        if (checkShell) {
4528            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4529        }
4530        if (userId == UserHandle.getUserId(callingUid)) return;
4531        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4532            if (requireFullPermission) {
4533                mContext.enforceCallingOrSelfPermission(
4534                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4535            } else {
4536                try {
4537                    mContext.enforceCallingOrSelfPermission(
4538                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4539                } catch (SecurityException se) {
4540                    mContext.enforceCallingOrSelfPermission(
4541                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4542                }
4543            }
4544        }
4545    }
4546
4547    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4548        if (callingUid == Process.SHELL_UID) {
4549            if (userHandle >= 0
4550                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4551                throw new SecurityException("Shell does not have permission to access user "
4552                        + userHandle);
4553            } else if (userHandle < 0) {
4554                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4555                        + Debug.getCallers(3));
4556            }
4557        }
4558    }
4559
4560    private BasePermission findPermissionTreeLP(String permName) {
4561        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4562            if (permName.startsWith(bp.name) &&
4563                    permName.length() > bp.name.length() &&
4564                    permName.charAt(bp.name.length()) == '.') {
4565                return bp;
4566            }
4567        }
4568        return null;
4569    }
4570
4571    private BasePermission checkPermissionTreeLP(String permName) {
4572        if (permName != null) {
4573            BasePermission bp = findPermissionTreeLP(permName);
4574            if (bp != null) {
4575                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4576                    return bp;
4577                }
4578                throw new SecurityException("Calling uid "
4579                        + Binder.getCallingUid()
4580                        + " is not allowed to add to permission tree "
4581                        + bp.name + " owned by uid " + bp.uid);
4582            }
4583        }
4584        throw new SecurityException("No permission tree found for " + permName);
4585    }
4586
4587    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4588        if (s1 == null) {
4589            return s2 == null;
4590        }
4591        if (s2 == null) {
4592            return false;
4593        }
4594        if (s1.getClass() != s2.getClass()) {
4595            return false;
4596        }
4597        return s1.equals(s2);
4598    }
4599
4600    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4601        if (pi1.icon != pi2.icon) return false;
4602        if (pi1.logo != pi2.logo) return false;
4603        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4604        if (!compareStrings(pi1.name, pi2.name)) return false;
4605        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4606        // We'll take care of setting this one.
4607        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4608        // These are not currently stored in settings.
4609        //if (!compareStrings(pi1.group, pi2.group)) return false;
4610        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4611        //if (pi1.labelRes != pi2.labelRes) return false;
4612        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4613        return true;
4614    }
4615
4616    int permissionInfoFootprint(PermissionInfo info) {
4617        int size = info.name.length();
4618        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4619        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4620        return size;
4621    }
4622
4623    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4624        int size = 0;
4625        for (BasePermission perm : mSettings.mPermissions.values()) {
4626            if (perm.uid == tree.uid) {
4627                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4628            }
4629        }
4630        return size;
4631    }
4632
4633    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4634        // We calculate the max size of permissions defined by this uid and throw
4635        // if that plus the size of 'info' would exceed our stated maximum.
4636        if (tree.uid != Process.SYSTEM_UID) {
4637            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4638            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4639                throw new SecurityException("Permission tree size cap exceeded");
4640            }
4641        }
4642    }
4643
4644    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4645        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4646            throw new SecurityException("Label must be specified in permission");
4647        }
4648        BasePermission tree = checkPermissionTreeLP(info.name);
4649        BasePermission bp = mSettings.mPermissions.get(info.name);
4650        boolean added = bp == null;
4651        boolean changed = true;
4652        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4653        if (added) {
4654            enforcePermissionCapLocked(info, tree);
4655            bp = new BasePermission(info.name, tree.sourcePackage,
4656                    BasePermission.TYPE_DYNAMIC);
4657        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4658            throw new SecurityException(
4659                    "Not allowed to modify non-dynamic permission "
4660                    + info.name);
4661        } else {
4662            if (bp.protectionLevel == fixedLevel
4663                    && bp.perm.owner.equals(tree.perm.owner)
4664                    && bp.uid == tree.uid
4665                    && comparePermissionInfos(bp.perm.info, info)) {
4666                changed = false;
4667            }
4668        }
4669        bp.protectionLevel = fixedLevel;
4670        info = new PermissionInfo(info);
4671        info.protectionLevel = fixedLevel;
4672        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4673        bp.perm.info.packageName = tree.perm.info.packageName;
4674        bp.uid = tree.uid;
4675        if (added) {
4676            mSettings.mPermissions.put(info.name, bp);
4677        }
4678        if (changed) {
4679            if (!async) {
4680                mSettings.writeLPr();
4681            } else {
4682                scheduleWriteSettingsLocked();
4683            }
4684        }
4685        return added;
4686    }
4687
4688    @Override
4689    public boolean addPermission(PermissionInfo info) {
4690        synchronized (mPackages) {
4691            return addPermissionLocked(info, false);
4692        }
4693    }
4694
4695    @Override
4696    public boolean addPermissionAsync(PermissionInfo info) {
4697        synchronized (mPackages) {
4698            return addPermissionLocked(info, true);
4699        }
4700    }
4701
4702    @Override
4703    public void removePermission(String name) {
4704        synchronized (mPackages) {
4705            checkPermissionTreeLP(name);
4706            BasePermission bp = mSettings.mPermissions.get(name);
4707            if (bp != null) {
4708                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4709                    throw new SecurityException(
4710                            "Not allowed to modify non-dynamic permission "
4711                            + name);
4712                }
4713                mSettings.mPermissions.remove(name);
4714                mSettings.writeLPr();
4715            }
4716        }
4717    }
4718
4719    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4720            BasePermission bp) {
4721        int index = pkg.requestedPermissions.indexOf(bp.name);
4722        if (index == -1) {
4723            throw new SecurityException("Package " + pkg.packageName
4724                    + " has not requested permission " + bp.name);
4725        }
4726        if (!bp.isRuntime() && !bp.isDevelopment()) {
4727            throw new SecurityException("Permission " + bp.name
4728                    + " is not a changeable permission type");
4729        }
4730    }
4731
4732    @Override
4733    public void grantRuntimePermission(String packageName, String name, final int userId) {
4734        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4735    }
4736
4737    private void grantRuntimePermission(String packageName, String name, final int userId,
4738            boolean overridePolicy) {
4739        if (!sUserManager.exists(userId)) {
4740            Log.e(TAG, "No such user:" + userId);
4741            return;
4742        }
4743
4744        mContext.enforceCallingOrSelfPermission(
4745                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4746                "grantRuntimePermission");
4747
4748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4749                true /* requireFullPermission */, true /* checkShell */,
4750                "grantRuntimePermission");
4751
4752        final int uid;
4753        final SettingBase sb;
4754
4755        synchronized (mPackages) {
4756            final PackageParser.Package pkg = mPackages.get(packageName);
4757            if (pkg == null) {
4758                throw new IllegalArgumentException("Unknown package: " + packageName);
4759            }
4760
4761            final BasePermission bp = mSettings.mPermissions.get(name);
4762            if (bp == null) {
4763                throw new IllegalArgumentException("Unknown permission: " + name);
4764            }
4765
4766            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4767
4768            // If a permission review is required for legacy apps we represent
4769            // their permissions as always granted runtime ones since we need
4770            // to keep the review required permission flag per user while an
4771            // install permission's state is shared across all users.
4772            if (mPermissionReviewRequired
4773                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4774                    && bp.isRuntime()) {
4775                return;
4776            }
4777
4778            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4779            sb = (SettingBase) pkg.mExtras;
4780            if (sb == null) {
4781                throw new IllegalArgumentException("Unknown package: " + packageName);
4782            }
4783
4784            final PermissionsState permissionsState = sb.getPermissionsState();
4785
4786            final int flags = permissionsState.getPermissionFlags(name, userId);
4787            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4788                throw new SecurityException("Cannot grant system fixed permission "
4789                        + name + " for package " + packageName);
4790            }
4791            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4792                throw new SecurityException("Cannot grant policy fixed permission "
4793                        + name + " for package " + packageName);
4794            }
4795
4796            if (bp.isDevelopment()) {
4797                // Development permissions must be handled specially, since they are not
4798                // normal runtime permissions.  For now they apply to all users.
4799                if (permissionsState.grantInstallPermission(bp) !=
4800                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4801                    scheduleWriteSettingsLocked();
4802                }
4803                return;
4804            }
4805
4806            final PackageSetting ps = mSettings.mPackages.get(packageName);
4807            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4808                throw new SecurityException("Cannot grant non-ephemeral permission"
4809                        + name + " for package " + packageName);
4810            }
4811
4812            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4813                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4814                return;
4815            }
4816
4817            final int result = permissionsState.grantRuntimePermission(bp, userId);
4818            switch (result) {
4819                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4820                    return;
4821                }
4822
4823                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4824                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4825                    mHandler.post(new Runnable() {
4826                        @Override
4827                        public void run() {
4828                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4829                        }
4830                    });
4831                }
4832                break;
4833            }
4834
4835            if (bp.isRuntime()) {
4836                logPermissionGranted(mContext, name, packageName);
4837            }
4838
4839            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4840
4841            // Not critical if that is lost - app has to request again.
4842            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4843        }
4844
4845        // Only need to do this if user is initialized. Otherwise it's a new user
4846        // and there are no processes running as the user yet and there's no need
4847        // to make an expensive call to remount processes for the changed permissions.
4848        if (READ_EXTERNAL_STORAGE.equals(name)
4849                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4850            final long token = Binder.clearCallingIdentity();
4851            try {
4852                if (sUserManager.isInitialized(userId)) {
4853                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4854                            StorageManagerInternal.class);
4855                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4856                }
4857            } finally {
4858                Binder.restoreCallingIdentity(token);
4859            }
4860        }
4861    }
4862
4863    @Override
4864    public void revokeRuntimePermission(String packageName, String name, int userId) {
4865        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4866    }
4867
4868    private void revokeRuntimePermission(String packageName, String name, int userId,
4869            boolean overridePolicy) {
4870        if (!sUserManager.exists(userId)) {
4871            Log.e(TAG, "No such user:" + userId);
4872            return;
4873        }
4874
4875        mContext.enforceCallingOrSelfPermission(
4876                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4877                "revokeRuntimePermission");
4878
4879        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4880                true /* requireFullPermission */, true /* checkShell */,
4881                "revokeRuntimePermission");
4882
4883        final int appId;
4884
4885        synchronized (mPackages) {
4886            final PackageParser.Package pkg = mPackages.get(packageName);
4887            if (pkg == null) {
4888                throw new IllegalArgumentException("Unknown package: " + packageName);
4889            }
4890
4891            final BasePermission bp = mSettings.mPermissions.get(name);
4892            if (bp == null) {
4893                throw new IllegalArgumentException("Unknown permission: " + name);
4894            }
4895
4896            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4897
4898            // If a permission review is required for legacy apps we represent
4899            // their permissions as always granted runtime ones since we need
4900            // to keep the review required permission flag per user while an
4901            // install permission's state is shared across all users.
4902            if (mPermissionReviewRequired
4903                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4904                    && bp.isRuntime()) {
4905                return;
4906            }
4907
4908            SettingBase sb = (SettingBase) pkg.mExtras;
4909            if (sb == null) {
4910                throw new IllegalArgumentException("Unknown package: " + packageName);
4911            }
4912
4913            final PermissionsState permissionsState = sb.getPermissionsState();
4914
4915            final int flags = permissionsState.getPermissionFlags(name, userId);
4916            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4917                throw new SecurityException("Cannot revoke system fixed permission "
4918                        + name + " for package " + packageName);
4919            }
4920            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4921                throw new SecurityException("Cannot revoke policy fixed permission "
4922                        + name + " for package " + packageName);
4923            }
4924
4925            if (bp.isDevelopment()) {
4926                // Development permissions must be handled specially, since they are not
4927                // normal runtime permissions.  For now they apply to all users.
4928                if (permissionsState.revokeInstallPermission(bp) !=
4929                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4930                    scheduleWriteSettingsLocked();
4931                }
4932                return;
4933            }
4934
4935            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4936                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4937                return;
4938            }
4939
4940            if (bp.isRuntime()) {
4941                logPermissionRevoked(mContext, name, packageName);
4942            }
4943
4944            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4945
4946            // Critical, after this call app should never have the permission.
4947            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4948
4949            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4950        }
4951
4952        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4953    }
4954
4955    /**
4956     * Get the first event id for the permission.
4957     *
4958     * <p>There are four events for each permission: <ul>
4959     *     <li>Request permission: first id + 0</li>
4960     *     <li>Grant permission: first id + 1</li>
4961     *     <li>Request for permission denied: first id + 2</li>
4962     *     <li>Revoke permission: first id + 3</li>
4963     * </ul></p>
4964     *
4965     * @param name name of the permission
4966     *
4967     * @return The first event id for the permission
4968     */
4969    private static int getBaseEventId(@NonNull String name) {
4970        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4971
4972        if (eventIdIndex == -1) {
4973            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4974                    || "user".equals(Build.TYPE)) {
4975                Log.i(TAG, "Unknown permission " + name);
4976
4977                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4978            } else {
4979                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4980                //
4981                // Also update
4982                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4983                // - metrics_constants.proto
4984                throw new IllegalStateException("Unknown permission " + name);
4985            }
4986        }
4987
4988        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4989    }
4990
4991    /**
4992     * Log that a permission was revoked.
4993     *
4994     * @param context Context of the caller
4995     * @param name name of the permission
4996     * @param packageName package permission if for
4997     */
4998    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4999            @NonNull String packageName) {
5000        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5001    }
5002
5003    /**
5004     * Log that a permission request was granted.
5005     *
5006     * @param context Context of the caller
5007     * @param name name of the permission
5008     * @param packageName package permission if for
5009     */
5010    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5011            @NonNull String packageName) {
5012        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5013    }
5014
5015    @Override
5016    public void resetRuntimePermissions() {
5017        mContext.enforceCallingOrSelfPermission(
5018                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5019                "revokeRuntimePermission");
5020
5021        int callingUid = Binder.getCallingUid();
5022        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5023            mContext.enforceCallingOrSelfPermission(
5024                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5025                    "resetRuntimePermissions");
5026        }
5027
5028        synchronized (mPackages) {
5029            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5030            for (int userId : UserManagerService.getInstance().getUserIds()) {
5031                final int packageCount = mPackages.size();
5032                for (int i = 0; i < packageCount; i++) {
5033                    PackageParser.Package pkg = mPackages.valueAt(i);
5034                    if (!(pkg.mExtras instanceof PackageSetting)) {
5035                        continue;
5036                    }
5037                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5038                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5039                }
5040            }
5041        }
5042    }
5043
5044    @Override
5045    public int getPermissionFlags(String name, String packageName, int userId) {
5046        if (!sUserManager.exists(userId)) {
5047            return 0;
5048        }
5049
5050        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5051
5052        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5053                true /* requireFullPermission */, false /* checkShell */,
5054                "getPermissionFlags");
5055
5056        synchronized (mPackages) {
5057            final PackageParser.Package pkg = mPackages.get(packageName);
5058            if (pkg == null) {
5059                return 0;
5060            }
5061
5062            final BasePermission bp = mSettings.mPermissions.get(name);
5063            if (bp == null) {
5064                return 0;
5065            }
5066
5067            SettingBase sb = (SettingBase) pkg.mExtras;
5068            if (sb == null) {
5069                return 0;
5070            }
5071
5072            PermissionsState permissionsState = sb.getPermissionsState();
5073            return permissionsState.getPermissionFlags(name, userId);
5074        }
5075    }
5076
5077    @Override
5078    public void updatePermissionFlags(String name, String packageName, int flagMask,
5079            int flagValues, int userId) {
5080        if (!sUserManager.exists(userId)) {
5081            return;
5082        }
5083
5084        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5085
5086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5087                true /* requireFullPermission */, true /* checkShell */,
5088                "updatePermissionFlags");
5089
5090        // Only the system can change these flags and nothing else.
5091        if (getCallingUid() != Process.SYSTEM_UID) {
5092            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5093            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5094            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5095            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5096            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5097        }
5098
5099        synchronized (mPackages) {
5100            final PackageParser.Package pkg = mPackages.get(packageName);
5101            if (pkg == null) {
5102                throw new IllegalArgumentException("Unknown package: " + packageName);
5103            }
5104
5105            final BasePermission bp = mSettings.mPermissions.get(name);
5106            if (bp == null) {
5107                throw new IllegalArgumentException("Unknown permission: " + name);
5108            }
5109
5110            SettingBase sb = (SettingBase) pkg.mExtras;
5111            if (sb == null) {
5112                throw new IllegalArgumentException("Unknown package: " + packageName);
5113            }
5114
5115            PermissionsState permissionsState = sb.getPermissionsState();
5116
5117            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5118
5119            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5120                // Install and runtime permissions are stored in different places,
5121                // so figure out what permission changed and persist the change.
5122                if (permissionsState.getInstallPermissionState(name) != null) {
5123                    scheduleWriteSettingsLocked();
5124                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5125                        || hadState) {
5126                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5127                }
5128            }
5129        }
5130    }
5131
5132    /**
5133     * Update the permission flags for all packages and runtime permissions of a user in order
5134     * to allow device or profile owner to remove POLICY_FIXED.
5135     */
5136    @Override
5137    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5138        if (!sUserManager.exists(userId)) {
5139            return;
5140        }
5141
5142        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5143
5144        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5145                true /* requireFullPermission */, true /* checkShell */,
5146                "updatePermissionFlagsForAllApps");
5147
5148        // Only the system can change system fixed flags.
5149        if (getCallingUid() != Process.SYSTEM_UID) {
5150            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5151            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5152        }
5153
5154        synchronized (mPackages) {
5155            boolean changed = false;
5156            final int packageCount = mPackages.size();
5157            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5158                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5159                SettingBase sb = (SettingBase) pkg.mExtras;
5160                if (sb == null) {
5161                    continue;
5162                }
5163                PermissionsState permissionsState = sb.getPermissionsState();
5164                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5165                        userId, flagMask, flagValues);
5166            }
5167            if (changed) {
5168                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5169            }
5170        }
5171    }
5172
5173    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5174        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5175                != PackageManager.PERMISSION_GRANTED
5176            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5177                != PackageManager.PERMISSION_GRANTED) {
5178            throw new SecurityException(message + " requires "
5179                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5180                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5181        }
5182    }
5183
5184    @Override
5185    public boolean shouldShowRequestPermissionRationale(String permissionName,
5186            String packageName, int userId) {
5187        if (UserHandle.getCallingUserId() != userId) {
5188            mContext.enforceCallingPermission(
5189                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5190                    "canShowRequestPermissionRationale for user " + userId);
5191        }
5192
5193        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5194        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5195            return false;
5196        }
5197
5198        if (checkPermission(permissionName, packageName, userId)
5199                == PackageManager.PERMISSION_GRANTED) {
5200            return false;
5201        }
5202
5203        final int flags;
5204
5205        final long identity = Binder.clearCallingIdentity();
5206        try {
5207            flags = getPermissionFlags(permissionName,
5208                    packageName, userId);
5209        } finally {
5210            Binder.restoreCallingIdentity(identity);
5211        }
5212
5213        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5214                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5215                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5216
5217        if ((flags & fixedFlags) != 0) {
5218            return false;
5219        }
5220
5221        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5222    }
5223
5224    @Override
5225    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5226        mContext.enforceCallingOrSelfPermission(
5227                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5228                "addOnPermissionsChangeListener");
5229
5230        synchronized (mPackages) {
5231            mOnPermissionChangeListeners.addListenerLocked(listener);
5232        }
5233    }
5234
5235    @Override
5236    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5237        synchronized (mPackages) {
5238            mOnPermissionChangeListeners.removeListenerLocked(listener);
5239        }
5240    }
5241
5242    @Override
5243    public boolean isProtectedBroadcast(String actionName) {
5244        synchronized (mPackages) {
5245            if (mProtectedBroadcasts.contains(actionName)) {
5246                return true;
5247            } else if (actionName != null) {
5248                // TODO: remove these terrible hacks
5249                if (actionName.startsWith("android.net.netmon.lingerExpired")
5250                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5251                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5252                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5253                    return true;
5254                }
5255            }
5256        }
5257        return false;
5258    }
5259
5260    @Override
5261    public int checkSignatures(String pkg1, String pkg2) {
5262        synchronized (mPackages) {
5263            final PackageParser.Package p1 = mPackages.get(pkg1);
5264            final PackageParser.Package p2 = mPackages.get(pkg2);
5265            if (p1 == null || p1.mExtras == null
5266                    || p2 == null || p2.mExtras == null) {
5267                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5268            }
5269            return compareSignatures(p1.mSignatures, p2.mSignatures);
5270        }
5271    }
5272
5273    @Override
5274    public int checkUidSignatures(int uid1, int uid2) {
5275        // Map to base uids.
5276        uid1 = UserHandle.getAppId(uid1);
5277        uid2 = UserHandle.getAppId(uid2);
5278        // reader
5279        synchronized (mPackages) {
5280            Signature[] s1;
5281            Signature[] s2;
5282            Object obj = mSettings.getUserIdLPr(uid1);
5283            if (obj != null) {
5284                if (obj instanceof SharedUserSetting) {
5285                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5286                } else if (obj instanceof PackageSetting) {
5287                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5288                } else {
5289                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5290                }
5291            } else {
5292                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5293            }
5294            obj = mSettings.getUserIdLPr(uid2);
5295            if (obj != null) {
5296                if (obj instanceof SharedUserSetting) {
5297                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5298                } else if (obj instanceof PackageSetting) {
5299                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5300                } else {
5301                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5302                }
5303            } else {
5304                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5305            }
5306            return compareSignatures(s1, s2);
5307        }
5308    }
5309
5310    /**
5311     * This method should typically only be used when granting or revoking
5312     * permissions, since the app may immediately restart after this call.
5313     * <p>
5314     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5315     * guard your work against the app being relaunched.
5316     */
5317    private void killUid(int appId, int userId, String reason) {
5318        final long identity = Binder.clearCallingIdentity();
5319        try {
5320            IActivityManager am = ActivityManager.getService();
5321            if (am != null) {
5322                try {
5323                    am.killUid(appId, userId, reason);
5324                } catch (RemoteException e) {
5325                    /* ignore - same process */
5326                }
5327            }
5328        } finally {
5329            Binder.restoreCallingIdentity(identity);
5330        }
5331    }
5332
5333    /**
5334     * Compares two sets of signatures. Returns:
5335     * <br />
5336     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5337     * <br />
5338     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5339     * <br />
5340     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5341     * <br />
5342     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5343     * <br />
5344     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5345     */
5346    static int compareSignatures(Signature[] s1, Signature[] s2) {
5347        if (s1 == null) {
5348            return s2 == null
5349                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5350                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5351        }
5352
5353        if (s2 == null) {
5354            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5355        }
5356
5357        if (s1.length != s2.length) {
5358            return PackageManager.SIGNATURE_NO_MATCH;
5359        }
5360
5361        // Since both signature sets are of size 1, we can compare without HashSets.
5362        if (s1.length == 1) {
5363            return s1[0].equals(s2[0]) ?
5364                    PackageManager.SIGNATURE_MATCH :
5365                    PackageManager.SIGNATURE_NO_MATCH;
5366        }
5367
5368        ArraySet<Signature> set1 = new ArraySet<Signature>();
5369        for (Signature sig : s1) {
5370            set1.add(sig);
5371        }
5372        ArraySet<Signature> set2 = new ArraySet<Signature>();
5373        for (Signature sig : s2) {
5374            set2.add(sig);
5375        }
5376        // Make sure s2 contains all signatures in s1.
5377        if (set1.equals(set2)) {
5378            return PackageManager.SIGNATURE_MATCH;
5379        }
5380        return PackageManager.SIGNATURE_NO_MATCH;
5381    }
5382
5383    /**
5384     * If the database version for this type of package (internal storage or
5385     * external storage) is less than the version where package signatures
5386     * were updated, return true.
5387     */
5388    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5389        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5390        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5391    }
5392
5393    /**
5394     * Used for backward compatibility to make sure any packages with
5395     * certificate chains get upgraded to the new style. {@code existingSigs}
5396     * will be in the old format (since they were stored on disk from before the
5397     * system upgrade) and {@code scannedSigs} will be in the newer format.
5398     */
5399    private int compareSignaturesCompat(PackageSignatures existingSigs,
5400            PackageParser.Package scannedPkg) {
5401        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5402            return PackageManager.SIGNATURE_NO_MATCH;
5403        }
5404
5405        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5406        for (Signature sig : existingSigs.mSignatures) {
5407            existingSet.add(sig);
5408        }
5409        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5410        for (Signature sig : scannedPkg.mSignatures) {
5411            try {
5412                Signature[] chainSignatures = sig.getChainSignatures();
5413                for (Signature chainSig : chainSignatures) {
5414                    scannedCompatSet.add(chainSig);
5415                }
5416            } catch (CertificateEncodingException e) {
5417                scannedCompatSet.add(sig);
5418            }
5419        }
5420        /*
5421         * Make sure the expanded scanned set contains all signatures in the
5422         * existing one.
5423         */
5424        if (scannedCompatSet.equals(existingSet)) {
5425            // Migrate the old signatures to the new scheme.
5426            existingSigs.assignSignatures(scannedPkg.mSignatures);
5427            // The new KeySets will be re-added later in the scanning process.
5428            synchronized (mPackages) {
5429                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5430            }
5431            return PackageManager.SIGNATURE_MATCH;
5432        }
5433        return PackageManager.SIGNATURE_NO_MATCH;
5434    }
5435
5436    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5437        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5438        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5439    }
5440
5441    private int compareSignaturesRecover(PackageSignatures existingSigs,
5442            PackageParser.Package scannedPkg) {
5443        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5444            return PackageManager.SIGNATURE_NO_MATCH;
5445        }
5446
5447        String msg = null;
5448        try {
5449            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5450                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5451                        + scannedPkg.packageName);
5452                return PackageManager.SIGNATURE_MATCH;
5453            }
5454        } catch (CertificateException e) {
5455            msg = e.getMessage();
5456        }
5457
5458        logCriticalInfo(Log.INFO,
5459                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5460        return PackageManager.SIGNATURE_NO_MATCH;
5461    }
5462
5463    @Override
5464    public List<String> getAllPackages() {
5465        synchronized (mPackages) {
5466            return new ArrayList<String>(mPackages.keySet());
5467        }
5468    }
5469
5470    @Override
5471    public String[] getPackagesForUid(int uid) {
5472        final int userId = UserHandle.getUserId(uid);
5473        uid = UserHandle.getAppId(uid);
5474        // reader
5475        synchronized (mPackages) {
5476            Object obj = mSettings.getUserIdLPr(uid);
5477            if (obj instanceof SharedUserSetting) {
5478                final SharedUserSetting sus = (SharedUserSetting) obj;
5479                final int N = sus.packages.size();
5480                String[] res = new String[N];
5481                final Iterator<PackageSetting> it = sus.packages.iterator();
5482                int i = 0;
5483                while (it.hasNext()) {
5484                    PackageSetting ps = it.next();
5485                    if (ps.getInstalled(userId)) {
5486                        res[i++] = ps.name;
5487                    } else {
5488                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5489                    }
5490                }
5491                return res;
5492            } else if (obj instanceof PackageSetting) {
5493                final PackageSetting ps = (PackageSetting) obj;
5494                if (ps.getInstalled(userId)) {
5495                    return new String[]{ps.name};
5496                }
5497            }
5498        }
5499        return null;
5500    }
5501
5502    @Override
5503    public String getNameForUid(int uid) {
5504        // reader
5505        synchronized (mPackages) {
5506            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5507            if (obj instanceof SharedUserSetting) {
5508                final SharedUserSetting sus = (SharedUserSetting) obj;
5509                return sus.name + ":" + sus.userId;
5510            } else if (obj instanceof PackageSetting) {
5511                final PackageSetting ps = (PackageSetting) obj;
5512                return ps.name;
5513            }
5514        }
5515        return null;
5516    }
5517
5518    @Override
5519    public int getUidForSharedUser(String sharedUserName) {
5520        if(sharedUserName == null) {
5521            return -1;
5522        }
5523        // reader
5524        synchronized (mPackages) {
5525            SharedUserSetting suid;
5526            try {
5527                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5528                if (suid != null) {
5529                    return suid.userId;
5530                }
5531            } catch (PackageManagerException ignore) {
5532                // can't happen, but, still need to catch it
5533            }
5534            return -1;
5535        }
5536    }
5537
5538    @Override
5539    public int getFlagsForUid(int uid) {
5540        synchronized (mPackages) {
5541            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5542            if (obj instanceof SharedUserSetting) {
5543                final SharedUserSetting sus = (SharedUserSetting) obj;
5544                return sus.pkgFlags;
5545            } else if (obj instanceof PackageSetting) {
5546                final PackageSetting ps = (PackageSetting) obj;
5547                return ps.pkgFlags;
5548            }
5549        }
5550        return 0;
5551    }
5552
5553    @Override
5554    public int getPrivateFlagsForUid(int uid) {
5555        synchronized (mPackages) {
5556            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5557            if (obj instanceof SharedUserSetting) {
5558                final SharedUserSetting sus = (SharedUserSetting) obj;
5559                return sus.pkgPrivateFlags;
5560            } else if (obj instanceof PackageSetting) {
5561                final PackageSetting ps = (PackageSetting) obj;
5562                return ps.pkgPrivateFlags;
5563            }
5564        }
5565        return 0;
5566    }
5567
5568    @Override
5569    public boolean isUidPrivileged(int uid) {
5570        uid = UserHandle.getAppId(uid);
5571        // reader
5572        synchronized (mPackages) {
5573            Object obj = mSettings.getUserIdLPr(uid);
5574            if (obj instanceof SharedUserSetting) {
5575                final SharedUserSetting sus = (SharedUserSetting) obj;
5576                final Iterator<PackageSetting> it = sus.packages.iterator();
5577                while (it.hasNext()) {
5578                    if (it.next().isPrivileged()) {
5579                        return true;
5580                    }
5581                }
5582            } else if (obj instanceof PackageSetting) {
5583                final PackageSetting ps = (PackageSetting) obj;
5584                return ps.isPrivileged();
5585            }
5586        }
5587        return false;
5588    }
5589
5590    @Override
5591    public String[] getAppOpPermissionPackages(String permissionName) {
5592        synchronized (mPackages) {
5593            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5594            if (pkgs == null) {
5595                return null;
5596            }
5597            return pkgs.toArray(new String[pkgs.size()]);
5598        }
5599    }
5600
5601    @Override
5602    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5603            int flags, int userId) {
5604        return resolveIntentInternal(
5605                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5606    }
5607
5608    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5609            int flags, int userId, boolean includeInstantApp) {
5610        try {
5611            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5612
5613            if (!sUserManager.exists(userId)) return null;
5614            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5615            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5616                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5617
5618            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5619            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5620                    flags, userId, includeInstantApp);
5621            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5622
5623            final ResolveInfo bestChoice =
5624                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5625            return bestChoice;
5626        } finally {
5627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5628        }
5629    }
5630
5631    @Override
5632    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5633        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5634            throw new SecurityException(
5635                    "findPersistentPreferredActivity can only be run by the system");
5636        }
5637        if (!sUserManager.exists(userId)) {
5638            return null;
5639        }
5640        intent = updateIntentForResolve(intent);
5641        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5642        final int flags = updateFlagsForResolve(0, userId, intent, false);
5643        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5644                userId);
5645        synchronized (mPackages) {
5646            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5647                    userId);
5648        }
5649    }
5650
5651    @Override
5652    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5653            IntentFilter filter, int match, ComponentName activity) {
5654        final int userId = UserHandle.getCallingUserId();
5655        if (DEBUG_PREFERRED) {
5656            Log.v(TAG, "setLastChosenActivity intent=" + intent
5657                + " resolvedType=" + resolvedType
5658                + " flags=" + flags
5659                + " filter=" + filter
5660                + " match=" + match
5661                + " activity=" + activity);
5662            filter.dump(new PrintStreamPrinter(System.out), "    ");
5663        }
5664        intent.setComponent(null);
5665        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5666                userId);
5667        // Find any earlier preferred or last chosen entries and nuke them
5668        findPreferredActivity(intent, resolvedType,
5669                flags, query, 0, false, true, false, userId);
5670        // Add the new activity as the last chosen for this filter
5671        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5672                "Setting last chosen");
5673    }
5674
5675    @Override
5676    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5677        final int userId = UserHandle.getCallingUserId();
5678        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5679        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5680                userId);
5681        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5682                false, false, false, userId);
5683    }
5684
5685    private boolean isEphemeralDisabled() {
5686        // ephemeral apps have been disabled across the board
5687        if (DISABLE_EPHEMERAL_APPS) {
5688            return true;
5689        }
5690        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5691        if (!mSystemReady) {
5692            return true;
5693        }
5694        // we can't get a content resolver until the system is ready; these checks must happen last
5695        final ContentResolver resolver = mContext.getContentResolver();
5696        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5697            return true;
5698        }
5699        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5700    }
5701
5702    private boolean isEphemeralAllowed(
5703            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5704            boolean skipPackageCheck) {
5705        // Short circuit and return early if possible.
5706        if (isEphemeralDisabled()) {
5707            return false;
5708        }
5709        final int callingUser = UserHandle.getCallingUserId();
5710        if (callingUser != UserHandle.USER_SYSTEM) {
5711            return false;
5712        }
5713        if (mInstantAppResolverConnection == null) {
5714            return false;
5715        }
5716        if (mInstantAppInstallerComponent == null) {
5717            return false;
5718        }
5719        if (intent.getComponent() != null) {
5720            return false;
5721        }
5722        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5723            return false;
5724        }
5725        if (!skipPackageCheck && intent.getPackage() != null) {
5726            return false;
5727        }
5728        final boolean isWebUri = hasWebURI(intent);
5729        if (!isWebUri || intent.getData().getHost() == null) {
5730            return false;
5731        }
5732        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5733        // Or if there's already an ephemeral app installed that handles the action
5734        synchronized (mPackages) {
5735            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5736            for (int n = 0; n < count; n++) {
5737                ResolveInfo info = resolvedActivities.get(n);
5738                String packageName = info.activityInfo.packageName;
5739                PackageSetting ps = mSettings.mPackages.get(packageName);
5740                if (ps != null) {
5741                    // Try to get the status from User settings first
5742                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5743                    int status = (int) (packedStatus >> 32);
5744                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5745                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5746                        if (DEBUG_EPHEMERAL) {
5747                            Slog.v(TAG, "DENY ephemeral apps;"
5748                                + " pkg: " + packageName + ", status: " + status);
5749                        }
5750                        return false;
5751                    }
5752                    if (ps.getInstantApp(userId)) {
5753                        return false;
5754                    }
5755                }
5756            }
5757        }
5758        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5759        return true;
5760    }
5761
5762    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5763            Intent origIntent, String resolvedType, String callingPackage,
5764            int userId) {
5765        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5766                new EphemeralRequest(responseObj, origIntent, resolvedType,
5767                        callingPackage, userId));
5768        mHandler.sendMessage(msg);
5769    }
5770
5771    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5772            int flags, List<ResolveInfo> query, int userId) {
5773        if (query != null) {
5774            final int N = query.size();
5775            if (N == 1) {
5776                return query.get(0);
5777            } else if (N > 1) {
5778                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5779                // If there is more than one activity with the same priority,
5780                // then let the user decide between them.
5781                ResolveInfo r0 = query.get(0);
5782                ResolveInfo r1 = query.get(1);
5783                if (DEBUG_INTENT_MATCHING || debug) {
5784                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5785                            + r1.activityInfo.name + "=" + r1.priority);
5786                }
5787                // If the first activity has a higher priority, or a different
5788                // default, then it is always desirable to pick it.
5789                if (r0.priority != r1.priority
5790                        || r0.preferredOrder != r1.preferredOrder
5791                        || r0.isDefault != r1.isDefault) {
5792                    return query.get(0);
5793                }
5794                // If we have saved a preference for a preferred activity for
5795                // this Intent, use that.
5796                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5797                        flags, query, r0.priority, true, false, debug, userId);
5798                if (ri != null) {
5799                    return ri;
5800                }
5801                // If we have an ephemeral app, use it
5802                for (int i = 0; i < N; i++) {
5803                    ri = query.get(i);
5804                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5805                        return ri;
5806                    }
5807                }
5808                ri = new ResolveInfo(mResolveInfo);
5809                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5810                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5811                // If all of the options come from the same package, show the application's
5812                // label and icon instead of the generic resolver's.
5813                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5814                // and then throw away the ResolveInfo itself, meaning that the caller loses
5815                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5816                // a fallback for this case; we only set the target package's resources on
5817                // the ResolveInfo, not the ActivityInfo.
5818                final String intentPackage = intent.getPackage();
5819                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5820                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5821                    ri.resolvePackageName = intentPackage;
5822                    if (userNeedsBadging(userId)) {
5823                        ri.noResourceId = true;
5824                    } else {
5825                        ri.icon = appi.icon;
5826                    }
5827                    ri.iconResourceId = appi.icon;
5828                    ri.labelRes = appi.labelRes;
5829                }
5830                ri.activityInfo.applicationInfo = new ApplicationInfo(
5831                        ri.activityInfo.applicationInfo);
5832                if (userId != 0) {
5833                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5834                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5835                }
5836                // Make sure that the resolver is displayable in car mode
5837                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5838                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5839                return ri;
5840            }
5841        }
5842        return null;
5843    }
5844
5845    /**
5846     * Return true if the given list is not empty and all of its contents have
5847     * an activityInfo with the given package name.
5848     */
5849    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5850        if (ArrayUtils.isEmpty(list)) {
5851            return false;
5852        }
5853        for (int i = 0, N = list.size(); i < N; i++) {
5854            final ResolveInfo ri = list.get(i);
5855            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5856            if (ai == null || !packageName.equals(ai.packageName)) {
5857                return false;
5858            }
5859        }
5860        return true;
5861    }
5862
5863    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5864            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5865        final int N = query.size();
5866        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5867                .get(userId);
5868        // Get the list of persistent preferred activities that handle the intent
5869        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5870        List<PersistentPreferredActivity> pprefs = ppir != null
5871                ? ppir.queryIntent(intent, resolvedType,
5872                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5873                        userId)
5874                : null;
5875        if (pprefs != null && pprefs.size() > 0) {
5876            final int M = pprefs.size();
5877            for (int i=0; i<M; i++) {
5878                final PersistentPreferredActivity ppa = pprefs.get(i);
5879                if (DEBUG_PREFERRED || debug) {
5880                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5881                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5882                            + "\n  component=" + ppa.mComponent);
5883                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5884                }
5885                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5886                        flags | MATCH_DISABLED_COMPONENTS, userId);
5887                if (DEBUG_PREFERRED || debug) {
5888                    Slog.v(TAG, "Found persistent preferred activity:");
5889                    if (ai != null) {
5890                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5891                    } else {
5892                        Slog.v(TAG, "  null");
5893                    }
5894                }
5895                if (ai == null) {
5896                    // This previously registered persistent preferred activity
5897                    // component is no longer known. Ignore it and do NOT remove it.
5898                    continue;
5899                }
5900                for (int j=0; j<N; j++) {
5901                    final ResolveInfo ri = query.get(j);
5902                    if (!ri.activityInfo.applicationInfo.packageName
5903                            .equals(ai.applicationInfo.packageName)) {
5904                        continue;
5905                    }
5906                    if (!ri.activityInfo.name.equals(ai.name)) {
5907                        continue;
5908                    }
5909                    //  Found a persistent preference that can handle the intent.
5910                    if (DEBUG_PREFERRED || debug) {
5911                        Slog.v(TAG, "Returning persistent preferred activity: " +
5912                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5913                    }
5914                    return ri;
5915                }
5916            }
5917        }
5918        return null;
5919    }
5920
5921    // TODO: handle preferred activities missing while user has amnesia
5922    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5923            List<ResolveInfo> query, int priority, boolean always,
5924            boolean removeMatches, boolean debug, int userId) {
5925        if (!sUserManager.exists(userId)) return null;
5926        flags = updateFlagsForResolve(flags, userId, intent, false);
5927        intent = updateIntentForResolve(intent);
5928        // writer
5929        synchronized (mPackages) {
5930            // Try to find a matching persistent preferred activity.
5931            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5932                    debug, userId);
5933
5934            // If a persistent preferred activity matched, use it.
5935            if (pri != null) {
5936                return pri;
5937            }
5938
5939            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5940            // Get the list of preferred activities that handle the intent
5941            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5942            List<PreferredActivity> prefs = pir != null
5943                    ? pir.queryIntent(intent, resolvedType,
5944                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5945                            userId)
5946                    : null;
5947            if (prefs != null && prefs.size() > 0) {
5948                boolean changed = false;
5949                try {
5950                    // First figure out how good the original match set is.
5951                    // We will only allow preferred activities that came
5952                    // from the same match quality.
5953                    int match = 0;
5954
5955                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5956
5957                    final int N = query.size();
5958                    for (int j=0; j<N; j++) {
5959                        final ResolveInfo ri = query.get(j);
5960                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5961                                + ": 0x" + Integer.toHexString(match));
5962                        if (ri.match > match) {
5963                            match = ri.match;
5964                        }
5965                    }
5966
5967                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5968                            + Integer.toHexString(match));
5969
5970                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5971                    final int M = prefs.size();
5972                    for (int i=0; i<M; i++) {
5973                        final PreferredActivity pa = prefs.get(i);
5974                        if (DEBUG_PREFERRED || debug) {
5975                            Slog.v(TAG, "Checking PreferredActivity ds="
5976                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5977                                    + "\n  component=" + pa.mPref.mComponent);
5978                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5979                        }
5980                        if (pa.mPref.mMatch != match) {
5981                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5982                                    + Integer.toHexString(pa.mPref.mMatch));
5983                            continue;
5984                        }
5985                        // If it's not an "always" type preferred activity and that's what we're
5986                        // looking for, skip it.
5987                        if (always && !pa.mPref.mAlways) {
5988                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5989                            continue;
5990                        }
5991                        final ActivityInfo ai = getActivityInfo(
5992                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5993                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5994                                userId);
5995                        if (DEBUG_PREFERRED || debug) {
5996                            Slog.v(TAG, "Found preferred activity:");
5997                            if (ai != null) {
5998                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5999                            } else {
6000                                Slog.v(TAG, "  null");
6001                            }
6002                        }
6003                        if (ai == null) {
6004                            // This previously registered preferred activity
6005                            // component is no longer known.  Most likely an update
6006                            // to the app was installed and in the new version this
6007                            // component no longer exists.  Clean it up by removing
6008                            // it from the preferred activities list, and skip it.
6009                            Slog.w(TAG, "Removing dangling preferred activity: "
6010                                    + pa.mPref.mComponent);
6011                            pir.removeFilter(pa);
6012                            changed = true;
6013                            continue;
6014                        }
6015                        for (int j=0; j<N; j++) {
6016                            final ResolveInfo ri = query.get(j);
6017                            if (!ri.activityInfo.applicationInfo.packageName
6018                                    .equals(ai.applicationInfo.packageName)) {
6019                                continue;
6020                            }
6021                            if (!ri.activityInfo.name.equals(ai.name)) {
6022                                continue;
6023                            }
6024
6025                            if (removeMatches) {
6026                                pir.removeFilter(pa);
6027                                changed = true;
6028                                if (DEBUG_PREFERRED) {
6029                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6030                                }
6031                                break;
6032                            }
6033
6034                            // Okay we found a previously set preferred or last chosen app.
6035                            // If the result set is different from when this
6036                            // was created, we need to clear it and re-ask the
6037                            // user their preference, if we're looking for an "always" type entry.
6038                            if (always && !pa.mPref.sameSet(query)) {
6039                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6040                                        + intent + " type " + resolvedType);
6041                                if (DEBUG_PREFERRED) {
6042                                    Slog.v(TAG, "Removing preferred activity since set changed "
6043                                            + pa.mPref.mComponent);
6044                                }
6045                                pir.removeFilter(pa);
6046                                // Re-add the filter as a "last chosen" entry (!always)
6047                                PreferredActivity lastChosen = new PreferredActivity(
6048                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6049                                pir.addFilter(lastChosen);
6050                                changed = true;
6051                                return null;
6052                            }
6053
6054                            // Yay! Either the set matched or we're looking for the last chosen
6055                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6056                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6057                            return ri;
6058                        }
6059                    }
6060                } finally {
6061                    if (changed) {
6062                        if (DEBUG_PREFERRED) {
6063                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6064                        }
6065                        scheduleWritePackageRestrictionsLocked(userId);
6066                    }
6067                }
6068            }
6069        }
6070        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6071        return null;
6072    }
6073
6074    /*
6075     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6076     */
6077    @Override
6078    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6079            int targetUserId) {
6080        mContext.enforceCallingOrSelfPermission(
6081                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6082        List<CrossProfileIntentFilter> matches =
6083                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6084        if (matches != null) {
6085            int size = matches.size();
6086            for (int i = 0; i < size; i++) {
6087                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6088            }
6089        }
6090        if (hasWebURI(intent)) {
6091            // cross-profile app linking works only towards the parent.
6092            final UserInfo parent = getProfileParent(sourceUserId);
6093            synchronized(mPackages) {
6094                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6095                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6096                        intent, resolvedType, flags, sourceUserId, parent.id);
6097                return xpDomainInfo != null;
6098            }
6099        }
6100        return false;
6101    }
6102
6103    private UserInfo getProfileParent(int userId) {
6104        final long identity = Binder.clearCallingIdentity();
6105        try {
6106            return sUserManager.getProfileParent(userId);
6107        } finally {
6108            Binder.restoreCallingIdentity(identity);
6109        }
6110    }
6111
6112    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6113            String resolvedType, int userId) {
6114        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6115        if (resolver != null) {
6116            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6117        }
6118        return null;
6119    }
6120
6121    @Override
6122    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6123            String resolvedType, int flags, int userId) {
6124        try {
6125            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6126
6127            return new ParceledListSlice<>(
6128                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6129        } finally {
6130            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6131        }
6132    }
6133
6134    /**
6135     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6136     * instant, returns {@code null}.
6137     */
6138    private String getInstantAppPackageName(int callingUid) {
6139        final int appId = UserHandle.getAppId(callingUid);
6140        synchronized (mPackages) {
6141            final Object obj = mSettings.getUserIdLPr(appId);
6142            if (obj instanceof PackageSetting) {
6143                final PackageSetting ps = (PackageSetting) obj;
6144                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6145                return isInstantApp ? ps.pkg.packageName : null;
6146            }
6147        }
6148        return null;
6149    }
6150
6151    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6152            String resolvedType, int flags, int userId) {
6153        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6154    }
6155
6156    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6157            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6158        if (!sUserManager.exists(userId)) return Collections.emptyList();
6159        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6160        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6161        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6162                false /* requireFullPermission */, false /* checkShell */,
6163                "query intent activities");
6164        ComponentName comp = intent.getComponent();
6165        if (comp == null) {
6166            if (intent.getSelector() != null) {
6167                intent = intent.getSelector();
6168                comp = intent.getComponent();
6169            }
6170        }
6171
6172        if (comp != null) {
6173            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6174            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6175            if (ai != null) {
6176                // When specifying an explicit component, we prevent the activity from being
6177                // used when either 1) the calling package is normal and the activity is within
6178                // an ephemeral application or 2) the calling package is ephemeral and the
6179                // activity is not visible to ephemeral applications.
6180                final boolean matchInstantApp =
6181                        (flags & PackageManager.MATCH_INSTANT) != 0;
6182                final boolean matchVisibleToInstantAppOnly =
6183                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6184                final boolean isCallerInstantApp =
6185                        instantAppPkgName != null;
6186                final boolean isTargetSameInstantApp =
6187                        comp.getPackageName().equals(instantAppPkgName);
6188                final boolean isTargetInstantApp =
6189                        (ai.applicationInfo.privateFlags
6190                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6191                final boolean isTargetHiddenFromInstantApp =
6192                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6193                final boolean blockResolution =
6194                        !isTargetSameInstantApp
6195                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6196                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6197                                        && isTargetHiddenFromInstantApp));
6198                if (!blockResolution) {
6199                    final ResolveInfo ri = new ResolveInfo();
6200                    ri.activityInfo = ai;
6201                    list.add(ri);
6202                }
6203            }
6204            return applyPostResolutionFilter(list, instantAppPkgName);
6205        }
6206
6207        // reader
6208        boolean sortResult = false;
6209        boolean addEphemeral = false;
6210        List<ResolveInfo> result;
6211        final String pkgName = intent.getPackage();
6212        synchronized (mPackages) {
6213            if (pkgName == null) {
6214                List<CrossProfileIntentFilter> matchingFilters =
6215                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6216                // Check for results that need to skip the current profile.
6217                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6218                        resolvedType, flags, userId);
6219                if (xpResolveInfo != null) {
6220                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6221                    xpResult.add(xpResolveInfo);
6222                    return applyPostResolutionFilter(
6223                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6224                }
6225
6226                // Check for results in the current profile.
6227                result = filterIfNotSystemUser(mActivities.queryIntent(
6228                        intent, resolvedType, flags, userId), userId);
6229                addEphemeral =
6230                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6231
6232                // Check for cross profile results.
6233                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6234                xpResolveInfo = queryCrossProfileIntents(
6235                        matchingFilters, intent, resolvedType, flags, userId,
6236                        hasNonNegativePriorityResult);
6237                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6238                    boolean isVisibleToUser = filterIfNotSystemUser(
6239                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6240                    if (isVisibleToUser) {
6241                        result.add(xpResolveInfo);
6242                        sortResult = true;
6243                    }
6244                }
6245                if (hasWebURI(intent)) {
6246                    CrossProfileDomainInfo xpDomainInfo = null;
6247                    final UserInfo parent = getProfileParent(userId);
6248                    if (parent != null) {
6249                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6250                                flags, userId, parent.id);
6251                    }
6252                    if (xpDomainInfo != null) {
6253                        if (xpResolveInfo != null) {
6254                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6255                            // in the result.
6256                            result.remove(xpResolveInfo);
6257                        }
6258                        if (result.size() == 0 && !addEphemeral) {
6259                            // No result in current profile, but found candidate in parent user.
6260                            // And we are not going to add emphemeral app, so we can return the
6261                            // result straight away.
6262                            result.add(xpDomainInfo.resolveInfo);
6263                            return applyPostResolutionFilter(result, instantAppPkgName);
6264                        }
6265                    } else if (result.size() <= 1 && !addEphemeral) {
6266                        // No result in parent user and <= 1 result in current profile, and we
6267                        // are not going to add emphemeral app, so we can return the result without
6268                        // further processing.
6269                        return applyPostResolutionFilter(result, instantAppPkgName);
6270                    }
6271                    // We have more than one candidate (combining results from current and parent
6272                    // profile), so we need filtering and sorting.
6273                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6274                            intent, flags, result, xpDomainInfo, userId);
6275                    sortResult = true;
6276                }
6277            } else {
6278                final PackageParser.Package pkg = mPackages.get(pkgName);
6279                if (pkg != null) {
6280                    result = applyPostResolutionFilter(filterIfNotSystemUser(
6281                            mActivities.queryIntentForPackage(
6282                                    intent, resolvedType, flags, pkg.activities, userId),
6283                            userId), instantAppPkgName);
6284                } else {
6285                    // the caller wants to resolve for a particular package; however, there
6286                    // were no installed results, so, try to find an ephemeral result
6287                    addEphemeral = isEphemeralAllowed(
6288                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6289                    result = new ArrayList<ResolveInfo>();
6290                }
6291            }
6292        }
6293        if (addEphemeral) {
6294            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6295            final EphemeralRequest requestObject = new EphemeralRequest(
6296                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6297                    null /*callingPackage*/, userId);
6298            final AuxiliaryResolveInfo auxiliaryResponse =
6299                    EphemeralResolver.doEphemeralResolutionPhaseOne(
6300                            mContext, mInstantAppResolverConnection, requestObject);
6301            if (auxiliaryResponse != null) {
6302                if (DEBUG_EPHEMERAL) {
6303                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6304                }
6305                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6306                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6307                // make sure this resolver is the default
6308                ephemeralInstaller.isDefault = true;
6309                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6310                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6311                // add a non-generic filter
6312                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6313                ephemeralInstaller.filter.addDataPath(
6314                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6315                result.add(ephemeralInstaller);
6316            }
6317            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6318        }
6319        if (sortResult) {
6320            Collections.sort(result, mResolvePrioritySorter);
6321        }
6322        return applyPostResolutionFilter(result, instantAppPkgName);
6323    }
6324
6325    private static class CrossProfileDomainInfo {
6326        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6327        ResolveInfo resolveInfo;
6328        /* Best domain verification status of the activities found in the other profile */
6329        int bestDomainVerificationStatus;
6330    }
6331
6332    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6333            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6334        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6335                sourceUserId)) {
6336            return null;
6337        }
6338        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6339                resolvedType, flags, parentUserId);
6340
6341        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6342            return null;
6343        }
6344        CrossProfileDomainInfo result = null;
6345        int size = resultTargetUser.size();
6346        for (int i = 0; i < size; i++) {
6347            ResolveInfo riTargetUser = resultTargetUser.get(i);
6348            // Intent filter verification is only for filters that specify a host. So don't return
6349            // those that handle all web uris.
6350            if (riTargetUser.handleAllWebDataURI) {
6351                continue;
6352            }
6353            String packageName = riTargetUser.activityInfo.packageName;
6354            PackageSetting ps = mSettings.mPackages.get(packageName);
6355            if (ps == null) {
6356                continue;
6357            }
6358            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6359            int status = (int)(verificationState >> 32);
6360            if (result == null) {
6361                result = new CrossProfileDomainInfo();
6362                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6363                        sourceUserId, parentUserId);
6364                result.bestDomainVerificationStatus = status;
6365            } else {
6366                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6367                        result.bestDomainVerificationStatus);
6368            }
6369        }
6370        // Don't consider matches with status NEVER across profiles.
6371        if (result != null && result.bestDomainVerificationStatus
6372                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6373            return null;
6374        }
6375        return result;
6376    }
6377
6378    /**
6379     * Verification statuses are ordered from the worse to the best, except for
6380     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6381     */
6382    private int bestDomainVerificationStatus(int status1, int status2) {
6383        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6384            return status2;
6385        }
6386        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6387            return status1;
6388        }
6389        return (int) MathUtils.max(status1, status2);
6390    }
6391
6392    private boolean isUserEnabled(int userId) {
6393        long callingId = Binder.clearCallingIdentity();
6394        try {
6395            UserInfo userInfo = sUserManager.getUserInfo(userId);
6396            return userInfo != null && userInfo.isEnabled();
6397        } finally {
6398            Binder.restoreCallingIdentity(callingId);
6399        }
6400    }
6401
6402    /**
6403     * Filter out activities with systemUserOnly flag set, when current user is not System.
6404     *
6405     * @return filtered list
6406     */
6407    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6408        if (userId == UserHandle.USER_SYSTEM) {
6409            return resolveInfos;
6410        }
6411        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6412            ResolveInfo info = resolveInfos.get(i);
6413            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6414                resolveInfos.remove(i);
6415            }
6416        }
6417        return resolveInfos;
6418    }
6419
6420    /**
6421     * Filters out ephemeral activities.
6422     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6423     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6424     *
6425     * @param resolveInfos The pre-filtered list of resolved activities
6426     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6427     *          is performed.
6428     * @return A filtered list of resolved activities.
6429     */
6430    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6431            String ephemeralPkgName) {
6432        // TODO: When adding on-demand split support for non-instant apps, remove this check
6433        // and always apply post filtering
6434        if (ephemeralPkgName == null) {
6435            return resolveInfos;
6436        }
6437        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6438            final ResolveInfo info = resolveInfos.get(i);
6439            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6440            // allow activities that are defined in the provided package
6441            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6442                if (info.activityInfo.splitName != null
6443                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6444                                info.activityInfo.splitName)) {
6445                    // requested activity is defined in a split that hasn't been installed yet.
6446                    // add the installer to the resolve list
6447                    if (DEBUG_EPHEMERAL) {
6448                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6449                    }
6450                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6451                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6452                            info.activityInfo.packageName, info.activityInfo.splitName,
6453                            info.activityInfo.applicationInfo.versionCode);
6454                    // make sure this resolver is the default
6455                    installerInfo.isDefault = true;
6456                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6457                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6458                    // add a non-generic filter
6459                    installerInfo.filter = new IntentFilter();
6460                    // load resources from the correct package
6461                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6462                    resolveInfos.set(i, installerInfo);
6463                }
6464                continue;
6465            }
6466            // allow activities that have been explicitly exposed to ephemeral apps
6467            if (!isEphemeralApp
6468                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6469                continue;
6470            }
6471            resolveInfos.remove(i);
6472        }
6473        return resolveInfos;
6474    }
6475
6476    /**
6477     * @param resolveInfos list of resolve infos in descending priority order
6478     * @return if the list contains a resolve info with non-negative priority
6479     */
6480    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6481        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6482    }
6483
6484    private static boolean hasWebURI(Intent intent) {
6485        if (intent.getData() == null) {
6486            return false;
6487        }
6488        final String scheme = intent.getScheme();
6489        if (TextUtils.isEmpty(scheme)) {
6490            return false;
6491        }
6492        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6493    }
6494
6495    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6496            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6497            int userId) {
6498        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6499
6500        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6501            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6502                    candidates.size());
6503        }
6504
6505        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6506        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6507        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6508        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6509        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6510        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6511
6512        synchronized (mPackages) {
6513            final int count = candidates.size();
6514            // First, try to use linked apps. Partition the candidates into four lists:
6515            // one for the final results, one for the "do not use ever", one for "undefined status"
6516            // and finally one for "browser app type".
6517            for (int n=0; n<count; n++) {
6518                ResolveInfo info = candidates.get(n);
6519                String packageName = info.activityInfo.packageName;
6520                PackageSetting ps = mSettings.mPackages.get(packageName);
6521                if (ps != null) {
6522                    // Add to the special match all list (Browser use case)
6523                    if (info.handleAllWebDataURI) {
6524                        matchAllList.add(info);
6525                        continue;
6526                    }
6527                    // Try to get the status from User settings first
6528                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6529                    int status = (int)(packedStatus >> 32);
6530                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6531                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6532                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6533                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6534                                    + " : linkgen=" + linkGeneration);
6535                        }
6536                        // Use link-enabled generation as preferredOrder, i.e.
6537                        // prefer newly-enabled over earlier-enabled.
6538                        info.preferredOrder = linkGeneration;
6539                        alwaysList.add(info);
6540                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6541                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6542                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6543                        }
6544                        neverList.add(info);
6545                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6546                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6547                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6548                        }
6549                        alwaysAskList.add(info);
6550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6551                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6552                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6553                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6554                        }
6555                        undefinedList.add(info);
6556                    }
6557                }
6558            }
6559
6560            // We'll want to include browser possibilities in a few cases
6561            boolean includeBrowser = false;
6562
6563            // First try to add the "always" resolution(s) for the current user, if any
6564            if (alwaysList.size() > 0) {
6565                result.addAll(alwaysList);
6566            } else {
6567                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6568                result.addAll(undefinedList);
6569                // Maybe add one for the other profile.
6570                if (xpDomainInfo != null && (
6571                        xpDomainInfo.bestDomainVerificationStatus
6572                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6573                    result.add(xpDomainInfo.resolveInfo);
6574                }
6575                includeBrowser = true;
6576            }
6577
6578            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6579            // If there were 'always' entries their preferred order has been set, so we also
6580            // back that off to make the alternatives equivalent
6581            if (alwaysAskList.size() > 0) {
6582                for (ResolveInfo i : result) {
6583                    i.preferredOrder = 0;
6584                }
6585                result.addAll(alwaysAskList);
6586                includeBrowser = true;
6587            }
6588
6589            if (includeBrowser) {
6590                // Also add browsers (all of them or only the default one)
6591                if (DEBUG_DOMAIN_VERIFICATION) {
6592                    Slog.v(TAG, "   ...including browsers in candidate set");
6593                }
6594                if ((matchFlags & MATCH_ALL) != 0) {
6595                    result.addAll(matchAllList);
6596                } else {
6597                    // Browser/generic handling case.  If there's a default browser, go straight
6598                    // to that (but only if there is no other higher-priority match).
6599                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6600                    int maxMatchPrio = 0;
6601                    ResolveInfo defaultBrowserMatch = null;
6602                    final int numCandidates = matchAllList.size();
6603                    for (int n = 0; n < numCandidates; n++) {
6604                        ResolveInfo info = matchAllList.get(n);
6605                        // track the highest overall match priority...
6606                        if (info.priority > maxMatchPrio) {
6607                            maxMatchPrio = info.priority;
6608                        }
6609                        // ...and the highest-priority default browser match
6610                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6611                            if (defaultBrowserMatch == null
6612                                    || (defaultBrowserMatch.priority < info.priority)) {
6613                                if (debug) {
6614                                    Slog.v(TAG, "Considering default browser match " + info);
6615                                }
6616                                defaultBrowserMatch = info;
6617                            }
6618                        }
6619                    }
6620                    if (defaultBrowserMatch != null
6621                            && defaultBrowserMatch.priority >= maxMatchPrio
6622                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6623                    {
6624                        if (debug) {
6625                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6626                        }
6627                        result.add(defaultBrowserMatch);
6628                    } else {
6629                        result.addAll(matchAllList);
6630                    }
6631                }
6632
6633                // If there is nothing selected, add all candidates and remove the ones that the user
6634                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6635                if (result.size() == 0) {
6636                    result.addAll(candidates);
6637                    result.removeAll(neverList);
6638                }
6639            }
6640        }
6641        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6642            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6643                    result.size());
6644            for (ResolveInfo info : result) {
6645                Slog.v(TAG, "  + " + info.activityInfo);
6646            }
6647        }
6648        return result;
6649    }
6650
6651    // Returns a packed value as a long:
6652    //
6653    // high 'int'-sized word: link status: undefined/ask/never/always.
6654    // low 'int'-sized word: relative priority among 'always' results.
6655    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6656        long result = ps.getDomainVerificationStatusForUser(userId);
6657        // if none available, get the master status
6658        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6659            if (ps.getIntentFilterVerificationInfo() != null) {
6660                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6661            }
6662        }
6663        return result;
6664    }
6665
6666    private ResolveInfo querySkipCurrentProfileIntents(
6667            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6668            int flags, int sourceUserId) {
6669        if (matchingFilters != null) {
6670            int size = matchingFilters.size();
6671            for (int i = 0; i < size; i ++) {
6672                CrossProfileIntentFilter filter = matchingFilters.get(i);
6673                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6674                    // Checking if there are activities in the target user that can handle the
6675                    // intent.
6676                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6677                            resolvedType, flags, sourceUserId);
6678                    if (resolveInfo != null) {
6679                        return resolveInfo;
6680                    }
6681                }
6682            }
6683        }
6684        return null;
6685    }
6686
6687    // Return matching ResolveInfo in target user if any.
6688    private ResolveInfo queryCrossProfileIntents(
6689            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6690            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6691        if (matchingFilters != null) {
6692            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6693            // match the same intent. For performance reasons, it is better not to
6694            // run queryIntent twice for the same userId
6695            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6696            int size = matchingFilters.size();
6697            for (int i = 0; i < size; i++) {
6698                CrossProfileIntentFilter filter = matchingFilters.get(i);
6699                int targetUserId = filter.getTargetUserId();
6700                boolean skipCurrentProfile =
6701                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6702                boolean skipCurrentProfileIfNoMatchFound =
6703                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6704                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6705                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6706                    // Checking if there are activities in the target user that can handle the
6707                    // intent.
6708                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6709                            resolvedType, flags, sourceUserId);
6710                    if (resolveInfo != null) return resolveInfo;
6711                    alreadyTriedUserIds.put(targetUserId, true);
6712                }
6713            }
6714        }
6715        return null;
6716    }
6717
6718    /**
6719     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6720     * will forward the intent to the filter's target user.
6721     * Otherwise, returns null.
6722     */
6723    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6724            String resolvedType, int flags, int sourceUserId) {
6725        int targetUserId = filter.getTargetUserId();
6726        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6727                resolvedType, flags, targetUserId);
6728        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6729            // If all the matches in the target profile are suspended, return null.
6730            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6731                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6732                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6733                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6734                            targetUserId);
6735                }
6736            }
6737        }
6738        return null;
6739    }
6740
6741    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6742            int sourceUserId, int targetUserId) {
6743        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6744        long ident = Binder.clearCallingIdentity();
6745        boolean targetIsProfile;
6746        try {
6747            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6748        } finally {
6749            Binder.restoreCallingIdentity(ident);
6750        }
6751        String className;
6752        if (targetIsProfile) {
6753            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6754        } else {
6755            className = FORWARD_INTENT_TO_PARENT;
6756        }
6757        ComponentName forwardingActivityComponentName = new ComponentName(
6758                mAndroidApplication.packageName, className);
6759        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6760                sourceUserId);
6761        if (!targetIsProfile) {
6762            forwardingActivityInfo.showUserIcon = targetUserId;
6763            forwardingResolveInfo.noResourceId = true;
6764        }
6765        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6766        forwardingResolveInfo.priority = 0;
6767        forwardingResolveInfo.preferredOrder = 0;
6768        forwardingResolveInfo.match = 0;
6769        forwardingResolveInfo.isDefault = true;
6770        forwardingResolveInfo.filter = filter;
6771        forwardingResolveInfo.targetUserId = targetUserId;
6772        return forwardingResolveInfo;
6773    }
6774
6775    @Override
6776    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6777            Intent[] specifics, String[] specificTypes, Intent intent,
6778            String resolvedType, int flags, int userId) {
6779        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6780                specificTypes, intent, resolvedType, flags, userId));
6781    }
6782
6783    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6784            Intent[] specifics, String[] specificTypes, Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        if (!sUserManager.exists(userId)) return Collections.emptyList();
6787        flags = updateFlagsForResolve(flags, userId, intent, false);
6788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6789                false /* requireFullPermission */, false /* checkShell */,
6790                "query intent activity options");
6791        final String resultsAction = intent.getAction();
6792
6793        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6794                | PackageManager.GET_RESOLVED_FILTER, userId);
6795
6796        if (DEBUG_INTENT_MATCHING) {
6797            Log.v(TAG, "Query " + intent + ": " + results);
6798        }
6799
6800        int specificsPos = 0;
6801        int N;
6802
6803        // todo: note that the algorithm used here is O(N^2).  This
6804        // isn't a problem in our current environment, but if we start running
6805        // into situations where we have more than 5 or 10 matches then this
6806        // should probably be changed to something smarter...
6807
6808        // First we go through and resolve each of the specific items
6809        // that were supplied, taking care of removing any corresponding
6810        // duplicate items in the generic resolve list.
6811        if (specifics != null) {
6812            for (int i=0; i<specifics.length; i++) {
6813                final Intent sintent = specifics[i];
6814                if (sintent == null) {
6815                    continue;
6816                }
6817
6818                if (DEBUG_INTENT_MATCHING) {
6819                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6820                }
6821
6822                String action = sintent.getAction();
6823                if (resultsAction != null && resultsAction.equals(action)) {
6824                    // If this action was explicitly requested, then don't
6825                    // remove things that have it.
6826                    action = null;
6827                }
6828
6829                ResolveInfo ri = null;
6830                ActivityInfo ai = null;
6831
6832                ComponentName comp = sintent.getComponent();
6833                if (comp == null) {
6834                    ri = resolveIntent(
6835                        sintent,
6836                        specificTypes != null ? specificTypes[i] : null,
6837                            flags, userId);
6838                    if (ri == null) {
6839                        continue;
6840                    }
6841                    if (ri == mResolveInfo) {
6842                        // ACK!  Must do something better with this.
6843                    }
6844                    ai = ri.activityInfo;
6845                    comp = new ComponentName(ai.applicationInfo.packageName,
6846                            ai.name);
6847                } else {
6848                    ai = getActivityInfo(comp, flags, userId);
6849                    if (ai == null) {
6850                        continue;
6851                    }
6852                }
6853
6854                // Look for any generic query activities that are duplicates
6855                // of this specific one, and remove them from the results.
6856                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6857                N = results.size();
6858                int j;
6859                for (j=specificsPos; j<N; j++) {
6860                    ResolveInfo sri = results.get(j);
6861                    if ((sri.activityInfo.name.equals(comp.getClassName())
6862                            && sri.activityInfo.applicationInfo.packageName.equals(
6863                                    comp.getPackageName()))
6864                        || (action != null && sri.filter.matchAction(action))) {
6865                        results.remove(j);
6866                        if (DEBUG_INTENT_MATCHING) Log.v(
6867                            TAG, "Removing duplicate item from " + j
6868                            + " due to specific " + specificsPos);
6869                        if (ri == null) {
6870                            ri = sri;
6871                        }
6872                        j--;
6873                        N--;
6874                    }
6875                }
6876
6877                // Add this specific item to its proper place.
6878                if (ri == null) {
6879                    ri = new ResolveInfo();
6880                    ri.activityInfo = ai;
6881                }
6882                results.add(specificsPos, ri);
6883                ri.specificIndex = i;
6884                specificsPos++;
6885            }
6886        }
6887
6888        // Now we go through the remaining generic results and remove any
6889        // duplicate actions that are found here.
6890        N = results.size();
6891        for (int i=specificsPos; i<N-1; i++) {
6892            final ResolveInfo rii = results.get(i);
6893            if (rii.filter == null) {
6894                continue;
6895            }
6896
6897            // Iterate over all of the actions of this result's intent
6898            // filter...  typically this should be just one.
6899            final Iterator<String> it = rii.filter.actionsIterator();
6900            if (it == null) {
6901                continue;
6902            }
6903            while (it.hasNext()) {
6904                final String action = it.next();
6905                if (resultsAction != null && resultsAction.equals(action)) {
6906                    // If this action was explicitly requested, then don't
6907                    // remove things that have it.
6908                    continue;
6909                }
6910                for (int j=i+1; j<N; j++) {
6911                    final ResolveInfo rij = results.get(j);
6912                    if (rij.filter != null && rij.filter.hasAction(action)) {
6913                        results.remove(j);
6914                        if (DEBUG_INTENT_MATCHING) Log.v(
6915                            TAG, "Removing duplicate item from " + j
6916                            + " due to action " + action + " at " + i);
6917                        j--;
6918                        N--;
6919                    }
6920                }
6921            }
6922
6923            // If the caller didn't request filter information, drop it now
6924            // so we don't have to marshall/unmarshall it.
6925            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6926                rii.filter = null;
6927            }
6928        }
6929
6930        // Filter out the caller activity if so requested.
6931        if (caller != null) {
6932            N = results.size();
6933            for (int i=0; i<N; i++) {
6934                ActivityInfo ainfo = results.get(i).activityInfo;
6935                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6936                        && caller.getClassName().equals(ainfo.name)) {
6937                    results.remove(i);
6938                    break;
6939                }
6940            }
6941        }
6942
6943        // If the caller didn't request filter information,
6944        // drop them now so we don't have to
6945        // marshall/unmarshall it.
6946        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6947            N = results.size();
6948            for (int i=0; i<N; i++) {
6949                results.get(i).filter = null;
6950            }
6951        }
6952
6953        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6954        return results;
6955    }
6956
6957    @Override
6958    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6959            String resolvedType, int flags, int userId) {
6960        return new ParceledListSlice<>(
6961                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6962    }
6963
6964    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6965            String resolvedType, int flags, int userId) {
6966        if (!sUserManager.exists(userId)) return Collections.emptyList();
6967        flags = updateFlagsForResolve(flags, userId, intent, false);
6968        ComponentName comp = intent.getComponent();
6969        if (comp == null) {
6970            if (intent.getSelector() != null) {
6971                intent = intent.getSelector();
6972                comp = intent.getComponent();
6973            }
6974        }
6975        if (comp != null) {
6976            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6977            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6978            if (ai != null) {
6979                ResolveInfo ri = new ResolveInfo();
6980                ri.activityInfo = ai;
6981                list.add(ri);
6982            }
6983            return list;
6984        }
6985
6986        // reader
6987        synchronized (mPackages) {
6988            String pkgName = intent.getPackage();
6989            if (pkgName == null) {
6990                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6991            }
6992            final PackageParser.Package pkg = mPackages.get(pkgName);
6993            if (pkg != null) {
6994                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6995                        userId);
6996            }
6997            return Collections.emptyList();
6998        }
6999    }
7000
7001    @Override
7002    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7003        if (!sUserManager.exists(userId)) return null;
7004        flags = updateFlagsForResolve(flags, userId, intent, false);
7005        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7006        if (query != null) {
7007            if (query.size() >= 1) {
7008                // If there is more than one service with the same priority,
7009                // just arbitrarily pick the first one.
7010                return query.get(0);
7011            }
7012        }
7013        return null;
7014    }
7015
7016    @Override
7017    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7018            String resolvedType, int flags, int userId) {
7019        return new ParceledListSlice<>(
7020                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7021    }
7022
7023    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7024            String resolvedType, int flags, int userId) {
7025        if (!sUserManager.exists(userId)) return Collections.emptyList();
7026        flags = updateFlagsForResolve(flags, userId, intent, false);
7027        ComponentName comp = intent.getComponent();
7028        if (comp == null) {
7029            if (intent.getSelector() != null) {
7030                intent = intent.getSelector();
7031                comp = intent.getComponent();
7032            }
7033        }
7034        if (comp != null) {
7035            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7036            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7037            if (si != null) {
7038                final ResolveInfo ri = new ResolveInfo();
7039                ri.serviceInfo = si;
7040                list.add(ri);
7041            }
7042            return list;
7043        }
7044
7045        // reader
7046        synchronized (mPackages) {
7047            String pkgName = intent.getPackage();
7048            if (pkgName == null) {
7049                return mServices.queryIntent(intent, resolvedType, flags, userId);
7050            }
7051            final PackageParser.Package pkg = mPackages.get(pkgName);
7052            if (pkg != null) {
7053                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7054                        userId);
7055            }
7056            return Collections.emptyList();
7057        }
7058    }
7059
7060    @Override
7061    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7062            String resolvedType, int flags, int userId) {
7063        return new ParceledListSlice<>(
7064                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7065    }
7066
7067    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7068            Intent intent, String resolvedType, int flags, int userId) {
7069        if (!sUserManager.exists(userId)) return Collections.emptyList();
7070        flags = updateFlagsForResolve(flags, userId, intent, false);
7071        ComponentName comp = intent.getComponent();
7072        if (comp == null) {
7073            if (intent.getSelector() != null) {
7074                intent = intent.getSelector();
7075                comp = intent.getComponent();
7076            }
7077        }
7078        if (comp != null) {
7079            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7080            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7081            if (pi != null) {
7082                final ResolveInfo ri = new ResolveInfo();
7083                ri.providerInfo = pi;
7084                list.add(ri);
7085            }
7086            return list;
7087        }
7088
7089        // reader
7090        synchronized (mPackages) {
7091            String pkgName = intent.getPackage();
7092            if (pkgName == null) {
7093                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7094            }
7095            final PackageParser.Package pkg = mPackages.get(pkgName);
7096            if (pkg != null) {
7097                return mProviders.queryIntentForPackage(
7098                        intent, resolvedType, flags, pkg.providers, userId);
7099            }
7100            return Collections.emptyList();
7101        }
7102    }
7103
7104    @Override
7105    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7106        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7107        flags = updateFlagsForPackage(flags, userId, null);
7108        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7110                true /* requireFullPermission */, false /* checkShell */,
7111                "get installed packages");
7112
7113        // writer
7114        synchronized (mPackages) {
7115            ArrayList<PackageInfo> list;
7116            if (listUninstalled) {
7117                list = new ArrayList<>(mSettings.mPackages.size());
7118                for (PackageSetting ps : mSettings.mPackages.values()) {
7119                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7120                        continue;
7121                    }
7122                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7123                    if (pi != null) {
7124                        list.add(pi);
7125                    }
7126                }
7127            } else {
7128                list = new ArrayList<>(mPackages.size());
7129                for (PackageParser.Package p : mPackages.values()) {
7130                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7131                            Binder.getCallingUid(), userId)) {
7132                        continue;
7133                    }
7134                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7135                            p.mExtras, flags, userId);
7136                    if (pi != null) {
7137                        list.add(pi);
7138                    }
7139                }
7140            }
7141
7142            return new ParceledListSlice<>(list);
7143        }
7144    }
7145
7146    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7147            String[] permissions, boolean[] tmp, int flags, int userId) {
7148        int numMatch = 0;
7149        final PermissionsState permissionsState = ps.getPermissionsState();
7150        for (int i=0; i<permissions.length; i++) {
7151            final String permission = permissions[i];
7152            if (permissionsState.hasPermission(permission, userId)) {
7153                tmp[i] = true;
7154                numMatch++;
7155            } else {
7156                tmp[i] = false;
7157            }
7158        }
7159        if (numMatch == 0) {
7160            return;
7161        }
7162        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7163
7164        // The above might return null in cases of uninstalled apps or install-state
7165        // skew across users/profiles.
7166        if (pi != null) {
7167            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7168                if (numMatch == permissions.length) {
7169                    pi.requestedPermissions = permissions;
7170                } else {
7171                    pi.requestedPermissions = new String[numMatch];
7172                    numMatch = 0;
7173                    for (int i=0; i<permissions.length; i++) {
7174                        if (tmp[i]) {
7175                            pi.requestedPermissions[numMatch] = permissions[i];
7176                            numMatch++;
7177                        }
7178                    }
7179                }
7180            }
7181            list.add(pi);
7182        }
7183    }
7184
7185    @Override
7186    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7187            String[] permissions, int flags, int userId) {
7188        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7189        flags = updateFlagsForPackage(flags, userId, permissions);
7190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7191                true /* requireFullPermission */, false /* checkShell */,
7192                "get packages holding permissions");
7193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7194
7195        // writer
7196        synchronized (mPackages) {
7197            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7198            boolean[] tmpBools = new boolean[permissions.length];
7199            if (listUninstalled) {
7200                for (PackageSetting ps : mSettings.mPackages.values()) {
7201                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7202                            userId);
7203                }
7204            } else {
7205                for (PackageParser.Package pkg : mPackages.values()) {
7206                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7207                    if (ps != null) {
7208                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7209                                userId);
7210                    }
7211                }
7212            }
7213
7214            return new ParceledListSlice<PackageInfo>(list);
7215        }
7216    }
7217
7218    @Override
7219    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7221        flags = updateFlagsForApplication(flags, userId, null);
7222        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7223
7224        // writer
7225        synchronized (mPackages) {
7226            ArrayList<ApplicationInfo> list;
7227            if (listUninstalled) {
7228                list = new ArrayList<>(mSettings.mPackages.size());
7229                for (PackageSetting ps : mSettings.mPackages.values()) {
7230                    ApplicationInfo ai;
7231                    int effectiveFlags = flags;
7232                    if (ps.isSystem()) {
7233                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7234                    }
7235                    if (ps.pkg != null) {
7236                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7237                            continue;
7238                        }
7239                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7240                                ps.readUserState(userId), userId);
7241                        if (ai != null) {
7242                            rebaseEnabledOverlays(ai, userId);
7243                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7244                        }
7245                    } else {
7246                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7247                        // and already converts to externally visible package name
7248                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7249                                Binder.getCallingUid(), effectiveFlags, userId);
7250                    }
7251                    if (ai != null) {
7252                        list.add(ai);
7253                    }
7254                }
7255            } else {
7256                list = new ArrayList<>(mPackages.size());
7257                for (PackageParser.Package p : mPackages.values()) {
7258                    if (p.mExtras != null) {
7259                        PackageSetting ps = (PackageSetting) p.mExtras;
7260                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7261                            continue;
7262                        }
7263                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7264                                ps.readUserState(userId), userId);
7265                        if (ai != null) {
7266                            rebaseEnabledOverlays(ai, userId);
7267                            ai.packageName = resolveExternalPackageNameLPr(p);
7268                            list.add(ai);
7269                        }
7270                    }
7271                }
7272            }
7273
7274            return new ParceledListSlice<>(list);
7275        }
7276    }
7277
7278    @Override
7279    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7280        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7281            return null;
7282        }
7283
7284        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7285                "getEphemeralApplications");
7286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7287                true /* requireFullPermission */, false /* checkShell */,
7288                "getEphemeralApplications");
7289        synchronized (mPackages) {
7290            List<InstantAppInfo> instantApps = mInstantAppRegistry
7291                    .getInstantAppsLPr(userId);
7292            if (instantApps != null) {
7293                return new ParceledListSlice<>(instantApps);
7294            }
7295        }
7296        return null;
7297    }
7298
7299    @Override
7300    public boolean isInstantApp(String packageName, int userId) {
7301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7302                true /* requireFullPermission */, false /* checkShell */,
7303                "isInstantApp");
7304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7305            return false;
7306        }
7307
7308        if (!isCallerSameApp(packageName)) {
7309            return false;
7310        }
7311        synchronized (mPackages) {
7312            final PackageSetting ps = mSettings.mPackages.get(packageName);
7313            if (ps != null) {
7314                return ps.getInstantApp(userId);
7315            }
7316        }
7317        return false;
7318    }
7319
7320    @Override
7321    public byte[] getInstantAppCookie(String packageName, int userId) {
7322        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7323            return null;
7324        }
7325
7326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7327                true /* requireFullPermission */, false /* checkShell */,
7328                "getInstantAppCookie");
7329        if (!isCallerSameApp(packageName)) {
7330            return null;
7331        }
7332        synchronized (mPackages) {
7333            return mInstantAppRegistry.getInstantAppCookieLPw(
7334                    packageName, userId);
7335        }
7336    }
7337
7338    @Override
7339    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7340        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7341            return true;
7342        }
7343
7344        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7345                true /* requireFullPermission */, true /* checkShell */,
7346                "setInstantAppCookie");
7347        if (!isCallerSameApp(packageName)) {
7348            return false;
7349        }
7350        synchronized (mPackages) {
7351            return mInstantAppRegistry.setInstantAppCookieLPw(
7352                    packageName, cookie, userId);
7353        }
7354    }
7355
7356    @Override
7357    public Bitmap getInstantAppIcon(String packageName, int userId) {
7358        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7359            return null;
7360        }
7361
7362        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7363                "getInstantAppIcon");
7364
7365        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7366                true /* requireFullPermission */, false /* checkShell */,
7367                "getInstantAppIcon");
7368
7369        synchronized (mPackages) {
7370            return mInstantAppRegistry.getInstantAppIconLPw(
7371                    packageName, userId);
7372        }
7373    }
7374
7375    private boolean isCallerSameApp(String packageName) {
7376        PackageParser.Package pkg = mPackages.get(packageName);
7377        return pkg != null
7378                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7379    }
7380
7381    @Override
7382    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7383        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7384    }
7385
7386    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7387        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7388
7389        // reader
7390        synchronized (mPackages) {
7391            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7392            final int userId = UserHandle.getCallingUserId();
7393            while (i.hasNext()) {
7394                final PackageParser.Package p = i.next();
7395                if (p.applicationInfo == null) continue;
7396
7397                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7398                        && !p.applicationInfo.isDirectBootAware();
7399                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7400                        && p.applicationInfo.isDirectBootAware();
7401
7402                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7403                        && (!mSafeMode || isSystemApp(p))
7404                        && (matchesUnaware || matchesAware)) {
7405                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7406                    if (ps != null) {
7407                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7408                                ps.readUserState(userId), userId);
7409                        if (ai != null) {
7410                            rebaseEnabledOverlays(ai, userId);
7411                            finalList.add(ai);
7412                        }
7413                    }
7414                }
7415            }
7416        }
7417
7418        return finalList;
7419    }
7420
7421    @Override
7422    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7423        if (!sUserManager.exists(userId)) return null;
7424        flags = updateFlagsForComponent(flags, userId, name);
7425        // reader
7426        synchronized (mPackages) {
7427            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7428            PackageSetting ps = provider != null
7429                    ? mSettings.mPackages.get(provider.owner.packageName)
7430                    : null;
7431            return ps != null
7432                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7433                    ? PackageParser.generateProviderInfo(provider, flags,
7434                            ps.readUserState(userId), userId)
7435                    : null;
7436        }
7437    }
7438
7439    /**
7440     * @deprecated
7441     */
7442    @Deprecated
7443    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7444        // reader
7445        synchronized (mPackages) {
7446            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7447                    .entrySet().iterator();
7448            final int userId = UserHandle.getCallingUserId();
7449            while (i.hasNext()) {
7450                Map.Entry<String, PackageParser.Provider> entry = i.next();
7451                PackageParser.Provider p = entry.getValue();
7452                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7453
7454                if (ps != null && p.syncable
7455                        && (!mSafeMode || (p.info.applicationInfo.flags
7456                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7457                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7458                            ps.readUserState(userId), userId);
7459                    if (info != null) {
7460                        outNames.add(entry.getKey());
7461                        outInfo.add(info);
7462                    }
7463                }
7464            }
7465        }
7466    }
7467
7468    @Override
7469    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7470            int uid, int flags) {
7471        final int userId = processName != null ? UserHandle.getUserId(uid)
7472                : UserHandle.getCallingUserId();
7473        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7474        flags = updateFlagsForComponent(flags, userId, processName);
7475
7476        ArrayList<ProviderInfo> finalList = null;
7477        // reader
7478        synchronized (mPackages) {
7479            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7480            while (i.hasNext()) {
7481                final PackageParser.Provider p = i.next();
7482                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7483                if (ps != null && p.info.authority != null
7484                        && (processName == null
7485                                || (p.info.processName.equals(processName)
7486                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7487                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7488                    if (finalList == null) {
7489                        finalList = new ArrayList<ProviderInfo>(3);
7490                    }
7491                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7492                            ps.readUserState(userId), userId);
7493                    if (info != null) {
7494                        finalList.add(info);
7495                    }
7496                }
7497            }
7498        }
7499
7500        if (finalList != null) {
7501            Collections.sort(finalList, mProviderInitOrderSorter);
7502            return new ParceledListSlice<ProviderInfo>(finalList);
7503        }
7504
7505        return ParceledListSlice.emptyList();
7506    }
7507
7508    @Override
7509    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7510        // reader
7511        synchronized (mPackages) {
7512            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7513            return PackageParser.generateInstrumentationInfo(i, flags);
7514        }
7515    }
7516
7517    @Override
7518    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7519            String targetPackage, int flags) {
7520        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7521    }
7522
7523    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7524            int flags) {
7525        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7526
7527        // reader
7528        synchronized (mPackages) {
7529            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7530            while (i.hasNext()) {
7531                final PackageParser.Instrumentation p = i.next();
7532                if (targetPackage == null
7533                        || targetPackage.equals(p.info.targetPackage)) {
7534                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7535                            flags);
7536                    if (ii != null) {
7537                        finalList.add(ii);
7538                    }
7539                }
7540            }
7541        }
7542
7543        return finalList;
7544    }
7545
7546    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7547        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7548        try {
7549            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7550        } finally {
7551            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7552        }
7553    }
7554
7555    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7556        final File[] files = dir.listFiles();
7557        if (ArrayUtils.isEmpty(files)) {
7558            Log.d(TAG, "No files in app dir " + dir);
7559            return;
7560        }
7561
7562        if (DEBUG_PACKAGE_SCANNING) {
7563            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7564                    + " flags=0x" + Integer.toHexString(parseFlags));
7565        }
7566        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7567                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7568
7569        // Submit files for parsing in parallel
7570        int fileCount = 0;
7571        for (File file : files) {
7572            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7573                    && !PackageInstallerService.isStageName(file.getName());
7574            if (!isPackage) {
7575                // Ignore entries which are not packages
7576                continue;
7577            }
7578            parallelPackageParser.submit(file, parseFlags);
7579            fileCount++;
7580        }
7581
7582        // Process results one by one
7583        for (; fileCount > 0; fileCount--) {
7584            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7585            Throwable throwable = parseResult.throwable;
7586            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7587
7588            if (throwable == null) {
7589                // Static shared libraries have synthetic package names
7590                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7591                    renameStaticSharedLibraryPackage(parseResult.pkg);
7592                }
7593                try {
7594                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7595                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7596                                currentTime, null);
7597                    }
7598                } catch (PackageManagerException e) {
7599                    errorCode = e.error;
7600                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7601                }
7602            } else if (throwable instanceof PackageParser.PackageParserException) {
7603                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7604                        throwable;
7605                errorCode = e.error;
7606                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7607            } else {
7608                throw new IllegalStateException("Unexpected exception occurred while parsing "
7609                        + parseResult.scanFile, throwable);
7610            }
7611
7612            // Delete invalid userdata apps
7613            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7614                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7615                logCriticalInfo(Log.WARN,
7616                        "Deleting invalid package at " + parseResult.scanFile);
7617                removeCodePathLI(parseResult.scanFile);
7618            }
7619        }
7620        parallelPackageParser.close();
7621    }
7622
7623    private static File getSettingsProblemFile() {
7624        File dataDir = Environment.getDataDirectory();
7625        File systemDir = new File(dataDir, "system");
7626        File fname = new File(systemDir, "uiderrors.txt");
7627        return fname;
7628    }
7629
7630    static void reportSettingsProblem(int priority, String msg) {
7631        logCriticalInfo(priority, msg);
7632    }
7633
7634    static void logCriticalInfo(int priority, String msg) {
7635        Slog.println(priority, TAG, msg);
7636        EventLogTags.writePmCriticalInfo(msg);
7637        try {
7638            File fname = getSettingsProblemFile();
7639            FileOutputStream out = new FileOutputStream(fname, true);
7640            PrintWriter pw = new FastPrintWriter(out);
7641            SimpleDateFormat formatter = new SimpleDateFormat();
7642            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7643            pw.println(dateString + ": " + msg);
7644            pw.close();
7645            FileUtils.setPermissions(
7646                    fname.toString(),
7647                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7648                    -1, -1);
7649        } catch (java.io.IOException e) {
7650        }
7651    }
7652
7653    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7654        if (srcFile.isDirectory()) {
7655            final File baseFile = new File(pkg.baseCodePath);
7656            long maxModifiedTime = baseFile.lastModified();
7657            if (pkg.splitCodePaths != null) {
7658                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7659                    final File splitFile = new File(pkg.splitCodePaths[i]);
7660                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7661                }
7662            }
7663            return maxModifiedTime;
7664        }
7665        return srcFile.lastModified();
7666    }
7667
7668    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7669            final int policyFlags) throws PackageManagerException {
7670        // When upgrading from pre-N MR1, verify the package time stamp using the package
7671        // directory and not the APK file.
7672        final long lastModifiedTime = mIsPreNMR1Upgrade
7673                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7674        if (ps != null
7675                && ps.codePath.equals(srcFile)
7676                && ps.timeStamp == lastModifiedTime
7677                && !isCompatSignatureUpdateNeeded(pkg)
7678                && !isRecoverSignatureUpdateNeeded(pkg)) {
7679            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7680            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7681            ArraySet<PublicKey> signingKs;
7682            synchronized (mPackages) {
7683                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7684            }
7685            if (ps.signatures.mSignatures != null
7686                    && ps.signatures.mSignatures.length != 0
7687                    && signingKs != null) {
7688                // Optimization: reuse the existing cached certificates
7689                // if the package appears to be unchanged.
7690                pkg.mSignatures = ps.signatures.mSignatures;
7691                pkg.mSigningKeys = signingKs;
7692                return;
7693            }
7694
7695            Slog.w(TAG, "PackageSetting for " + ps.name
7696                    + " is missing signatures.  Collecting certs again to recover them.");
7697        } else {
7698            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7699        }
7700
7701        try {
7702            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7703            PackageParser.collectCertificates(pkg, policyFlags);
7704        } catch (PackageParserException e) {
7705            throw PackageManagerException.from(e);
7706        } finally {
7707            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7708        }
7709    }
7710
7711    /**
7712     *  Traces a package scan.
7713     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7714     */
7715    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7716            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7717        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7718        try {
7719            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7720        } finally {
7721            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7722        }
7723    }
7724
7725    /**
7726     *  Scans a package and returns the newly parsed package.
7727     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7728     */
7729    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7730            long currentTime, UserHandle user) throws PackageManagerException {
7731        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7732        PackageParser pp = new PackageParser();
7733        pp.setSeparateProcesses(mSeparateProcesses);
7734        pp.setOnlyCoreApps(mOnlyCore);
7735        pp.setDisplayMetrics(mMetrics);
7736
7737        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7738            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7739        }
7740
7741        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7742        final PackageParser.Package pkg;
7743        try {
7744            pkg = pp.parsePackage(scanFile, parseFlags);
7745        } catch (PackageParserException e) {
7746            throw PackageManagerException.from(e);
7747        } finally {
7748            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7749        }
7750
7751        // Static shared libraries have synthetic package names
7752        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7753            renameStaticSharedLibraryPackage(pkg);
7754        }
7755
7756        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7757    }
7758
7759    /**
7760     *  Scans a package and returns the newly parsed package.
7761     *  @throws PackageManagerException on a parse error.
7762     */
7763    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7764            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7765            throws PackageManagerException {
7766        // If the package has children and this is the first dive in the function
7767        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7768        // packages (parent and children) would be successfully scanned before the
7769        // actual scan since scanning mutates internal state and we want to atomically
7770        // install the package and its children.
7771        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7772            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7773                scanFlags |= SCAN_CHECK_ONLY;
7774            }
7775        } else {
7776            scanFlags &= ~SCAN_CHECK_ONLY;
7777        }
7778
7779        // Scan the parent
7780        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7781                scanFlags, currentTime, user);
7782
7783        // Scan the children
7784        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7785        for (int i = 0; i < childCount; i++) {
7786            PackageParser.Package childPackage = pkg.childPackages.get(i);
7787            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7788                    currentTime, user);
7789        }
7790
7791
7792        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7793            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7794        }
7795
7796        return scannedPkg;
7797    }
7798
7799    /**
7800     *  Scans a package and returns the newly parsed package.
7801     *  @throws PackageManagerException on a parse error.
7802     */
7803    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7804            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7805            throws PackageManagerException {
7806        PackageSetting ps = null;
7807        PackageSetting updatedPkg;
7808        // reader
7809        synchronized (mPackages) {
7810            // Look to see if we already know about this package.
7811            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7812            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7813                // This package has been renamed to its original name.  Let's
7814                // use that.
7815                ps = mSettings.getPackageLPr(oldName);
7816            }
7817            // If there was no original package, see one for the real package name.
7818            if (ps == null) {
7819                ps = mSettings.getPackageLPr(pkg.packageName);
7820            }
7821            // Check to see if this package could be hiding/updating a system
7822            // package.  Must look for it either under the original or real
7823            // package name depending on our state.
7824            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7825            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7826
7827            // If this is a package we don't know about on the system partition, we
7828            // may need to remove disabled child packages on the system partition
7829            // or may need to not add child packages if the parent apk is updated
7830            // on the data partition and no longer defines this child package.
7831            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7832                // If this is a parent package for an updated system app and this system
7833                // app got an OTA update which no longer defines some of the child packages
7834                // we have to prune them from the disabled system packages.
7835                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7836                if (disabledPs != null) {
7837                    final int scannedChildCount = (pkg.childPackages != null)
7838                            ? pkg.childPackages.size() : 0;
7839                    final int disabledChildCount = disabledPs.childPackageNames != null
7840                            ? disabledPs.childPackageNames.size() : 0;
7841                    for (int i = 0; i < disabledChildCount; i++) {
7842                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7843                        boolean disabledPackageAvailable = false;
7844                        for (int j = 0; j < scannedChildCount; j++) {
7845                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7846                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7847                                disabledPackageAvailable = true;
7848                                break;
7849                            }
7850                         }
7851                         if (!disabledPackageAvailable) {
7852                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7853                         }
7854                    }
7855                }
7856            }
7857        }
7858
7859        boolean updatedPkgBetter = false;
7860        // First check if this is a system package that may involve an update
7861        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7862            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7863            // it needs to drop FLAG_PRIVILEGED.
7864            if (locationIsPrivileged(scanFile)) {
7865                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7866            } else {
7867                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7868            }
7869
7870            if (ps != null && !ps.codePath.equals(scanFile)) {
7871                // The path has changed from what was last scanned...  check the
7872                // version of the new path against what we have stored to determine
7873                // what to do.
7874                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7875                if (pkg.mVersionCode <= ps.versionCode) {
7876                    // The system package has been updated and the code path does not match
7877                    // Ignore entry. Skip it.
7878                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7879                            + " ignored: updated version " + ps.versionCode
7880                            + " better than this " + pkg.mVersionCode);
7881                    if (!updatedPkg.codePath.equals(scanFile)) {
7882                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7883                                + ps.name + " changing from " + updatedPkg.codePathString
7884                                + " to " + scanFile);
7885                        updatedPkg.codePath = scanFile;
7886                        updatedPkg.codePathString = scanFile.toString();
7887                        updatedPkg.resourcePath = scanFile;
7888                        updatedPkg.resourcePathString = scanFile.toString();
7889                    }
7890                    updatedPkg.pkg = pkg;
7891                    updatedPkg.versionCode = pkg.mVersionCode;
7892
7893                    // Update the disabled system child packages to point to the package too.
7894                    final int childCount = updatedPkg.childPackageNames != null
7895                            ? updatedPkg.childPackageNames.size() : 0;
7896                    for (int i = 0; i < childCount; i++) {
7897                        String childPackageName = updatedPkg.childPackageNames.get(i);
7898                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7899                                childPackageName);
7900                        if (updatedChildPkg != null) {
7901                            updatedChildPkg.pkg = pkg;
7902                            updatedChildPkg.versionCode = pkg.mVersionCode;
7903                        }
7904                    }
7905
7906                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7907                            + scanFile + " ignored: updated version " + ps.versionCode
7908                            + " better than this " + pkg.mVersionCode);
7909                } else {
7910                    // The current app on the system partition is better than
7911                    // what we have updated to on the data partition; switch
7912                    // back to the system partition version.
7913                    // At this point, its safely assumed that package installation for
7914                    // apps in system partition will go through. If not there won't be a working
7915                    // version of the app
7916                    // writer
7917                    synchronized (mPackages) {
7918                        // Just remove the loaded entries from package lists.
7919                        mPackages.remove(ps.name);
7920                    }
7921
7922                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7923                            + " reverting from " + ps.codePathString
7924                            + ": new version " + pkg.mVersionCode
7925                            + " better than installed " + ps.versionCode);
7926
7927                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7928                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7929                    synchronized (mInstallLock) {
7930                        args.cleanUpResourcesLI();
7931                    }
7932                    synchronized (mPackages) {
7933                        mSettings.enableSystemPackageLPw(ps.name);
7934                    }
7935                    updatedPkgBetter = true;
7936                }
7937            }
7938        }
7939
7940        if (updatedPkg != null) {
7941            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7942            // initially
7943            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7944
7945            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7946            // flag set initially
7947            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7948                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7949            }
7950        }
7951
7952        // Verify certificates against what was last scanned
7953        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7954
7955        /*
7956         * A new system app appeared, but we already had a non-system one of the
7957         * same name installed earlier.
7958         */
7959        boolean shouldHideSystemApp = false;
7960        if (updatedPkg == null && ps != null
7961                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7962            /*
7963             * Check to make sure the signatures match first. If they don't,
7964             * wipe the installed application and its data.
7965             */
7966            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7967                    != PackageManager.SIGNATURE_MATCH) {
7968                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7969                        + " signatures don't match existing userdata copy; removing");
7970                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7971                        "scanPackageInternalLI")) {
7972                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7973                }
7974                ps = null;
7975            } else {
7976                /*
7977                 * If the newly-added system app is an older version than the
7978                 * already installed version, hide it. It will be scanned later
7979                 * and re-added like an update.
7980                 */
7981                if (pkg.mVersionCode <= ps.versionCode) {
7982                    shouldHideSystemApp = true;
7983                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7984                            + " but new version " + pkg.mVersionCode + " better than installed "
7985                            + ps.versionCode + "; hiding system");
7986                } else {
7987                    /*
7988                     * The newly found system app is a newer version that the
7989                     * one previously installed. Simply remove the
7990                     * already-installed application and replace it with our own
7991                     * while keeping the application data.
7992                     */
7993                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7994                            + " reverting from " + ps.codePathString + ": new version "
7995                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7996                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7997                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7998                    synchronized (mInstallLock) {
7999                        args.cleanUpResourcesLI();
8000                    }
8001                }
8002            }
8003        }
8004
8005        // The apk is forward locked (not public) if its code and resources
8006        // are kept in different files. (except for app in either system or
8007        // vendor path).
8008        // TODO grab this value from PackageSettings
8009        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8010            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8011                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8012            }
8013        }
8014
8015        // TODO: extend to support forward-locked splits
8016        String resourcePath = null;
8017        String baseResourcePath = null;
8018        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8019            if (ps != null && ps.resourcePathString != null) {
8020                resourcePath = ps.resourcePathString;
8021                baseResourcePath = ps.resourcePathString;
8022            } else {
8023                // Should not happen at all. Just log an error.
8024                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8025            }
8026        } else {
8027            resourcePath = pkg.codePath;
8028            baseResourcePath = pkg.baseCodePath;
8029        }
8030
8031        // Set application objects path explicitly.
8032        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8033        pkg.setApplicationInfoCodePath(pkg.codePath);
8034        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8035        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8036        pkg.setApplicationInfoResourcePath(resourcePath);
8037        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8038        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8039
8040        final int userId = ((user == null) ? 0 : user.getIdentifier());
8041        if (ps != null && ps.getInstantApp(userId)) {
8042            scanFlags |= SCAN_AS_INSTANT_APP;
8043        }
8044
8045        // Note that we invoke the following method only if we are about to unpack an application
8046        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8047                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8048
8049        /*
8050         * If the system app should be overridden by a previously installed
8051         * data, hide the system app now and let the /data/app scan pick it up
8052         * again.
8053         */
8054        if (shouldHideSystemApp) {
8055            synchronized (mPackages) {
8056                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8057            }
8058        }
8059
8060        return scannedPkg;
8061    }
8062
8063    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8064        // Derive the new package synthetic package name
8065        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8066                + pkg.staticSharedLibVersion);
8067    }
8068
8069    private static String fixProcessName(String defProcessName,
8070            String processName) {
8071        if (processName == null) {
8072            return defProcessName;
8073        }
8074        return processName;
8075    }
8076
8077    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8078            throws PackageManagerException {
8079        if (pkgSetting.signatures.mSignatures != null) {
8080            // Already existing package. Make sure signatures match
8081            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8082                    == PackageManager.SIGNATURE_MATCH;
8083            if (!match) {
8084                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8085                        == PackageManager.SIGNATURE_MATCH;
8086            }
8087            if (!match) {
8088                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8089                        == PackageManager.SIGNATURE_MATCH;
8090            }
8091            if (!match) {
8092                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8093                        + pkg.packageName + " signatures do not match the "
8094                        + "previously installed version; ignoring!");
8095            }
8096        }
8097
8098        // Check for shared user signatures
8099        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8100            // Already existing package. Make sure signatures match
8101            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8102                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8103            if (!match) {
8104                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8105                        == PackageManager.SIGNATURE_MATCH;
8106            }
8107            if (!match) {
8108                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8109                        == PackageManager.SIGNATURE_MATCH;
8110            }
8111            if (!match) {
8112                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8113                        "Package " + pkg.packageName
8114                        + " has no signatures that match those in shared user "
8115                        + pkgSetting.sharedUser.name + "; ignoring!");
8116            }
8117        }
8118    }
8119
8120    /**
8121     * Enforces that only the system UID or root's UID can call a method exposed
8122     * via Binder.
8123     *
8124     * @param message used as message if SecurityException is thrown
8125     * @throws SecurityException if the caller is not system or root
8126     */
8127    private static final void enforceSystemOrRoot(String message) {
8128        final int uid = Binder.getCallingUid();
8129        if (uid != Process.SYSTEM_UID && uid != 0) {
8130            throw new SecurityException(message);
8131        }
8132    }
8133
8134    @Override
8135    public void performFstrimIfNeeded() {
8136        enforceSystemOrRoot("Only the system can request fstrim");
8137
8138        // Before everything else, see whether we need to fstrim.
8139        try {
8140            IStorageManager sm = PackageHelper.getStorageManager();
8141            if (sm != null) {
8142                boolean doTrim = false;
8143                final long interval = android.provider.Settings.Global.getLong(
8144                        mContext.getContentResolver(),
8145                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8146                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8147                if (interval > 0) {
8148                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8149                    if (timeSinceLast > interval) {
8150                        doTrim = true;
8151                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8152                                + "; running immediately");
8153                    }
8154                }
8155                if (doTrim) {
8156                    final boolean dexOptDialogShown;
8157                    synchronized (mPackages) {
8158                        dexOptDialogShown = mDexOptDialogShown;
8159                    }
8160                    if (!isFirstBoot() && dexOptDialogShown) {
8161                        try {
8162                            ActivityManager.getService().showBootMessage(
8163                                    mContext.getResources().getString(
8164                                            R.string.android_upgrading_fstrim), true);
8165                        } catch (RemoteException e) {
8166                        }
8167                    }
8168                    sm.runMaintenance();
8169                }
8170            } else {
8171                Slog.e(TAG, "storageManager service unavailable!");
8172            }
8173        } catch (RemoteException e) {
8174            // Can't happen; StorageManagerService is local
8175        }
8176    }
8177
8178    @Override
8179    public void updatePackagesIfNeeded() {
8180        enforceSystemOrRoot("Only the system can request package update");
8181
8182        // We need to re-extract after an OTA.
8183        boolean causeUpgrade = isUpgrade();
8184
8185        // First boot or factory reset.
8186        // Note: we also handle devices that are upgrading to N right now as if it is their
8187        //       first boot, as they do not have profile data.
8188        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8189
8190        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8191        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8192
8193        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8194            return;
8195        }
8196
8197        List<PackageParser.Package> pkgs;
8198        synchronized (mPackages) {
8199            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8200        }
8201
8202        final long startTime = System.nanoTime();
8203        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8204                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8205
8206        final int elapsedTimeSeconds =
8207                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8208
8209        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8210        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8211        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8212        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8213        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8214    }
8215
8216    /**
8217     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8218     * containing statistics about the invocation. The array consists of three elements,
8219     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8220     * and {@code numberOfPackagesFailed}.
8221     */
8222    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8223            String compilerFilter) {
8224
8225        int numberOfPackagesVisited = 0;
8226        int numberOfPackagesOptimized = 0;
8227        int numberOfPackagesSkipped = 0;
8228        int numberOfPackagesFailed = 0;
8229        final int numberOfPackagesToDexopt = pkgs.size();
8230
8231        for (PackageParser.Package pkg : pkgs) {
8232            numberOfPackagesVisited++;
8233
8234            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8235                if (DEBUG_DEXOPT) {
8236                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8237                }
8238                numberOfPackagesSkipped++;
8239                continue;
8240            }
8241
8242            if (DEBUG_DEXOPT) {
8243                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8244                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8245            }
8246
8247            if (showDialog) {
8248                try {
8249                    ActivityManager.getService().showBootMessage(
8250                            mContext.getResources().getString(R.string.android_upgrading_apk,
8251                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8252                } catch (RemoteException e) {
8253                }
8254                synchronized (mPackages) {
8255                    mDexOptDialogShown = true;
8256                }
8257            }
8258
8259            // If the OTA updates a system app which was previously preopted to a non-preopted state
8260            // the app might end up being verified at runtime. That's because by default the apps
8261            // are verify-profile but for preopted apps there's no profile.
8262            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8263            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8264            // filter (by default interpret-only).
8265            // Note that at this stage unused apps are already filtered.
8266            if (isSystemApp(pkg) &&
8267                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8268                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8269                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8270            }
8271
8272            // checkProfiles is false to avoid merging profiles during boot which
8273            // might interfere with background compilation (b/28612421).
8274            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8275            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8276            // trade-off worth doing to save boot time work.
8277            int dexOptStatus = performDexOptTraced(pkg.packageName,
8278                    false /* checkProfiles */,
8279                    compilerFilter,
8280                    false /* force */);
8281            switch (dexOptStatus) {
8282                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8283                    numberOfPackagesOptimized++;
8284                    break;
8285                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8286                    numberOfPackagesSkipped++;
8287                    break;
8288                case PackageDexOptimizer.DEX_OPT_FAILED:
8289                    numberOfPackagesFailed++;
8290                    break;
8291                default:
8292                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8293                    break;
8294            }
8295        }
8296
8297        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8298                numberOfPackagesFailed };
8299    }
8300
8301    @Override
8302    public void notifyPackageUse(String packageName, int reason) {
8303        synchronized (mPackages) {
8304            PackageParser.Package p = mPackages.get(packageName);
8305            if (p == null) {
8306                return;
8307            }
8308            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8309        }
8310    }
8311
8312    @Override
8313    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8314        int userId = UserHandle.getCallingUserId();
8315        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8316        if (ai == null) {
8317            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8318                + loadingPackageName + ", user=" + userId);
8319            return;
8320        }
8321        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8322    }
8323
8324    // TODO: this is not used nor needed. Delete it.
8325    @Override
8326    public boolean performDexOptIfNeeded(String packageName) {
8327        int dexOptStatus = performDexOptTraced(packageName,
8328                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8329        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8330    }
8331
8332    @Override
8333    public boolean performDexOpt(String packageName,
8334            boolean checkProfiles, int compileReason, boolean force) {
8335        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8336                getCompilerFilterForReason(compileReason), force);
8337        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8338    }
8339
8340    @Override
8341    public boolean performDexOptMode(String packageName,
8342            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8343        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8344                targetCompilerFilter, force);
8345        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8346    }
8347
8348    private int performDexOptTraced(String packageName,
8349                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8350        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8351        try {
8352            return performDexOptInternal(packageName, checkProfiles,
8353                    targetCompilerFilter, force);
8354        } finally {
8355            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8356        }
8357    }
8358
8359    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8360    // if the package can now be considered up to date for the given filter.
8361    private int performDexOptInternal(String packageName,
8362                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8363        PackageParser.Package p;
8364        synchronized (mPackages) {
8365            p = mPackages.get(packageName);
8366            if (p == null) {
8367                // Package could not be found. Report failure.
8368                return PackageDexOptimizer.DEX_OPT_FAILED;
8369            }
8370            mPackageUsage.maybeWriteAsync(mPackages);
8371            mCompilerStats.maybeWriteAsync();
8372        }
8373        long callingId = Binder.clearCallingIdentity();
8374        try {
8375            synchronized (mInstallLock) {
8376                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8377                        targetCompilerFilter, force);
8378            }
8379        } finally {
8380            Binder.restoreCallingIdentity(callingId);
8381        }
8382    }
8383
8384    public ArraySet<String> getOptimizablePackages() {
8385        ArraySet<String> pkgs = new ArraySet<String>();
8386        synchronized (mPackages) {
8387            for (PackageParser.Package p : mPackages.values()) {
8388                if (PackageDexOptimizer.canOptimizePackage(p)) {
8389                    pkgs.add(p.packageName);
8390                }
8391            }
8392        }
8393        return pkgs;
8394    }
8395
8396    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8397            boolean checkProfiles, String targetCompilerFilter,
8398            boolean force) {
8399        // Select the dex optimizer based on the force parameter.
8400        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8401        //       allocate an object here.
8402        PackageDexOptimizer pdo = force
8403                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8404                : mPackageDexOptimizer;
8405
8406        // Optimize all dependencies first. Note: we ignore the return value and march on
8407        // on errors.
8408        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8409        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8410        if (!deps.isEmpty()) {
8411            for (PackageParser.Package depPackage : deps) {
8412                // TODO: Analyze and investigate if we (should) profile libraries.
8413                // Currently this will do a full compilation of the library by default.
8414                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8415                        false /* checkProfiles */,
8416                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8417                        getOrCreateCompilerPackageStats(depPackage));
8418            }
8419        }
8420        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8421                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8422    }
8423
8424    // Performs dexopt on the used secondary dex files belonging to the given package.
8425    // Returns true if all dex files were process successfully (which could mean either dexopt or
8426    // skip). Returns false if any of the files caused errors.
8427    @Override
8428    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8429            boolean force) {
8430        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8431    }
8432
8433    /**
8434     * Reconcile the information we have about the secondary dex files belonging to
8435     * {@code packagName} and the actual dex files. For all dex files that were
8436     * deleted, update the internal records and delete the generated oat files.
8437     */
8438    @Override
8439    public void reconcileSecondaryDexFiles(String packageName) {
8440        mDexManager.reconcileSecondaryDexFiles(packageName);
8441    }
8442
8443    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8444    // a reference there.
8445    /*package*/ DexManager getDexManager() {
8446        return mDexManager;
8447    }
8448
8449    /**
8450     * Execute the background dexopt job immediately.
8451     */
8452    @Override
8453    public boolean runBackgroundDexoptJob() {
8454        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8455    }
8456
8457    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8458        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8459                || p.usesStaticLibraries != null) {
8460            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8461            Set<String> collectedNames = new HashSet<>();
8462            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8463
8464            retValue.remove(p);
8465
8466            return retValue;
8467        } else {
8468            return Collections.emptyList();
8469        }
8470    }
8471
8472    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8473            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8474        if (!collectedNames.contains(p.packageName)) {
8475            collectedNames.add(p.packageName);
8476            collected.add(p);
8477
8478            if (p.usesLibraries != null) {
8479                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8480                        null, collected, collectedNames);
8481            }
8482            if (p.usesOptionalLibraries != null) {
8483                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8484                        null, collected, collectedNames);
8485            }
8486            if (p.usesStaticLibraries != null) {
8487                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8488                        p.usesStaticLibrariesVersions, collected, collectedNames);
8489            }
8490        }
8491    }
8492
8493    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8494            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8495        final int libNameCount = libs.size();
8496        for (int i = 0; i < libNameCount; i++) {
8497            String libName = libs.get(i);
8498            int version = (versions != null && versions.length == libNameCount)
8499                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8500            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8501            if (libPkg != null) {
8502                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8503            }
8504        }
8505    }
8506
8507    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8508        synchronized (mPackages) {
8509            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8510            if (libEntry != null) {
8511                return mPackages.get(libEntry.apk);
8512            }
8513            return null;
8514        }
8515    }
8516
8517    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8518        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8519        if (versionedLib == null) {
8520            return null;
8521        }
8522        return versionedLib.get(version);
8523    }
8524
8525    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8526        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8527                pkg.staticSharedLibName);
8528        if (versionedLib == null) {
8529            return null;
8530        }
8531        int previousLibVersion = -1;
8532        final int versionCount = versionedLib.size();
8533        for (int i = 0; i < versionCount; i++) {
8534            final int libVersion = versionedLib.keyAt(i);
8535            if (libVersion < pkg.staticSharedLibVersion) {
8536                previousLibVersion = Math.max(previousLibVersion, libVersion);
8537            }
8538        }
8539        if (previousLibVersion >= 0) {
8540            return versionedLib.get(previousLibVersion);
8541        }
8542        return null;
8543    }
8544
8545    public void shutdown() {
8546        mPackageUsage.writeNow(mPackages);
8547        mCompilerStats.writeNow();
8548    }
8549
8550    @Override
8551    public void dumpProfiles(String packageName) {
8552        PackageParser.Package pkg;
8553        synchronized (mPackages) {
8554            pkg = mPackages.get(packageName);
8555            if (pkg == null) {
8556                throw new IllegalArgumentException("Unknown package: " + packageName);
8557            }
8558        }
8559        /* Only the shell, root, or the app user should be able to dump profiles. */
8560        int callingUid = Binder.getCallingUid();
8561        if (callingUid != Process.SHELL_UID &&
8562            callingUid != Process.ROOT_UID &&
8563            callingUid != pkg.applicationInfo.uid) {
8564            throw new SecurityException("dumpProfiles");
8565        }
8566
8567        synchronized (mInstallLock) {
8568            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8569            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8570            try {
8571                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8572                String codePaths = TextUtils.join(";", allCodePaths);
8573                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8574            } catch (InstallerException e) {
8575                Slog.w(TAG, "Failed to dump profiles", e);
8576            }
8577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8578        }
8579    }
8580
8581    @Override
8582    public void forceDexOpt(String packageName) {
8583        enforceSystemOrRoot("forceDexOpt");
8584
8585        PackageParser.Package pkg;
8586        synchronized (mPackages) {
8587            pkg = mPackages.get(packageName);
8588            if (pkg == null) {
8589                throw new IllegalArgumentException("Unknown package: " + packageName);
8590            }
8591        }
8592
8593        synchronized (mInstallLock) {
8594            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8595
8596            // Whoever is calling forceDexOpt wants a fully compiled package.
8597            // Don't use profiles since that may cause compilation to be skipped.
8598            final int res = performDexOptInternalWithDependenciesLI(pkg,
8599                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8600                    true /* force */);
8601
8602            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8603            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8604                throw new IllegalStateException("Failed to dexopt: " + res);
8605            }
8606        }
8607    }
8608
8609    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8610        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8611            Slog.w(TAG, "Unable to update from " + oldPkg.name
8612                    + " to " + newPkg.packageName
8613                    + ": old package not in system partition");
8614            return false;
8615        } else if (mPackages.get(oldPkg.name) != null) {
8616            Slog.w(TAG, "Unable to update from " + oldPkg.name
8617                    + " to " + newPkg.packageName
8618                    + ": old package still exists");
8619            return false;
8620        }
8621        return true;
8622    }
8623
8624    void removeCodePathLI(File codePath) {
8625        if (codePath.isDirectory()) {
8626            try {
8627                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8628            } catch (InstallerException e) {
8629                Slog.w(TAG, "Failed to remove code path", e);
8630            }
8631        } else {
8632            codePath.delete();
8633        }
8634    }
8635
8636    private int[] resolveUserIds(int userId) {
8637        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8638    }
8639
8640    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8641        if (pkg == null) {
8642            Slog.wtf(TAG, "Package was null!", new Throwable());
8643            return;
8644        }
8645        clearAppDataLeafLIF(pkg, userId, flags);
8646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8647        for (int i = 0; i < childCount; i++) {
8648            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8649        }
8650    }
8651
8652    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8653        final PackageSetting ps;
8654        synchronized (mPackages) {
8655            ps = mSettings.mPackages.get(pkg.packageName);
8656        }
8657        for (int realUserId : resolveUserIds(userId)) {
8658            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8659            try {
8660                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8661                        ceDataInode);
8662            } catch (InstallerException e) {
8663                Slog.w(TAG, String.valueOf(e));
8664            }
8665        }
8666    }
8667
8668    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8669        if (pkg == null) {
8670            Slog.wtf(TAG, "Package was null!", new Throwable());
8671            return;
8672        }
8673        destroyAppDataLeafLIF(pkg, userId, flags);
8674        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8675        for (int i = 0; i < childCount; i++) {
8676            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8677        }
8678    }
8679
8680    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8681        final PackageSetting ps;
8682        synchronized (mPackages) {
8683            ps = mSettings.mPackages.get(pkg.packageName);
8684        }
8685        for (int realUserId : resolveUserIds(userId)) {
8686            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8687            try {
8688                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8689                        ceDataInode);
8690            } catch (InstallerException e) {
8691                Slog.w(TAG, String.valueOf(e));
8692            }
8693        }
8694    }
8695
8696    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8697        if (pkg == null) {
8698            Slog.wtf(TAG, "Package was null!", new Throwable());
8699            return;
8700        }
8701        destroyAppProfilesLeafLIF(pkg);
8702        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8704        for (int i = 0; i < childCount; i++) {
8705            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8706            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8707                    true /* removeBaseMarker */);
8708        }
8709    }
8710
8711    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8712            boolean removeBaseMarker) {
8713        if (pkg.isForwardLocked()) {
8714            return;
8715        }
8716
8717        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8718            try {
8719                path = PackageManagerServiceUtils.realpath(new File(path));
8720            } catch (IOException e) {
8721                // TODO: Should we return early here ?
8722                Slog.w(TAG, "Failed to get canonical path", e);
8723                continue;
8724            }
8725
8726            final String useMarker = path.replace('/', '@');
8727            for (int realUserId : resolveUserIds(userId)) {
8728                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8729                if (removeBaseMarker) {
8730                    File foreignUseMark = new File(profileDir, useMarker);
8731                    if (foreignUseMark.exists()) {
8732                        if (!foreignUseMark.delete()) {
8733                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8734                                    + pkg.packageName);
8735                        }
8736                    }
8737                }
8738
8739                File[] markers = profileDir.listFiles();
8740                if (markers != null) {
8741                    final String searchString = "@" + pkg.packageName + "@";
8742                    // We also delete all markers that contain the package name we're
8743                    // uninstalling. These are associated with secondary dex-files belonging
8744                    // to the package. Reconstructing the path of these dex files is messy
8745                    // in general.
8746                    for (File marker : markers) {
8747                        if (marker.getName().indexOf(searchString) > 0) {
8748                            if (!marker.delete()) {
8749                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8750                                    + pkg.packageName);
8751                            }
8752                        }
8753                    }
8754                }
8755            }
8756        }
8757    }
8758
8759    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8760        try {
8761            mInstaller.destroyAppProfiles(pkg.packageName);
8762        } catch (InstallerException e) {
8763            Slog.w(TAG, String.valueOf(e));
8764        }
8765    }
8766
8767    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8768        if (pkg == null) {
8769            Slog.wtf(TAG, "Package was null!", new Throwable());
8770            return;
8771        }
8772        clearAppProfilesLeafLIF(pkg);
8773        // We don't remove the base foreign use marker when clearing profiles because
8774        // we will rename it when the app is updated. Unlike the actual profile contents,
8775        // the foreign use marker is good across installs.
8776        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8777        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8778        for (int i = 0; i < childCount; i++) {
8779            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8780        }
8781    }
8782
8783    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8784        try {
8785            mInstaller.clearAppProfiles(pkg.packageName);
8786        } catch (InstallerException e) {
8787            Slog.w(TAG, String.valueOf(e));
8788        }
8789    }
8790
8791    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8792            long lastUpdateTime) {
8793        // Set parent install/update time
8794        PackageSetting ps = (PackageSetting) pkg.mExtras;
8795        if (ps != null) {
8796            ps.firstInstallTime = firstInstallTime;
8797            ps.lastUpdateTime = lastUpdateTime;
8798        }
8799        // Set children install/update time
8800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8801        for (int i = 0; i < childCount; i++) {
8802            PackageParser.Package childPkg = pkg.childPackages.get(i);
8803            ps = (PackageSetting) childPkg.mExtras;
8804            if (ps != null) {
8805                ps.firstInstallTime = firstInstallTime;
8806                ps.lastUpdateTime = lastUpdateTime;
8807            }
8808        }
8809    }
8810
8811    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8812            PackageParser.Package changingLib) {
8813        if (file.path != null) {
8814            usesLibraryFiles.add(file.path);
8815            return;
8816        }
8817        PackageParser.Package p = mPackages.get(file.apk);
8818        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8819            // If we are doing this while in the middle of updating a library apk,
8820            // then we need to make sure to use that new apk for determining the
8821            // dependencies here.  (We haven't yet finished committing the new apk
8822            // to the package manager state.)
8823            if (p == null || p.packageName.equals(changingLib.packageName)) {
8824                p = changingLib;
8825            }
8826        }
8827        if (p != null) {
8828            usesLibraryFiles.addAll(p.getAllCodePaths());
8829        }
8830    }
8831
8832    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8833            PackageParser.Package changingLib) throws PackageManagerException {
8834        if (pkg == null) {
8835            return;
8836        }
8837        ArraySet<String> usesLibraryFiles = null;
8838        if (pkg.usesLibraries != null) {
8839            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8840                    null, null, pkg.packageName, changingLib, true, null);
8841        }
8842        if (pkg.usesStaticLibraries != null) {
8843            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8844                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8845                    pkg.packageName, changingLib, true, usesLibraryFiles);
8846        }
8847        if (pkg.usesOptionalLibraries != null) {
8848            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8849                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8850        }
8851        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8852            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8853        } else {
8854            pkg.usesLibraryFiles = null;
8855        }
8856    }
8857
8858    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8859            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8860            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8861            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8862            throws PackageManagerException {
8863        final int libCount = requestedLibraries.size();
8864        for (int i = 0; i < libCount; i++) {
8865            final String libName = requestedLibraries.get(i);
8866            final int libVersion = requiredVersions != null ? requiredVersions[i]
8867                    : SharedLibraryInfo.VERSION_UNDEFINED;
8868            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8869            if (libEntry == null) {
8870                if (required) {
8871                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8872                            "Package " + packageName + " requires unavailable shared library "
8873                                    + libName + "; failing!");
8874                } else {
8875                    Slog.w(TAG, "Package " + packageName
8876                            + " desires unavailable shared library "
8877                            + libName + "; ignoring!");
8878                }
8879            } else {
8880                if (requiredVersions != null && requiredCertDigests != null) {
8881                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8882                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8883                            "Package " + packageName + " requires unavailable static shared"
8884                                    + " library " + libName + " version "
8885                                    + libEntry.info.getVersion() + "; failing!");
8886                    }
8887
8888                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8889                    if (libPkg == null) {
8890                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8891                                "Package " + packageName + " requires unavailable static shared"
8892                                        + " library; failing!");
8893                    }
8894
8895                    String expectedCertDigest = requiredCertDigests[i];
8896                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8897                                libPkg.mSignatures[0]);
8898                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8899                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8900                                "Package " + packageName + " requires differently signed" +
8901                                        " static shared library; failing!");
8902                    }
8903                }
8904
8905                if (outUsedLibraries == null) {
8906                    outUsedLibraries = new ArraySet<>();
8907                }
8908                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8909            }
8910        }
8911        return outUsedLibraries;
8912    }
8913
8914    private static boolean hasString(List<String> list, List<String> which) {
8915        if (list == null) {
8916            return false;
8917        }
8918        for (int i=list.size()-1; i>=0; i--) {
8919            for (int j=which.size()-1; j>=0; j--) {
8920                if (which.get(j).equals(list.get(i))) {
8921                    return true;
8922                }
8923            }
8924        }
8925        return false;
8926    }
8927
8928    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8929            PackageParser.Package changingPkg) {
8930        ArrayList<PackageParser.Package> res = null;
8931        for (PackageParser.Package pkg : mPackages.values()) {
8932            if (changingPkg != null
8933                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8934                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8935                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8936                            changingPkg.staticSharedLibName)) {
8937                return null;
8938            }
8939            if (res == null) {
8940                res = new ArrayList<>();
8941            }
8942            res.add(pkg);
8943            try {
8944                updateSharedLibrariesLPr(pkg, changingPkg);
8945            } catch (PackageManagerException e) {
8946                // If a system app update or an app and a required lib missing we
8947                // delete the package and for updated system apps keep the data as
8948                // it is better for the user to reinstall than to be in an limbo
8949                // state. Also libs disappearing under an app should never happen
8950                // - just in case.
8951                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8952                    final int flags = pkg.isUpdatedSystemApp()
8953                            ? PackageManager.DELETE_KEEP_DATA : 0;
8954                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8955                            flags , null, true, null);
8956                }
8957                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8958            }
8959        }
8960        return res;
8961    }
8962
8963    /**
8964     * Derive the value of the {@code cpuAbiOverride} based on the provided
8965     * value and an optional stored value from the package settings.
8966     */
8967    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8968        String cpuAbiOverride = null;
8969
8970        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8971            cpuAbiOverride = null;
8972        } else if (abiOverride != null) {
8973            cpuAbiOverride = abiOverride;
8974        } else if (settings != null) {
8975            cpuAbiOverride = settings.cpuAbiOverrideString;
8976        }
8977
8978        return cpuAbiOverride;
8979    }
8980
8981    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8982            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8983                    throws PackageManagerException {
8984        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8985        // If the package has children and this is the first dive in the function
8986        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8987        // whether all packages (parent and children) would be successfully scanned
8988        // before the actual scan since scanning mutates internal state and we want
8989        // to atomically install the package and its children.
8990        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8991            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8992                scanFlags |= SCAN_CHECK_ONLY;
8993            }
8994        } else {
8995            scanFlags &= ~SCAN_CHECK_ONLY;
8996        }
8997
8998        final PackageParser.Package scannedPkg;
8999        try {
9000            // Scan the parent
9001            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9002            // Scan the children
9003            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9004            for (int i = 0; i < childCount; i++) {
9005                PackageParser.Package childPkg = pkg.childPackages.get(i);
9006                scanPackageLI(childPkg, policyFlags,
9007                        scanFlags, currentTime, user);
9008            }
9009        } finally {
9010            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9011        }
9012
9013        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9014            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9015        }
9016
9017        return scannedPkg;
9018    }
9019
9020    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9021            int scanFlags, long currentTime, @Nullable UserHandle user)
9022                    throws PackageManagerException {
9023        boolean success = false;
9024        try {
9025            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9026                    currentTime, user);
9027            success = true;
9028            return res;
9029        } finally {
9030            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9031                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9032                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9033                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9034                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9035            }
9036        }
9037    }
9038
9039    /**
9040     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9041     */
9042    private static boolean apkHasCode(String fileName) {
9043        StrictJarFile jarFile = null;
9044        try {
9045            jarFile = new StrictJarFile(fileName,
9046                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9047            return jarFile.findEntry("classes.dex") != null;
9048        } catch (IOException ignore) {
9049        } finally {
9050            try {
9051                if (jarFile != null) {
9052                    jarFile.close();
9053                }
9054            } catch (IOException ignore) {}
9055        }
9056        return false;
9057    }
9058
9059    /**
9060     * Enforces code policy for the package. This ensures that if an APK has
9061     * declared hasCode="true" in its manifest that the APK actually contains
9062     * code.
9063     *
9064     * @throws PackageManagerException If bytecode could not be found when it should exist
9065     */
9066    private static void assertCodePolicy(PackageParser.Package pkg)
9067            throws PackageManagerException {
9068        final boolean shouldHaveCode =
9069                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9070        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9071            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9072                    "Package " + pkg.baseCodePath + " code is missing");
9073        }
9074
9075        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9076            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9077                final boolean splitShouldHaveCode =
9078                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9079                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9080                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9081                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9082                }
9083            }
9084        }
9085    }
9086
9087    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9088            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9089                    throws PackageManagerException {
9090        if (DEBUG_PACKAGE_SCANNING) {
9091            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9092                Log.d(TAG, "Scanning package " + pkg.packageName);
9093        }
9094
9095        applyPolicy(pkg, policyFlags);
9096
9097        assertPackageIsValid(pkg, policyFlags, scanFlags);
9098
9099        // Initialize package source and resource directories
9100        final File scanFile = new File(pkg.codePath);
9101        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9102        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9103
9104        SharedUserSetting suid = null;
9105        PackageSetting pkgSetting = null;
9106
9107        // Getting the package setting may have a side-effect, so if we
9108        // are only checking if scan would succeed, stash a copy of the
9109        // old setting to restore at the end.
9110        PackageSetting nonMutatedPs = null;
9111
9112        // We keep references to the derived CPU Abis from settings in oder to reuse
9113        // them in the case where we're not upgrading or booting for the first time.
9114        String primaryCpuAbiFromSettings = null;
9115        String secondaryCpuAbiFromSettings = null;
9116
9117        // writer
9118        synchronized (mPackages) {
9119            if (pkg.mSharedUserId != null) {
9120                // SIDE EFFECTS; may potentially allocate a new shared user
9121                suid = mSettings.getSharedUserLPw(
9122                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9123                if (DEBUG_PACKAGE_SCANNING) {
9124                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9125                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9126                                + "): packages=" + suid.packages);
9127                }
9128            }
9129
9130            // Check if we are renaming from an original package name.
9131            PackageSetting origPackage = null;
9132            String realName = null;
9133            if (pkg.mOriginalPackages != null) {
9134                // This package may need to be renamed to a previously
9135                // installed name.  Let's check on that...
9136                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9137                if (pkg.mOriginalPackages.contains(renamed)) {
9138                    // This package had originally been installed as the
9139                    // original name, and we have already taken care of
9140                    // transitioning to the new one.  Just update the new
9141                    // one to continue using the old name.
9142                    realName = pkg.mRealPackage;
9143                    if (!pkg.packageName.equals(renamed)) {
9144                        // Callers into this function may have already taken
9145                        // care of renaming the package; only do it here if
9146                        // it is not already done.
9147                        pkg.setPackageName(renamed);
9148                    }
9149                } else {
9150                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9151                        if ((origPackage = mSettings.getPackageLPr(
9152                                pkg.mOriginalPackages.get(i))) != null) {
9153                            // We do have the package already installed under its
9154                            // original name...  should we use it?
9155                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9156                                // New package is not compatible with original.
9157                                origPackage = null;
9158                                continue;
9159                            } else if (origPackage.sharedUser != null) {
9160                                // Make sure uid is compatible between packages.
9161                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9162                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9163                                            + " to " + pkg.packageName + ": old uid "
9164                                            + origPackage.sharedUser.name
9165                                            + " differs from " + pkg.mSharedUserId);
9166                                    origPackage = null;
9167                                    continue;
9168                                }
9169                                // TODO: Add case when shared user id is added [b/28144775]
9170                            } else {
9171                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9172                                        + pkg.packageName + " to old name " + origPackage.name);
9173                            }
9174                            break;
9175                        }
9176                    }
9177                }
9178            }
9179
9180            if (mTransferedPackages.contains(pkg.packageName)) {
9181                Slog.w(TAG, "Package " + pkg.packageName
9182                        + " was transferred to another, but its .apk remains");
9183            }
9184
9185            // See comments in nonMutatedPs declaration
9186            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9187                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9188                if (foundPs != null) {
9189                    nonMutatedPs = new PackageSetting(foundPs);
9190                }
9191            }
9192
9193            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9194                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9195                if (foundPs != null) {
9196                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9197                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9198                }
9199            }
9200
9201            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9202            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9203                PackageManagerService.reportSettingsProblem(Log.WARN,
9204                        "Package " + pkg.packageName + " shared user changed from "
9205                                + (pkgSetting.sharedUser != null
9206                                        ? pkgSetting.sharedUser.name : "<nothing>")
9207                                + " to "
9208                                + (suid != null ? suid.name : "<nothing>")
9209                                + "; replacing with new");
9210                pkgSetting = null;
9211            }
9212            final PackageSetting oldPkgSetting =
9213                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9214            final PackageSetting disabledPkgSetting =
9215                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9216
9217            String[] usesStaticLibraries = null;
9218            if (pkg.usesStaticLibraries != null) {
9219                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9220                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9221            }
9222
9223            if (pkgSetting == null) {
9224                final String parentPackageName = (pkg.parentPackage != null)
9225                        ? pkg.parentPackage.packageName : null;
9226                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9227                // REMOVE SharedUserSetting from method; update in a separate call
9228                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9229                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9230                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9231                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9232                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9233                        true /*allowInstall*/, instantApp, parentPackageName,
9234                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9235                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9236                // SIDE EFFECTS; updates system state; move elsewhere
9237                if (origPackage != null) {
9238                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9239                }
9240                mSettings.addUserToSettingLPw(pkgSetting);
9241            } else {
9242                // REMOVE SharedUserSetting from method; update in a separate call.
9243                //
9244                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9245                // secondaryCpuAbi are not known at this point so we always update them
9246                // to null here, only to reset them at a later point.
9247                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9248                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9249                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9250                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9251                        UserManagerService.getInstance(), usesStaticLibraries,
9252                        pkg.usesStaticLibrariesVersions);
9253            }
9254            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9255            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9256
9257            // SIDE EFFECTS; modifies system state; move elsewhere
9258            if (pkgSetting.origPackage != null) {
9259                // If we are first transitioning from an original package,
9260                // fix up the new package's name now.  We need to do this after
9261                // looking up the package under its new name, so getPackageLP
9262                // can take care of fiddling things correctly.
9263                pkg.setPackageName(origPackage.name);
9264
9265                // File a report about this.
9266                String msg = "New package " + pkgSetting.realName
9267                        + " renamed to replace old package " + pkgSetting.name;
9268                reportSettingsProblem(Log.WARN, msg);
9269
9270                // Make a note of it.
9271                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9272                    mTransferedPackages.add(origPackage.name);
9273                }
9274
9275                // No longer need to retain this.
9276                pkgSetting.origPackage = null;
9277            }
9278
9279            // SIDE EFFECTS; modifies system state; move elsewhere
9280            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9281                // Make a note of it.
9282                mTransferedPackages.add(pkg.packageName);
9283            }
9284
9285            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9286                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9287            }
9288
9289            if ((scanFlags & SCAN_BOOTING) == 0
9290                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9291                // Check all shared libraries and map to their actual file path.
9292                // We only do this here for apps not on a system dir, because those
9293                // are the only ones that can fail an install due to this.  We
9294                // will take care of the system apps by updating all of their
9295                // library paths after the scan is done. Also during the initial
9296                // scan don't update any libs as we do this wholesale after all
9297                // apps are scanned to avoid dependency based scanning.
9298                updateSharedLibrariesLPr(pkg, null);
9299            }
9300
9301            if (mFoundPolicyFile) {
9302                SELinuxMMAC.assignSeInfoValue(pkg);
9303            }
9304            pkg.applicationInfo.uid = pkgSetting.appId;
9305            pkg.mExtras = pkgSetting;
9306
9307
9308            // Static shared libs have same package with different versions where
9309            // we internally use a synthetic package name to allow multiple versions
9310            // of the same package, therefore we need to compare signatures against
9311            // the package setting for the latest library version.
9312            PackageSetting signatureCheckPs = pkgSetting;
9313            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9314                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9315                if (libraryEntry != null) {
9316                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9317                }
9318            }
9319
9320            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9321                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9322                    // We just determined the app is signed correctly, so bring
9323                    // over the latest parsed certs.
9324                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9325                } else {
9326                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9327                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9328                                "Package " + pkg.packageName + " upgrade keys do not match the "
9329                                + "previously installed version");
9330                    } else {
9331                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9332                        String msg = "System package " + pkg.packageName
9333                                + " signature changed; retaining data.";
9334                        reportSettingsProblem(Log.WARN, msg);
9335                    }
9336                }
9337            } else {
9338                try {
9339                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9340                    verifySignaturesLP(signatureCheckPs, pkg);
9341                    // We just determined the app is signed correctly, so bring
9342                    // over the latest parsed certs.
9343                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9344                } catch (PackageManagerException e) {
9345                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9346                        throw e;
9347                    }
9348                    // The signature has changed, but this package is in the system
9349                    // image...  let's recover!
9350                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9351                    // However...  if this package is part of a shared user, but it
9352                    // doesn't match the signature of the shared user, let's fail.
9353                    // What this means is that you can't change the signatures
9354                    // associated with an overall shared user, which doesn't seem all
9355                    // that unreasonable.
9356                    if (signatureCheckPs.sharedUser != null) {
9357                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9358                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9359                            throw new PackageManagerException(
9360                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9361                                    "Signature mismatch for shared user: "
9362                                            + pkgSetting.sharedUser);
9363                        }
9364                    }
9365                    // File a report about this.
9366                    String msg = "System package " + pkg.packageName
9367                            + " signature changed; retaining data.";
9368                    reportSettingsProblem(Log.WARN, msg);
9369                }
9370            }
9371
9372            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9373                // This package wants to adopt ownership of permissions from
9374                // another package.
9375                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9376                    final String origName = pkg.mAdoptPermissions.get(i);
9377                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9378                    if (orig != null) {
9379                        if (verifyPackageUpdateLPr(orig, pkg)) {
9380                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9381                                    + pkg.packageName);
9382                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9383                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9384                        }
9385                    }
9386                }
9387            }
9388        }
9389
9390        pkg.applicationInfo.processName = fixProcessName(
9391                pkg.applicationInfo.packageName,
9392                pkg.applicationInfo.processName);
9393
9394        if (pkg != mPlatformPackage) {
9395            // Get all of our default paths setup
9396            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9397        }
9398
9399        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9400
9401        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9402            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9403                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9404                derivePackageAbi(
9405                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9406                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9407
9408                // Some system apps still use directory structure for native libraries
9409                // in which case we might end up not detecting abi solely based on apk
9410                // structure. Try to detect abi based on directory structure.
9411                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9412                        pkg.applicationInfo.primaryCpuAbi == null) {
9413                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9414                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9415                }
9416            } else {
9417                // This is not a first boot or an upgrade, don't bother deriving the
9418                // ABI during the scan. Instead, trust the value that was stored in the
9419                // package setting.
9420                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9421                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9422
9423                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9424
9425                if (DEBUG_ABI_SELECTION) {
9426                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9427                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9428                        pkg.applicationInfo.secondaryCpuAbi);
9429                }
9430            }
9431        } else {
9432            if ((scanFlags & SCAN_MOVE) != 0) {
9433                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9434                // but we already have this packages package info in the PackageSetting. We just
9435                // use that and derive the native library path based on the new codepath.
9436                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9437                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9438            }
9439
9440            // Set native library paths again. For moves, the path will be updated based on the
9441            // ABIs we've determined above. For non-moves, the path will be updated based on the
9442            // ABIs we determined during compilation, but the path will depend on the final
9443            // package path (after the rename away from the stage path).
9444            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9445        }
9446
9447        // This is a special case for the "system" package, where the ABI is
9448        // dictated by the zygote configuration (and init.rc). We should keep track
9449        // of this ABI so that we can deal with "normal" applications that run under
9450        // the same UID correctly.
9451        if (mPlatformPackage == pkg) {
9452            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9453                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9454        }
9455
9456        // If there's a mismatch between the abi-override in the package setting
9457        // and the abiOverride specified for the install. Warn about this because we
9458        // would've already compiled the app without taking the package setting into
9459        // account.
9460        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9461            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9462                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9463                        " for package " + pkg.packageName);
9464            }
9465        }
9466
9467        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9468        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9469        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9470
9471        // Copy the derived override back to the parsed package, so that we can
9472        // update the package settings accordingly.
9473        pkg.cpuAbiOverride = cpuAbiOverride;
9474
9475        if (DEBUG_ABI_SELECTION) {
9476            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9477                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9478                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9479        }
9480
9481        // Push the derived path down into PackageSettings so we know what to
9482        // clean up at uninstall time.
9483        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9484
9485        if (DEBUG_ABI_SELECTION) {
9486            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9487                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9488                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9489        }
9490
9491        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9492        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9493            // We don't do this here during boot because we can do it all
9494            // at once after scanning all existing packages.
9495            //
9496            // We also do this *before* we perform dexopt on this package, so that
9497            // we can avoid redundant dexopts, and also to make sure we've got the
9498            // code and package path correct.
9499            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9500        }
9501
9502        if (mFactoryTest && pkg.requestedPermissions.contains(
9503                android.Manifest.permission.FACTORY_TEST)) {
9504            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9505        }
9506
9507        if (isSystemApp(pkg)) {
9508            pkgSetting.isOrphaned = true;
9509        }
9510
9511        // Take care of first install / last update times.
9512        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9513        if (currentTime != 0) {
9514            if (pkgSetting.firstInstallTime == 0) {
9515                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9516            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9517                pkgSetting.lastUpdateTime = currentTime;
9518            }
9519        } else if (pkgSetting.firstInstallTime == 0) {
9520            // We need *something*.  Take time time stamp of the file.
9521            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9522        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9523            if (scanFileTime != pkgSetting.timeStamp) {
9524                // A package on the system image has changed; consider this
9525                // to be an update.
9526                pkgSetting.lastUpdateTime = scanFileTime;
9527            }
9528        }
9529        pkgSetting.setTimeStamp(scanFileTime);
9530
9531        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9532            if (nonMutatedPs != null) {
9533                synchronized (mPackages) {
9534                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9535                }
9536            }
9537        } else {
9538            final int userId = user == null ? 0 : user.getIdentifier();
9539            // Modify state for the given package setting
9540            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9541                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9542            if (pkgSetting.getInstantApp(userId)) {
9543                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9544            }
9545        }
9546        return pkg;
9547    }
9548
9549    /**
9550     * Applies policy to the parsed package based upon the given policy flags.
9551     * Ensures the package is in a good state.
9552     * <p>
9553     * Implementation detail: This method must NOT have any side effect. It would
9554     * ideally be static, but, it requires locks to read system state.
9555     */
9556    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9557        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9558            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9559            if (pkg.applicationInfo.isDirectBootAware()) {
9560                // we're direct boot aware; set for all components
9561                for (PackageParser.Service s : pkg.services) {
9562                    s.info.encryptionAware = s.info.directBootAware = true;
9563                }
9564                for (PackageParser.Provider p : pkg.providers) {
9565                    p.info.encryptionAware = p.info.directBootAware = true;
9566                }
9567                for (PackageParser.Activity a : pkg.activities) {
9568                    a.info.encryptionAware = a.info.directBootAware = true;
9569                }
9570                for (PackageParser.Activity r : pkg.receivers) {
9571                    r.info.encryptionAware = r.info.directBootAware = true;
9572                }
9573            }
9574        } else {
9575            // Only allow system apps to be flagged as core apps.
9576            pkg.coreApp = false;
9577            // clear flags not applicable to regular apps
9578            pkg.applicationInfo.privateFlags &=
9579                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9580            pkg.applicationInfo.privateFlags &=
9581                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9582        }
9583        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9584
9585        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9586            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9587        }
9588
9589        if (!isSystemApp(pkg)) {
9590            // Only system apps can use these features.
9591            pkg.mOriginalPackages = null;
9592            pkg.mRealPackage = null;
9593            pkg.mAdoptPermissions = null;
9594        }
9595    }
9596
9597    /**
9598     * Asserts the parsed package is valid according to the given policy. If the
9599     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9600     * <p>
9601     * Implementation detail: This method must NOT have any side effects. It would
9602     * ideally be static, but, it requires locks to read system state.
9603     *
9604     * @throws PackageManagerException If the package fails any of the validation checks
9605     */
9606    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9607            throws PackageManagerException {
9608        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9609            assertCodePolicy(pkg);
9610        }
9611
9612        if (pkg.applicationInfo.getCodePath() == null ||
9613                pkg.applicationInfo.getResourcePath() == null) {
9614            // Bail out. The resource and code paths haven't been set.
9615            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9616                    "Code and resource paths haven't been set correctly");
9617        }
9618
9619        // Make sure we're not adding any bogus keyset info
9620        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9621        ksms.assertScannedPackageValid(pkg);
9622
9623        synchronized (mPackages) {
9624            // The special "android" package can only be defined once
9625            if (pkg.packageName.equals("android")) {
9626                if (mAndroidApplication != null) {
9627                    Slog.w(TAG, "*************************************************");
9628                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9629                    Slog.w(TAG, " codePath=" + pkg.codePath);
9630                    Slog.w(TAG, "*************************************************");
9631                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9632                            "Core android package being redefined.  Skipping.");
9633                }
9634            }
9635
9636            // A package name must be unique; don't allow duplicates
9637            if (mPackages.containsKey(pkg.packageName)) {
9638                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9639                        "Application package " + pkg.packageName
9640                        + " already installed.  Skipping duplicate.");
9641            }
9642
9643            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9644                // Static libs have a synthetic package name containing the version
9645                // but we still want the base name to be unique.
9646                if (mPackages.containsKey(pkg.manifestPackageName)) {
9647                    throw new PackageManagerException(
9648                            "Duplicate static shared lib provider package");
9649                }
9650
9651                // Static shared libraries should have at least O target SDK
9652                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9653                    throw new PackageManagerException(
9654                            "Packages declaring static-shared libs must target O SDK or higher");
9655                }
9656
9657                // Package declaring static a shared lib cannot be instant apps
9658                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9659                    throw new PackageManagerException(
9660                            "Packages declaring static-shared libs cannot be instant apps");
9661                }
9662
9663                // Package declaring static a shared lib cannot be renamed since the package
9664                // name is synthetic and apps can't code around package manager internals.
9665                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9666                    throw new PackageManagerException(
9667                            "Packages declaring static-shared libs cannot be renamed");
9668                }
9669
9670                // Package declaring static a shared lib cannot declare child packages
9671                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9672                    throw new PackageManagerException(
9673                            "Packages declaring static-shared libs cannot have child packages");
9674                }
9675
9676                // Package declaring static a shared lib cannot declare dynamic libs
9677                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9678                    throw new PackageManagerException(
9679                            "Packages declaring static-shared libs cannot declare dynamic libs");
9680                }
9681
9682                // Package declaring static a shared lib cannot declare shared users
9683                if (pkg.mSharedUserId != null) {
9684                    throw new PackageManagerException(
9685                            "Packages declaring static-shared libs cannot declare shared users");
9686                }
9687
9688                // Static shared libs cannot declare activities
9689                if (!pkg.activities.isEmpty()) {
9690                    throw new PackageManagerException(
9691                            "Static shared libs cannot declare activities");
9692                }
9693
9694                // Static shared libs cannot declare services
9695                if (!pkg.services.isEmpty()) {
9696                    throw new PackageManagerException(
9697                            "Static shared libs cannot declare services");
9698                }
9699
9700                // Static shared libs cannot declare providers
9701                if (!pkg.providers.isEmpty()) {
9702                    throw new PackageManagerException(
9703                            "Static shared libs cannot declare content providers");
9704                }
9705
9706                // Static shared libs cannot declare receivers
9707                if (!pkg.receivers.isEmpty()) {
9708                    throw new PackageManagerException(
9709                            "Static shared libs cannot declare broadcast receivers");
9710                }
9711
9712                // Static shared libs cannot declare permission groups
9713                if (!pkg.permissionGroups.isEmpty()) {
9714                    throw new PackageManagerException(
9715                            "Static shared libs cannot declare permission groups");
9716                }
9717
9718                // Static shared libs cannot declare permissions
9719                if (!pkg.permissions.isEmpty()) {
9720                    throw new PackageManagerException(
9721                            "Static shared libs cannot declare permissions");
9722                }
9723
9724                // Static shared libs cannot declare protected broadcasts
9725                if (pkg.protectedBroadcasts != null) {
9726                    throw new PackageManagerException(
9727                            "Static shared libs cannot declare protected broadcasts");
9728                }
9729
9730                // Static shared libs cannot be overlay targets
9731                if (pkg.mOverlayTarget != null) {
9732                    throw new PackageManagerException(
9733                            "Static shared libs cannot be overlay targets");
9734                }
9735
9736                // The version codes must be ordered as lib versions
9737                int minVersionCode = Integer.MIN_VALUE;
9738                int maxVersionCode = Integer.MAX_VALUE;
9739
9740                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9741                        pkg.staticSharedLibName);
9742                if (versionedLib != null) {
9743                    final int versionCount = versionedLib.size();
9744                    for (int i = 0; i < versionCount; i++) {
9745                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9746                        // TODO: We will change version code to long, so in the new API it is long
9747                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9748                                .getVersionCode();
9749                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9750                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9751                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9752                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9753                        } else {
9754                            minVersionCode = maxVersionCode = libVersionCode;
9755                            break;
9756                        }
9757                    }
9758                }
9759                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9760                    throw new PackageManagerException("Static shared"
9761                            + " lib version codes must be ordered as lib versions");
9762                }
9763            }
9764
9765            // Only privileged apps and updated privileged apps can add child packages.
9766            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9767                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9768                    throw new PackageManagerException("Only privileged apps can add child "
9769                            + "packages. Ignoring package " + pkg.packageName);
9770                }
9771                final int childCount = pkg.childPackages.size();
9772                for (int i = 0; i < childCount; i++) {
9773                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9774                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9775                            childPkg.packageName)) {
9776                        throw new PackageManagerException("Can't override child of "
9777                                + "another disabled app. Ignoring package " + pkg.packageName);
9778                    }
9779                }
9780            }
9781
9782            // If we're only installing presumed-existing packages, require that the
9783            // scanned APK is both already known and at the path previously established
9784            // for it.  Previously unknown packages we pick up normally, but if we have an
9785            // a priori expectation about this package's install presence, enforce it.
9786            // With a singular exception for new system packages. When an OTA contains
9787            // a new system package, we allow the codepath to change from a system location
9788            // to the user-installed location. If we don't allow this change, any newer,
9789            // user-installed version of the application will be ignored.
9790            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9791                if (mExpectingBetter.containsKey(pkg.packageName)) {
9792                    logCriticalInfo(Log.WARN,
9793                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9794                } else {
9795                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9796                    if (known != null) {
9797                        if (DEBUG_PACKAGE_SCANNING) {
9798                            Log.d(TAG, "Examining " + pkg.codePath
9799                                    + " and requiring known paths " + known.codePathString
9800                                    + " & " + known.resourcePathString);
9801                        }
9802                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9803                                || !pkg.applicationInfo.getResourcePath().equals(
9804                                        known.resourcePathString)) {
9805                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9806                                    "Application package " + pkg.packageName
9807                                    + " found at " + pkg.applicationInfo.getCodePath()
9808                                    + " but expected at " + known.codePathString
9809                                    + "; ignoring.");
9810                        }
9811                    }
9812                }
9813            }
9814
9815            // Verify that this new package doesn't have any content providers
9816            // that conflict with existing packages.  Only do this if the
9817            // package isn't already installed, since we don't want to break
9818            // things that are installed.
9819            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9820                final int N = pkg.providers.size();
9821                int i;
9822                for (i=0; i<N; i++) {
9823                    PackageParser.Provider p = pkg.providers.get(i);
9824                    if (p.info.authority != null) {
9825                        String names[] = p.info.authority.split(";");
9826                        for (int j = 0; j < names.length; j++) {
9827                            if (mProvidersByAuthority.containsKey(names[j])) {
9828                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9829                                final String otherPackageName =
9830                                        ((other != null && other.getComponentName() != null) ?
9831                                                other.getComponentName().getPackageName() : "?");
9832                                throw new PackageManagerException(
9833                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9834                                        "Can't install because provider name " + names[j]
9835                                                + " (in package " + pkg.applicationInfo.packageName
9836                                                + ") is already used by " + otherPackageName);
9837                            }
9838                        }
9839                    }
9840                }
9841            }
9842        }
9843    }
9844
9845    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9846            int type, String declaringPackageName, int declaringVersionCode) {
9847        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9848        if (versionedLib == null) {
9849            versionedLib = new SparseArray<>();
9850            mSharedLibraries.put(name, versionedLib);
9851            if (type == SharedLibraryInfo.TYPE_STATIC) {
9852                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9853            }
9854        } else if (versionedLib.indexOfKey(version) >= 0) {
9855            return false;
9856        }
9857        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9858                version, type, declaringPackageName, declaringVersionCode);
9859        versionedLib.put(version, libEntry);
9860        return true;
9861    }
9862
9863    private boolean removeSharedLibraryLPw(String name, int version) {
9864        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9865        if (versionedLib == null) {
9866            return false;
9867        }
9868        final int libIdx = versionedLib.indexOfKey(version);
9869        if (libIdx < 0) {
9870            return false;
9871        }
9872        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9873        versionedLib.remove(version);
9874        if (versionedLib.size() <= 0) {
9875            mSharedLibraries.remove(name);
9876            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9877                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9878                        .getPackageName());
9879            }
9880        }
9881        return true;
9882    }
9883
9884    /**
9885     * Adds a scanned package to the system. When this method is finished, the package will
9886     * be available for query, resolution, etc...
9887     */
9888    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9889            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9890        final String pkgName = pkg.packageName;
9891        if (mCustomResolverComponentName != null &&
9892                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9893            setUpCustomResolverActivity(pkg);
9894        }
9895
9896        if (pkg.packageName.equals("android")) {
9897            synchronized (mPackages) {
9898                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9899                    // Set up information for our fall-back user intent resolution activity.
9900                    mPlatformPackage = pkg;
9901                    pkg.mVersionCode = mSdkVersion;
9902                    mAndroidApplication = pkg.applicationInfo;
9903                    if (!mResolverReplaced) {
9904                        mResolveActivity.applicationInfo = mAndroidApplication;
9905                        mResolveActivity.name = ResolverActivity.class.getName();
9906                        mResolveActivity.packageName = mAndroidApplication.packageName;
9907                        mResolveActivity.processName = "system:ui";
9908                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9909                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9910                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9911                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9912                        mResolveActivity.exported = true;
9913                        mResolveActivity.enabled = true;
9914                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9915                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9916                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9917                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9918                                | ActivityInfo.CONFIG_ORIENTATION
9919                                | ActivityInfo.CONFIG_KEYBOARD
9920                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9921                        mResolveInfo.activityInfo = mResolveActivity;
9922                        mResolveInfo.priority = 0;
9923                        mResolveInfo.preferredOrder = 0;
9924                        mResolveInfo.match = 0;
9925                        mResolveComponentName = new ComponentName(
9926                                mAndroidApplication.packageName, mResolveActivity.name);
9927                    }
9928                }
9929            }
9930        }
9931
9932        ArrayList<PackageParser.Package> clientLibPkgs = null;
9933        // writer
9934        synchronized (mPackages) {
9935            boolean hasStaticSharedLibs = false;
9936
9937            // Any app can add new static shared libraries
9938            if (pkg.staticSharedLibName != null) {
9939                // Static shared libs don't allow renaming as they have synthetic package
9940                // names to allow install of multiple versions, so use name from manifest.
9941                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9942                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9943                        pkg.manifestPackageName, pkg.mVersionCode)) {
9944                    hasStaticSharedLibs = true;
9945                } else {
9946                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9947                                + pkg.staticSharedLibName + " already exists; skipping");
9948                }
9949                // Static shared libs cannot be updated once installed since they
9950                // use synthetic package name which includes the version code, so
9951                // not need to update other packages's shared lib dependencies.
9952            }
9953
9954            if (!hasStaticSharedLibs
9955                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9956                // Only system apps can add new dynamic shared libraries.
9957                if (pkg.libraryNames != null) {
9958                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9959                        String name = pkg.libraryNames.get(i);
9960                        boolean allowed = false;
9961                        if (pkg.isUpdatedSystemApp()) {
9962                            // New library entries can only be added through the
9963                            // system image.  This is important to get rid of a lot
9964                            // of nasty edge cases: for example if we allowed a non-
9965                            // system update of the app to add a library, then uninstalling
9966                            // the update would make the library go away, and assumptions
9967                            // we made such as through app install filtering would now
9968                            // have allowed apps on the device which aren't compatible
9969                            // with it.  Better to just have the restriction here, be
9970                            // conservative, and create many fewer cases that can negatively
9971                            // impact the user experience.
9972                            final PackageSetting sysPs = mSettings
9973                                    .getDisabledSystemPkgLPr(pkg.packageName);
9974                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9975                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9976                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9977                                        allowed = true;
9978                                        break;
9979                                    }
9980                                }
9981                            }
9982                        } else {
9983                            allowed = true;
9984                        }
9985                        if (allowed) {
9986                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9987                                    SharedLibraryInfo.VERSION_UNDEFINED,
9988                                    SharedLibraryInfo.TYPE_DYNAMIC,
9989                                    pkg.packageName, pkg.mVersionCode)) {
9990                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9991                                        + name + " already exists; skipping");
9992                            }
9993                        } else {
9994                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9995                                    + name + " that is not declared on system image; skipping");
9996                        }
9997                    }
9998
9999                    if ((scanFlags & SCAN_BOOTING) == 0) {
10000                        // If we are not booting, we need to update any applications
10001                        // that are clients of our shared library.  If we are booting,
10002                        // this will all be done once the scan is complete.
10003                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10004                    }
10005                }
10006            }
10007        }
10008
10009        if ((scanFlags & SCAN_BOOTING) != 0) {
10010            // No apps can run during boot scan, so they don't need to be frozen
10011        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10012            // Caller asked to not kill app, so it's probably not frozen
10013        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10014            // Caller asked us to ignore frozen check for some reason; they
10015            // probably didn't know the package name
10016        } else {
10017            // We're doing major surgery on this package, so it better be frozen
10018            // right now to keep it from launching
10019            checkPackageFrozen(pkgName);
10020        }
10021
10022        // Also need to kill any apps that are dependent on the library.
10023        if (clientLibPkgs != null) {
10024            for (int i=0; i<clientLibPkgs.size(); i++) {
10025                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10026                killApplication(clientPkg.applicationInfo.packageName,
10027                        clientPkg.applicationInfo.uid, "update lib");
10028            }
10029        }
10030
10031        // writer
10032        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10033
10034        synchronized (mPackages) {
10035            // We don't expect installation to fail beyond this point
10036
10037            if (pkgSetting.pkg != null) {
10038                // Note that |user| might be null during the initial boot scan. If a codePath
10039                // for an app has changed during a boot scan, it's due to an app update that's
10040                // part of the system partition and marker changes must be applied to all users.
10041                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
10042                final int[] userIds = resolveUserIds(userId);
10043                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
10044            }
10045
10046            // Add the new setting to mSettings
10047            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10048            // Add the new setting to mPackages
10049            mPackages.put(pkg.applicationInfo.packageName, pkg);
10050            // Make sure we don't accidentally delete its data.
10051            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10052            while (iter.hasNext()) {
10053                PackageCleanItem item = iter.next();
10054                if (pkgName.equals(item.packageName)) {
10055                    iter.remove();
10056                }
10057            }
10058
10059            // Add the package's KeySets to the global KeySetManagerService
10060            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10061            ksms.addScannedPackageLPw(pkg);
10062
10063            int N = pkg.providers.size();
10064            StringBuilder r = null;
10065            int i;
10066            for (i=0; i<N; i++) {
10067                PackageParser.Provider p = pkg.providers.get(i);
10068                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10069                        p.info.processName);
10070                mProviders.addProvider(p);
10071                p.syncable = p.info.isSyncable;
10072                if (p.info.authority != null) {
10073                    String names[] = p.info.authority.split(";");
10074                    p.info.authority = null;
10075                    for (int j = 0; j < names.length; j++) {
10076                        if (j == 1 && p.syncable) {
10077                            // We only want the first authority for a provider to possibly be
10078                            // syncable, so if we already added this provider using a different
10079                            // authority clear the syncable flag. We copy the provider before
10080                            // changing it because the mProviders object contains a reference
10081                            // to a provider that we don't want to change.
10082                            // Only do this for the second authority since the resulting provider
10083                            // object can be the same for all future authorities for this provider.
10084                            p = new PackageParser.Provider(p);
10085                            p.syncable = false;
10086                        }
10087                        if (!mProvidersByAuthority.containsKey(names[j])) {
10088                            mProvidersByAuthority.put(names[j], p);
10089                            if (p.info.authority == null) {
10090                                p.info.authority = names[j];
10091                            } else {
10092                                p.info.authority = p.info.authority + ";" + names[j];
10093                            }
10094                            if (DEBUG_PACKAGE_SCANNING) {
10095                                if (chatty)
10096                                    Log.d(TAG, "Registered content provider: " + names[j]
10097                                            + ", className = " + p.info.name + ", isSyncable = "
10098                                            + p.info.isSyncable);
10099                            }
10100                        } else {
10101                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10102                            Slog.w(TAG, "Skipping provider name " + names[j] +
10103                                    " (in package " + pkg.applicationInfo.packageName +
10104                                    "): name already used by "
10105                                    + ((other != null && other.getComponentName() != null)
10106                                            ? other.getComponentName().getPackageName() : "?"));
10107                        }
10108                    }
10109                }
10110                if (chatty) {
10111                    if (r == null) {
10112                        r = new StringBuilder(256);
10113                    } else {
10114                        r.append(' ');
10115                    }
10116                    r.append(p.info.name);
10117                }
10118            }
10119            if (r != null) {
10120                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10121            }
10122
10123            N = pkg.services.size();
10124            r = null;
10125            for (i=0; i<N; i++) {
10126                PackageParser.Service s = pkg.services.get(i);
10127                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10128                        s.info.processName);
10129                mServices.addService(s);
10130                if (chatty) {
10131                    if (r == null) {
10132                        r = new StringBuilder(256);
10133                    } else {
10134                        r.append(' ');
10135                    }
10136                    r.append(s.info.name);
10137                }
10138            }
10139            if (r != null) {
10140                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10141            }
10142
10143            N = pkg.receivers.size();
10144            r = null;
10145            for (i=0; i<N; i++) {
10146                PackageParser.Activity a = pkg.receivers.get(i);
10147                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10148                        a.info.processName);
10149                mReceivers.addActivity(a, "receiver");
10150                if (chatty) {
10151                    if (r == null) {
10152                        r = new StringBuilder(256);
10153                    } else {
10154                        r.append(' ');
10155                    }
10156                    r.append(a.info.name);
10157                }
10158            }
10159            if (r != null) {
10160                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10161            }
10162
10163            N = pkg.activities.size();
10164            r = null;
10165            for (i=0; i<N; i++) {
10166                PackageParser.Activity a = pkg.activities.get(i);
10167                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10168                        a.info.processName);
10169                mActivities.addActivity(a, "activity");
10170                if (chatty) {
10171                    if (r == null) {
10172                        r = new StringBuilder(256);
10173                    } else {
10174                        r.append(' ');
10175                    }
10176                    r.append(a.info.name);
10177                }
10178            }
10179            if (r != null) {
10180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10181            }
10182
10183            N = pkg.permissionGroups.size();
10184            r = null;
10185            for (i=0; i<N; i++) {
10186                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10187                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10188                final String curPackageName = cur == null ? null : cur.info.packageName;
10189                // Dont allow ephemeral apps to define new permission groups.
10190                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10191                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10192                            + pg.info.packageName
10193                            + " ignored: instant apps cannot define new permission groups.");
10194                    continue;
10195                }
10196                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10197                if (cur == null || isPackageUpdate) {
10198                    mPermissionGroups.put(pg.info.name, pg);
10199                    if (chatty) {
10200                        if (r == null) {
10201                            r = new StringBuilder(256);
10202                        } else {
10203                            r.append(' ');
10204                        }
10205                        if (isPackageUpdate) {
10206                            r.append("UPD:");
10207                        }
10208                        r.append(pg.info.name);
10209                    }
10210                } else {
10211                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10212                            + pg.info.packageName + " ignored: original from "
10213                            + cur.info.packageName);
10214                    if (chatty) {
10215                        if (r == null) {
10216                            r = new StringBuilder(256);
10217                        } else {
10218                            r.append(' ');
10219                        }
10220                        r.append("DUP:");
10221                        r.append(pg.info.name);
10222                    }
10223                }
10224            }
10225            if (r != null) {
10226                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10227            }
10228
10229            N = pkg.permissions.size();
10230            r = null;
10231            for (i=0; i<N; i++) {
10232                PackageParser.Permission p = pkg.permissions.get(i);
10233
10234                // Dont allow ephemeral apps to define new permissions.
10235                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10236                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10237                            + p.info.packageName
10238                            + " ignored: instant apps cannot define new permissions.");
10239                    continue;
10240                }
10241
10242                // Assume by default that we did not install this permission into the system.
10243                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10244
10245                // Now that permission groups have a special meaning, we ignore permission
10246                // groups for legacy apps to prevent unexpected behavior. In particular,
10247                // permissions for one app being granted to someone just becase they happen
10248                // to be in a group defined by another app (before this had no implications).
10249                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10250                    p.group = mPermissionGroups.get(p.info.group);
10251                    // Warn for a permission in an unknown group.
10252                    if (p.info.group != null && p.group == null) {
10253                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10254                                + p.info.packageName + " in an unknown group " + p.info.group);
10255                    }
10256                }
10257
10258                ArrayMap<String, BasePermission> permissionMap =
10259                        p.tree ? mSettings.mPermissionTrees
10260                                : mSettings.mPermissions;
10261                BasePermission bp = permissionMap.get(p.info.name);
10262
10263                // Allow system apps to redefine non-system permissions
10264                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10265                    final boolean currentOwnerIsSystem = (bp.perm != null
10266                            && isSystemApp(bp.perm.owner));
10267                    if (isSystemApp(p.owner)) {
10268                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10269                            // It's a built-in permission and no owner, take ownership now
10270                            bp.packageSetting = pkgSetting;
10271                            bp.perm = p;
10272                            bp.uid = pkg.applicationInfo.uid;
10273                            bp.sourcePackage = p.info.packageName;
10274                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10275                        } else if (!currentOwnerIsSystem) {
10276                            String msg = "New decl " + p.owner + " of permission  "
10277                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10278                            reportSettingsProblem(Log.WARN, msg);
10279                            bp = null;
10280                        }
10281                    }
10282                }
10283
10284                if (bp == null) {
10285                    bp = new BasePermission(p.info.name, p.info.packageName,
10286                            BasePermission.TYPE_NORMAL);
10287                    permissionMap.put(p.info.name, bp);
10288                }
10289
10290                if (bp.perm == null) {
10291                    if (bp.sourcePackage == null
10292                            || bp.sourcePackage.equals(p.info.packageName)) {
10293                        BasePermission tree = findPermissionTreeLP(p.info.name);
10294                        if (tree == null
10295                                || tree.sourcePackage.equals(p.info.packageName)) {
10296                            bp.packageSetting = pkgSetting;
10297                            bp.perm = p;
10298                            bp.uid = pkg.applicationInfo.uid;
10299                            bp.sourcePackage = p.info.packageName;
10300                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10301                            if (chatty) {
10302                                if (r == null) {
10303                                    r = new StringBuilder(256);
10304                                } else {
10305                                    r.append(' ');
10306                                }
10307                                r.append(p.info.name);
10308                            }
10309                        } else {
10310                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10311                                    + p.info.packageName + " ignored: base tree "
10312                                    + tree.name + " is from package "
10313                                    + tree.sourcePackage);
10314                        }
10315                    } else {
10316                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10317                                + p.info.packageName + " ignored: original from "
10318                                + bp.sourcePackage);
10319                    }
10320                } else if (chatty) {
10321                    if (r == null) {
10322                        r = new StringBuilder(256);
10323                    } else {
10324                        r.append(' ');
10325                    }
10326                    r.append("DUP:");
10327                    r.append(p.info.name);
10328                }
10329                if (bp.perm == p) {
10330                    bp.protectionLevel = p.info.protectionLevel;
10331                }
10332            }
10333
10334            if (r != null) {
10335                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10336            }
10337
10338            N = pkg.instrumentation.size();
10339            r = null;
10340            for (i=0; i<N; i++) {
10341                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10342                a.info.packageName = pkg.applicationInfo.packageName;
10343                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10344                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10345                a.info.splitNames = pkg.splitNames;
10346                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10347                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10348                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10349                a.info.dataDir = pkg.applicationInfo.dataDir;
10350                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10351                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10352                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10353                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10354                mInstrumentation.put(a.getComponentName(), a);
10355                if (chatty) {
10356                    if (r == null) {
10357                        r = new StringBuilder(256);
10358                    } else {
10359                        r.append(' ');
10360                    }
10361                    r.append(a.info.name);
10362                }
10363            }
10364            if (r != null) {
10365                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10366            }
10367
10368            if (pkg.protectedBroadcasts != null) {
10369                N = pkg.protectedBroadcasts.size();
10370                for (i=0; i<N; i++) {
10371                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10372                }
10373            }
10374        }
10375
10376        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10377    }
10378
10379    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10380            PackageParser.Package update, int[] userIds) {
10381        if (existing.applicationInfo == null || update.applicationInfo == null) {
10382            // This isn't due to an app installation.
10383            return;
10384        }
10385
10386        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10387        final File newCodePath = new File(update.applicationInfo.getCodePath());
10388
10389        // The codePath hasn't changed, so there's nothing for us to do.
10390        if (Objects.equals(oldCodePath, newCodePath)) {
10391            return;
10392        }
10393
10394        File canonicalNewCodePath;
10395        try {
10396            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10397        } catch (IOException e) {
10398            Slog.w(TAG, "Failed to get canonical path.", e);
10399            return;
10400        }
10401
10402        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10403        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10404        // that the last component of the path (i.e, the name) doesn't need canonicalization
10405        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10406        // but may change in the future. Hopefully this function won't exist at that point.
10407        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10408                oldCodePath.getName());
10409
10410        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10411        // with "@".
10412        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10413        if (!oldMarkerPrefix.endsWith("@")) {
10414            oldMarkerPrefix += "@";
10415        }
10416        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10417        if (!newMarkerPrefix.endsWith("@")) {
10418            newMarkerPrefix += "@";
10419        }
10420
10421        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10422        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10423        for (String updatedPath : updatedPaths) {
10424            String updatedPathName = new File(updatedPath).getName();
10425            markerSuffixes.add(updatedPathName.replace('/', '@'));
10426        }
10427
10428        for (int userId : userIds) {
10429            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10430
10431            for (String markerSuffix : markerSuffixes) {
10432                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10433                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10434                if (oldForeignUseMark.exists()) {
10435                    try {
10436                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10437                                newForeignUseMark.getAbsolutePath());
10438                    } catch (ErrnoException e) {
10439                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10440                        oldForeignUseMark.delete();
10441                    }
10442                }
10443            }
10444        }
10445    }
10446
10447    /**
10448     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10449     * is derived purely on the basis of the contents of {@code scanFile} and
10450     * {@code cpuAbiOverride}.
10451     *
10452     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10453     */
10454    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10455                                 String cpuAbiOverride, boolean extractLibs,
10456                                 File appLib32InstallDir)
10457            throws PackageManagerException {
10458        // Give ourselves some initial paths; we'll come back for another
10459        // pass once we've determined ABI below.
10460        setNativeLibraryPaths(pkg, appLib32InstallDir);
10461
10462        // We would never need to extract libs for forward-locked and external packages,
10463        // since the container service will do it for us. We shouldn't attempt to
10464        // extract libs from system app when it was not updated.
10465        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10466                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10467            extractLibs = false;
10468        }
10469
10470        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10471        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10472
10473        NativeLibraryHelper.Handle handle = null;
10474        try {
10475            handle = NativeLibraryHelper.Handle.create(pkg);
10476            // TODO(multiArch): This can be null for apps that didn't go through the
10477            // usual installation process. We can calculate it again, like we
10478            // do during install time.
10479            //
10480            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10481            // unnecessary.
10482            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10483
10484            // Null out the abis so that they can be recalculated.
10485            pkg.applicationInfo.primaryCpuAbi = null;
10486            pkg.applicationInfo.secondaryCpuAbi = null;
10487            if (isMultiArch(pkg.applicationInfo)) {
10488                // Warn if we've set an abiOverride for multi-lib packages..
10489                // By definition, we need to copy both 32 and 64 bit libraries for
10490                // such packages.
10491                if (pkg.cpuAbiOverride != null
10492                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10493                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10494                }
10495
10496                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10497                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10498                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10499                    if (extractLibs) {
10500                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10501                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10502                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10503                                useIsaSpecificSubdirs);
10504                    } else {
10505                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10506                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10507                    }
10508                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10509                }
10510
10511                maybeThrowExceptionForMultiArchCopy(
10512                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10513
10514                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10515                    if (extractLibs) {
10516                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10517                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10518                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10519                                useIsaSpecificSubdirs);
10520                    } else {
10521                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10522                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10523                    }
10524                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10525                }
10526
10527                maybeThrowExceptionForMultiArchCopy(
10528                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10529
10530                if (abi64 >= 0) {
10531                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10532                }
10533
10534                if (abi32 >= 0) {
10535                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10536                    if (abi64 >= 0) {
10537                        if (pkg.use32bitAbi) {
10538                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10539                            pkg.applicationInfo.primaryCpuAbi = abi;
10540                        } else {
10541                            pkg.applicationInfo.secondaryCpuAbi = abi;
10542                        }
10543                    } else {
10544                        pkg.applicationInfo.primaryCpuAbi = abi;
10545                    }
10546                }
10547
10548            } else {
10549                String[] abiList = (cpuAbiOverride != null) ?
10550                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10551
10552                // Enable gross and lame hacks for apps that are built with old
10553                // SDK tools. We must scan their APKs for renderscript bitcode and
10554                // not launch them if it's present. Don't bother checking on devices
10555                // that don't have 64 bit support.
10556                boolean needsRenderScriptOverride = false;
10557                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10558                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10559                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10560                    needsRenderScriptOverride = true;
10561                }
10562
10563                final int copyRet;
10564                if (extractLibs) {
10565                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10566                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10567                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10568                } else {
10569                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10570                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10571                }
10572                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10573
10574                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10575                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10576                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10577                }
10578
10579                if (copyRet >= 0) {
10580                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10581                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10582                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10583                } else if (needsRenderScriptOverride) {
10584                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10585                }
10586            }
10587        } catch (IOException ioe) {
10588            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10589        } finally {
10590            IoUtils.closeQuietly(handle);
10591        }
10592
10593        // Now that we've calculated the ABIs and determined if it's an internal app,
10594        // we will go ahead and populate the nativeLibraryPath.
10595        setNativeLibraryPaths(pkg, appLib32InstallDir);
10596    }
10597
10598    /**
10599     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10600     * i.e, so that all packages can be run inside a single process if required.
10601     *
10602     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10603     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10604     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10605     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10606     * updating a package that belongs to a shared user.
10607     *
10608     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10609     * adds unnecessary complexity.
10610     */
10611    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10612            PackageParser.Package scannedPackage) {
10613        String requiredInstructionSet = null;
10614        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10615            requiredInstructionSet = VMRuntime.getInstructionSet(
10616                     scannedPackage.applicationInfo.primaryCpuAbi);
10617        }
10618
10619        PackageSetting requirer = null;
10620        for (PackageSetting ps : packagesForUser) {
10621            // If packagesForUser contains scannedPackage, we skip it. This will happen
10622            // when scannedPackage is an update of an existing package. Without this check,
10623            // we will never be able to change the ABI of any package belonging to a shared
10624            // user, even if it's compatible with other packages.
10625            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10626                if (ps.primaryCpuAbiString == null) {
10627                    continue;
10628                }
10629
10630                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10631                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10632                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10633                    // this but there's not much we can do.
10634                    String errorMessage = "Instruction set mismatch, "
10635                            + ((requirer == null) ? "[caller]" : requirer)
10636                            + " requires " + requiredInstructionSet + " whereas " + ps
10637                            + " requires " + instructionSet;
10638                    Slog.w(TAG, errorMessage);
10639                }
10640
10641                if (requiredInstructionSet == null) {
10642                    requiredInstructionSet = instructionSet;
10643                    requirer = ps;
10644                }
10645            }
10646        }
10647
10648        if (requiredInstructionSet != null) {
10649            String adjustedAbi;
10650            if (requirer != null) {
10651                // requirer != null implies that either scannedPackage was null or that scannedPackage
10652                // did not require an ABI, in which case we have to adjust scannedPackage to match
10653                // the ABI of the set (which is the same as requirer's ABI)
10654                adjustedAbi = requirer.primaryCpuAbiString;
10655                if (scannedPackage != null) {
10656                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10657                }
10658            } else {
10659                // requirer == null implies that we're updating all ABIs in the set to
10660                // match scannedPackage.
10661                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10662            }
10663
10664            for (PackageSetting ps : packagesForUser) {
10665                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10666                    if (ps.primaryCpuAbiString != null) {
10667                        continue;
10668                    }
10669
10670                    ps.primaryCpuAbiString = adjustedAbi;
10671                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10672                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10673                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10674                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10675                                + " (requirer="
10676                                + (requirer == null ? "null" : requirer.pkg.packageName)
10677                                + ", scannedPackage="
10678                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10679                                + ")");
10680                        try {
10681                            mInstaller.rmdex(ps.codePathString,
10682                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10683                        } catch (InstallerException ignored) {
10684                        }
10685                    }
10686                }
10687            }
10688        }
10689    }
10690
10691    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10692        synchronized (mPackages) {
10693            mResolverReplaced = true;
10694            // Set up information for custom user intent resolution activity.
10695            mResolveActivity.applicationInfo = pkg.applicationInfo;
10696            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10697            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10698            mResolveActivity.processName = pkg.applicationInfo.packageName;
10699            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10700            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10701                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10702            mResolveActivity.theme = 0;
10703            mResolveActivity.exported = true;
10704            mResolveActivity.enabled = true;
10705            mResolveInfo.activityInfo = mResolveActivity;
10706            mResolveInfo.priority = 0;
10707            mResolveInfo.preferredOrder = 0;
10708            mResolveInfo.match = 0;
10709            mResolveComponentName = mCustomResolverComponentName;
10710            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10711                    mResolveComponentName);
10712        }
10713    }
10714
10715    private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) {
10716        if (installerComponent == null) {
10717            if (DEBUG_EPHEMERAL) {
10718                Slog.d(TAG, "Clear ephemeral installer activity");
10719            }
10720            mInstantAppInstallerActivity.applicationInfo = null;
10721            return;
10722        }
10723
10724        if (DEBUG_EPHEMERAL) {
10725            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10726        }
10727        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10728        // Set up information for ephemeral installer activity
10729        mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo;
10730        mInstantAppInstallerActivity.name = installerComponent.getClassName();
10731        mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName;
10732        mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName;
10733        mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10734        mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10735                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10736        mInstantAppInstallerActivity.theme = 0;
10737        mInstantAppInstallerActivity.exported = true;
10738        mInstantAppInstallerActivity.enabled = true;
10739        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10740        mInstantAppInstallerInfo.priority = 0;
10741        mInstantAppInstallerInfo.preferredOrder = 1;
10742        mInstantAppInstallerInfo.isDefault = true;
10743        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10744                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10745    }
10746
10747    private static String calculateBundledApkRoot(final String codePathString) {
10748        final File codePath = new File(codePathString);
10749        final File codeRoot;
10750        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10751            codeRoot = Environment.getRootDirectory();
10752        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10753            codeRoot = Environment.getOemDirectory();
10754        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10755            codeRoot = Environment.getVendorDirectory();
10756        } else {
10757            // Unrecognized code path; take its top real segment as the apk root:
10758            // e.g. /something/app/blah.apk => /something
10759            try {
10760                File f = codePath.getCanonicalFile();
10761                File parent = f.getParentFile();    // non-null because codePath is a file
10762                File tmp;
10763                while ((tmp = parent.getParentFile()) != null) {
10764                    f = parent;
10765                    parent = tmp;
10766                }
10767                codeRoot = f;
10768                Slog.w(TAG, "Unrecognized code path "
10769                        + codePath + " - using " + codeRoot);
10770            } catch (IOException e) {
10771                // Can't canonicalize the code path -- shenanigans?
10772                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10773                return Environment.getRootDirectory().getPath();
10774            }
10775        }
10776        return codeRoot.getPath();
10777    }
10778
10779    /**
10780     * Derive and set the location of native libraries for the given package,
10781     * which varies depending on where and how the package was installed.
10782     */
10783    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10784        final ApplicationInfo info = pkg.applicationInfo;
10785        final String codePath = pkg.codePath;
10786        final File codeFile = new File(codePath);
10787        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10788        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10789
10790        info.nativeLibraryRootDir = null;
10791        info.nativeLibraryRootRequiresIsa = false;
10792        info.nativeLibraryDir = null;
10793        info.secondaryNativeLibraryDir = null;
10794
10795        if (isApkFile(codeFile)) {
10796            // Monolithic install
10797            if (bundledApp) {
10798                // If "/system/lib64/apkname" exists, assume that is the per-package
10799                // native library directory to use; otherwise use "/system/lib/apkname".
10800                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10801                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10802                        getPrimaryInstructionSet(info));
10803
10804                // This is a bundled system app so choose the path based on the ABI.
10805                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10806                // is just the default path.
10807                final String apkName = deriveCodePathName(codePath);
10808                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10809                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10810                        apkName).getAbsolutePath();
10811
10812                if (info.secondaryCpuAbi != null) {
10813                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10814                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10815                            secondaryLibDir, apkName).getAbsolutePath();
10816                }
10817            } else if (asecApp) {
10818                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10819                        .getAbsolutePath();
10820            } else {
10821                final String apkName = deriveCodePathName(codePath);
10822                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10823                        .getAbsolutePath();
10824            }
10825
10826            info.nativeLibraryRootRequiresIsa = false;
10827            info.nativeLibraryDir = info.nativeLibraryRootDir;
10828        } else {
10829            // Cluster install
10830            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10831            info.nativeLibraryRootRequiresIsa = true;
10832
10833            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10834                    getPrimaryInstructionSet(info)).getAbsolutePath();
10835
10836            if (info.secondaryCpuAbi != null) {
10837                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10838                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10839            }
10840        }
10841    }
10842
10843    /**
10844     * Calculate the abis and roots for a bundled app. These can uniquely
10845     * be determined from the contents of the system partition, i.e whether
10846     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10847     * of this information, and instead assume that the system was built
10848     * sensibly.
10849     */
10850    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10851                                           PackageSetting pkgSetting) {
10852        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10853
10854        // If "/system/lib64/apkname" exists, assume that is the per-package
10855        // native library directory to use; otherwise use "/system/lib/apkname".
10856        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10857        setBundledAppAbi(pkg, apkRoot, apkName);
10858        // pkgSetting might be null during rescan following uninstall of updates
10859        // to a bundled app, so accommodate that possibility.  The settings in
10860        // that case will be established later from the parsed package.
10861        //
10862        // If the settings aren't null, sync them up with what we've just derived.
10863        // note that apkRoot isn't stored in the package settings.
10864        if (pkgSetting != null) {
10865            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10866            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10867        }
10868    }
10869
10870    /**
10871     * Deduces the ABI of a bundled app and sets the relevant fields on the
10872     * parsed pkg object.
10873     *
10874     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10875     *        under which system libraries are installed.
10876     * @param apkName the name of the installed package.
10877     */
10878    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10879        final File codeFile = new File(pkg.codePath);
10880
10881        final boolean has64BitLibs;
10882        final boolean has32BitLibs;
10883        if (isApkFile(codeFile)) {
10884            // Monolithic install
10885            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10886            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10887        } else {
10888            // Cluster install
10889            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10890            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10891                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10892                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10893                has64BitLibs = (new File(rootDir, isa)).exists();
10894            } else {
10895                has64BitLibs = false;
10896            }
10897            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10898                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10899                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10900                has32BitLibs = (new File(rootDir, isa)).exists();
10901            } else {
10902                has32BitLibs = false;
10903            }
10904        }
10905
10906        if (has64BitLibs && !has32BitLibs) {
10907            // The package has 64 bit libs, but not 32 bit libs. Its primary
10908            // ABI should be 64 bit. We can safely assume here that the bundled
10909            // native libraries correspond to the most preferred ABI in the list.
10910
10911            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10912            pkg.applicationInfo.secondaryCpuAbi = null;
10913        } else if (has32BitLibs && !has64BitLibs) {
10914            // The package has 32 bit libs but not 64 bit libs. Its primary
10915            // ABI should be 32 bit.
10916
10917            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10918            pkg.applicationInfo.secondaryCpuAbi = null;
10919        } else if (has32BitLibs && has64BitLibs) {
10920            // The application has both 64 and 32 bit bundled libraries. We check
10921            // here that the app declares multiArch support, and warn if it doesn't.
10922            //
10923            // We will be lenient here and record both ABIs. The primary will be the
10924            // ABI that's higher on the list, i.e, a device that's configured to prefer
10925            // 64 bit apps will see a 64 bit primary ABI,
10926
10927            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10928                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10929            }
10930
10931            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10932                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10933                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10934            } else {
10935                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10936                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10937            }
10938        } else {
10939            pkg.applicationInfo.primaryCpuAbi = null;
10940            pkg.applicationInfo.secondaryCpuAbi = null;
10941        }
10942    }
10943
10944    private void killApplication(String pkgName, int appId, String reason) {
10945        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10946    }
10947
10948    private void killApplication(String pkgName, int appId, int userId, String reason) {
10949        // Request the ActivityManager to kill the process(only for existing packages)
10950        // so that we do not end up in a confused state while the user is still using the older
10951        // version of the application while the new one gets installed.
10952        final long token = Binder.clearCallingIdentity();
10953        try {
10954            IActivityManager am = ActivityManager.getService();
10955            if (am != null) {
10956                try {
10957                    am.killApplication(pkgName, appId, userId, reason);
10958                } catch (RemoteException e) {
10959                }
10960            }
10961        } finally {
10962            Binder.restoreCallingIdentity(token);
10963        }
10964    }
10965
10966    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10967        // Remove the parent package setting
10968        PackageSetting ps = (PackageSetting) pkg.mExtras;
10969        if (ps != null) {
10970            removePackageLI(ps, chatty);
10971        }
10972        // Remove the child package setting
10973        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10974        for (int i = 0; i < childCount; i++) {
10975            PackageParser.Package childPkg = pkg.childPackages.get(i);
10976            ps = (PackageSetting) childPkg.mExtras;
10977            if (ps != null) {
10978                removePackageLI(ps, chatty);
10979            }
10980        }
10981    }
10982
10983    void removePackageLI(PackageSetting ps, boolean chatty) {
10984        if (DEBUG_INSTALL) {
10985            if (chatty)
10986                Log.d(TAG, "Removing package " + ps.name);
10987        }
10988
10989        // writer
10990        synchronized (mPackages) {
10991            mPackages.remove(ps.name);
10992            final PackageParser.Package pkg = ps.pkg;
10993            if (pkg != null) {
10994                cleanPackageDataStructuresLILPw(pkg, chatty);
10995            }
10996        }
10997    }
10998
10999    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11000        if (DEBUG_INSTALL) {
11001            if (chatty)
11002                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11003        }
11004
11005        // writer
11006        synchronized (mPackages) {
11007            // Remove the parent package
11008            mPackages.remove(pkg.applicationInfo.packageName);
11009            cleanPackageDataStructuresLILPw(pkg, chatty);
11010
11011            // Remove the child packages
11012            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11013            for (int i = 0; i < childCount; i++) {
11014                PackageParser.Package childPkg = pkg.childPackages.get(i);
11015                mPackages.remove(childPkg.applicationInfo.packageName);
11016                cleanPackageDataStructuresLILPw(childPkg, chatty);
11017            }
11018        }
11019    }
11020
11021    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11022        int N = pkg.providers.size();
11023        StringBuilder r = null;
11024        int i;
11025        for (i=0; i<N; i++) {
11026            PackageParser.Provider p = pkg.providers.get(i);
11027            mProviders.removeProvider(p);
11028            if (p.info.authority == null) {
11029
11030                /* There was another ContentProvider with this authority when
11031                 * this app was installed so this authority is null,
11032                 * Ignore it as we don't have to unregister the provider.
11033                 */
11034                continue;
11035            }
11036            String names[] = p.info.authority.split(";");
11037            for (int j = 0; j < names.length; j++) {
11038                if (mProvidersByAuthority.get(names[j]) == p) {
11039                    mProvidersByAuthority.remove(names[j]);
11040                    if (DEBUG_REMOVE) {
11041                        if (chatty)
11042                            Log.d(TAG, "Unregistered content provider: " + names[j]
11043                                    + ", className = " + p.info.name + ", isSyncable = "
11044                                    + p.info.isSyncable);
11045                    }
11046                }
11047            }
11048            if (DEBUG_REMOVE && chatty) {
11049                if (r == null) {
11050                    r = new StringBuilder(256);
11051                } else {
11052                    r.append(' ');
11053                }
11054                r.append(p.info.name);
11055            }
11056        }
11057        if (r != null) {
11058            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11059        }
11060
11061        N = pkg.services.size();
11062        r = null;
11063        for (i=0; i<N; i++) {
11064            PackageParser.Service s = pkg.services.get(i);
11065            mServices.removeService(s);
11066            if (chatty) {
11067                if (r == null) {
11068                    r = new StringBuilder(256);
11069                } else {
11070                    r.append(' ');
11071                }
11072                r.append(s.info.name);
11073            }
11074        }
11075        if (r != null) {
11076            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11077        }
11078
11079        N = pkg.receivers.size();
11080        r = null;
11081        for (i=0; i<N; i++) {
11082            PackageParser.Activity a = pkg.receivers.get(i);
11083            mReceivers.removeActivity(a, "receiver");
11084            if (DEBUG_REMOVE && chatty) {
11085                if (r == null) {
11086                    r = new StringBuilder(256);
11087                } else {
11088                    r.append(' ');
11089                }
11090                r.append(a.info.name);
11091            }
11092        }
11093        if (r != null) {
11094            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11095        }
11096
11097        N = pkg.activities.size();
11098        r = null;
11099        for (i=0; i<N; i++) {
11100            PackageParser.Activity a = pkg.activities.get(i);
11101            mActivities.removeActivity(a, "activity");
11102            if (DEBUG_REMOVE && chatty) {
11103                if (r == null) {
11104                    r = new StringBuilder(256);
11105                } else {
11106                    r.append(' ');
11107                }
11108                r.append(a.info.name);
11109            }
11110        }
11111        if (r != null) {
11112            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11113        }
11114
11115        N = pkg.permissions.size();
11116        r = null;
11117        for (i=0; i<N; i++) {
11118            PackageParser.Permission p = pkg.permissions.get(i);
11119            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11120            if (bp == null) {
11121                bp = mSettings.mPermissionTrees.get(p.info.name);
11122            }
11123            if (bp != null && bp.perm == p) {
11124                bp.perm = null;
11125                if (DEBUG_REMOVE && chatty) {
11126                    if (r == null) {
11127                        r = new StringBuilder(256);
11128                    } else {
11129                        r.append(' ');
11130                    }
11131                    r.append(p.info.name);
11132                }
11133            }
11134            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11135                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11136                if (appOpPkgs != null) {
11137                    appOpPkgs.remove(pkg.packageName);
11138                }
11139            }
11140        }
11141        if (r != null) {
11142            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11143        }
11144
11145        N = pkg.requestedPermissions.size();
11146        r = null;
11147        for (i=0; i<N; i++) {
11148            String perm = pkg.requestedPermissions.get(i);
11149            BasePermission bp = mSettings.mPermissions.get(perm);
11150            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11151                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11152                if (appOpPkgs != null) {
11153                    appOpPkgs.remove(pkg.packageName);
11154                    if (appOpPkgs.isEmpty()) {
11155                        mAppOpPermissionPackages.remove(perm);
11156                    }
11157                }
11158            }
11159        }
11160        if (r != null) {
11161            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11162        }
11163
11164        N = pkg.instrumentation.size();
11165        r = null;
11166        for (i=0; i<N; i++) {
11167            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11168            mInstrumentation.remove(a.getComponentName());
11169            if (DEBUG_REMOVE && chatty) {
11170                if (r == null) {
11171                    r = new StringBuilder(256);
11172                } else {
11173                    r.append(' ');
11174                }
11175                r.append(a.info.name);
11176            }
11177        }
11178        if (r != null) {
11179            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11180        }
11181
11182        r = null;
11183        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11184            // Only system apps can hold shared libraries.
11185            if (pkg.libraryNames != null) {
11186                for (i = 0; i < pkg.libraryNames.size(); i++) {
11187                    String name = pkg.libraryNames.get(i);
11188                    if (removeSharedLibraryLPw(name, 0)) {
11189                        if (DEBUG_REMOVE && chatty) {
11190                            if (r == null) {
11191                                r = new StringBuilder(256);
11192                            } else {
11193                                r.append(' ');
11194                            }
11195                            r.append(name);
11196                        }
11197                    }
11198                }
11199            }
11200        }
11201
11202        r = null;
11203
11204        // Any package can hold static shared libraries.
11205        if (pkg.staticSharedLibName != null) {
11206            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11207                if (DEBUG_REMOVE && chatty) {
11208                    if (r == null) {
11209                        r = new StringBuilder(256);
11210                    } else {
11211                        r.append(' ');
11212                    }
11213                    r.append(pkg.staticSharedLibName);
11214                }
11215            }
11216        }
11217
11218        if (r != null) {
11219            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11220        }
11221    }
11222
11223    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11224        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11225            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11226                return true;
11227            }
11228        }
11229        return false;
11230    }
11231
11232    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11233    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11234    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11235
11236    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11237        // Update the parent permissions
11238        updatePermissionsLPw(pkg.packageName, pkg, flags);
11239        // Update the child permissions
11240        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11241        for (int i = 0; i < childCount; i++) {
11242            PackageParser.Package childPkg = pkg.childPackages.get(i);
11243            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11244        }
11245    }
11246
11247    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11248            int flags) {
11249        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11250        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11251    }
11252
11253    private void updatePermissionsLPw(String changingPkg,
11254            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11255        // Make sure there are no dangling permission trees.
11256        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11257        while (it.hasNext()) {
11258            final BasePermission bp = it.next();
11259            if (bp.packageSetting == null) {
11260                // We may not yet have parsed the package, so just see if
11261                // we still know about its settings.
11262                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11263            }
11264            if (bp.packageSetting == null) {
11265                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11266                        + " from package " + bp.sourcePackage);
11267                it.remove();
11268            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11269                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11270                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11271                            + " from package " + bp.sourcePackage);
11272                    flags |= UPDATE_PERMISSIONS_ALL;
11273                    it.remove();
11274                }
11275            }
11276        }
11277
11278        // Make sure all dynamic permissions have been assigned to a package,
11279        // and make sure there are no dangling permissions.
11280        it = mSettings.mPermissions.values().iterator();
11281        while (it.hasNext()) {
11282            final BasePermission bp = it.next();
11283            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11284                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11285                        + bp.name + " pkg=" + bp.sourcePackage
11286                        + " info=" + bp.pendingInfo);
11287                if (bp.packageSetting == null && bp.pendingInfo != null) {
11288                    final BasePermission tree = findPermissionTreeLP(bp.name);
11289                    if (tree != null && tree.perm != null) {
11290                        bp.packageSetting = tree.packageSetting;
11291                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11292                                new PermissionInfo(bp.pendingInfo));
11293                        bp.perm.info.packageName = tree.perm.info.packageName;
11294                        bp.perm.info.name = bp.name;
11295                        bp.uid = tree.uid;
11296                    }
11297                }
11298            }
11299            if (bp.packageSetting == null) {
11300                // We may not yet have parsed the package, so just see if
11301                // we still know about its settings.
11302                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11303            }
11304            if (bp.packageSetting == null) {
11305                Slog.w(TAG, "Removing dangling permission: " + bp.name
11306                        + " from package " + bp.sourcePackage);
11307                it.remove();
11308            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11309                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11310                    Slog.i(TAG, "Removing old permission: " + bp.name
11311                            + " from package " + bp.sourcePackage);
11312                    flags |= UPDATE_PERMISSIONS_ALL;
11313                    it.remove();
11314                }
11315            }
11316        }
11317
11318        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11319        // Now update the permissions for all packages, in particular
11320        // replace the granted permissions of the system packages.
11321        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11322            for (PackageParser.Package pkg : mPackages.values()) {
11323                if (pkg != pkgInfo) {
11324                    // Only replace for packages on requested volume
11325                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11326                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11327                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11328                    grantPermissionsLPw(pkg, replace, changingPkg);
11329                }
11330            }
11331        }
11332
11333        if (pkgInfo != null) {
11334            // Only replace for packages on requested volume
11335            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11336            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11337                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11338            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11339        }
11340        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11341    }
11342
11343    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11344            String packageOfInterest) {
11345        // IMPORTANT: There are two types of permissions: install and runtime.
11346        // Install time permissions are granted when the app is installed to
11347        // all device users and users added in the future. Runtime permissions
11348        // are granted at runtime explicitly to specific users. Normal and signature
11349        // protected permissions are install time permissions. Dangerous permissions
11350        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11351        // otherwise they are runtime permissions. This function does not manage
11352        // runtime permissions except for the case an app targeting Lollipop MR1
11353        // being upgraded to target a newer SDK, in which case dangerous permissions
11354        // are transformed from install time to runtime ones.
11355
11356        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11357        if (ps == null) {
11358            return;
11359        }
11360
11361        PermissionsState permissionsState = ps.getPermissionsState();
11362        PermissionsState origPermissions = permissionsState;
11363
11364        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11365
11366        boolean runtimePermissionsRevoked = false;
11367        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11368
11369        boolean changedInstallPermission = false;
11370
11371        if (replace) {
11372            ps.installPermissionsFixed = false;
11373            if (!ps.isSharedUser()) {
11374                origPermissions = new PermissionsState(permissionsState);
11375                permissionsState.reset();
11376            } else {
11377                // We need to know only about runtime permission changes since the
11378                // calling code always writes the install permissions state but
11379                // the runtime ones are written only if changed. The only cases of
11380                // changed runtime permissions here are promotion of an install to
11381                // runtime and revocation of a runtime from a shared user.
11382                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11383                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11384                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11385                    runtimePermissionsRevoked = true;
11386                }
11387            }
11388        }
11389
11390        permissionsState.setGlobalGids(mGlobalGids);
11391
11392        final int N = pkg.requestedPermissions.size();
11393        for (int i=0; i<N; i++) {
11394            final String name = pkg.requestedPermissions.get(i);
11395            final BasePermission bp = mSettings.mPermissions.get(name);
11396
11397            if (DEBUG_INSTALL) {
11398                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11399            }
11400
11401            if (bp == null || bp.packageSetting == null) {
11402                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11403                    Slog.w(TAG, "Unknown permission " + name
11404                            + " in package " + pkg.packageName);
11405                }
11406                continue;
11407            }
11408
11409
11410            // Limit ephemeral apps to ephemeral allowed permissions.
11411            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11412                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11413                        + pkg.packageName);
11414                continue;
11415            }
11416
11417            final String perm = bp.name;
11418            boolean allowedSig = false;
11419            int grant = GRANT_DENIED;
11420
11421            // Keep track of app op permissions.
11422            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11423                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11424                if (pkgs == null) {
11425                    pkgs = new ArraySet<>();
11426                    mAppOpPermissionPackages.put(bp.name, pkgs);
11427                }
11428                pkgs.add(pkg.packageName);
11429            }
11430
11431            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11432            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11433                    >= Build.VERSION_CODES.M;
11434            switch (level) {
11435                case PermissionInfo.PROTECTION_NORMAL: {
11436                    // For all apps normal permissions are install time ones.
11437                    grant = GRANT_INSTALL;
11438                } break;
11439
11440                case PermissionInfo.PROTECTION_DANGEROUS: {
11441                    // If a permission review is required for legacy apps we represent
11442                    // their permissions as always granted runtime ones since we need
11443                    // to keep the review required permission flag per user while an
11444                    // install permission's state is shared across all users.
11445                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11446                        // For legacy apps dangerous permissions are install time ones.
11447                        grant = GRANT_INSTALL;
11448                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11449                        // For legacy apps that became modern, install becomes runtime.
11450                        grant = GRANT_UPGRADE;
11451                    } else if (mPromoteSystemApps
11452                            && isSystemApp(ps)
11453                            && mExistingSystemPackages.contains(ps.name)) {
11454                        // For legacy system apps, install becomes runtime.
11455                        // We cannot check hasInstallPermission() for system apps since those
11456                        // permissions were granted implicitly and not persisted pre-M.
11457                        grant = GRANT_UPGRADE;
11458                    } else {
11459                        // For modern apps keep runtime permissions unchanged.
11460                        grant = GRANT_RUNTIME;
11461                    }
11462                } break;
11463
11464                case PermissionInfo.PROTECTION_SIGNATURE: {
11465                    // For all apps signature permissions are install time ones.
11466                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11467                    if (allowedSig) {
11468                        grant = GRANT_INSTALL;
11469                    }
11470                } break;
11471            }
11472
11473            if (DEBUG_INSTALL) {
11474                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11475            }
11476
11477            if (grant != GRANT_DENIED) {
11478                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11479                    // If this is an existing, non-system package, then
11480                    // we can't add any new permissions to it.
11481                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11482                        // Except...  if this is a permission that was added
11483                        // to the platform (note: need to only do this when
11484                        // updating the platform).
11485                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11486                            grant = GRANT_DENIED;
11487                        }
11488                    }
11489                }
11490
11491                switch (grant) {
11492                    case GRANT_INSTALL: {
11493                        // Revoke this as runtime permission to handle the case of
11494                        // a runtime permission being downgraded to an install one.
11495                        // Also in permission review mode we keep dangerous permissions
11496                        // for legacy apps
11497                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11498                            if (origPermissions.getRuntimePermissionState(
11499                                    bp.name, userId) != null) {
11500                                // Revoke the runtime permission and clear the flags.
11501                                origPermissions.revokeRuntimePermission(bp, userId);
11502                                origPermissions.updatePermissionFlags(bp, userId,
11503                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11504                                // If we revoked a permission permission, we have to write.
11505                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11506                                        changedRuntimePermissionUserIds, userId);
11507                            }
11508                        }
11509                        // Grant an install permission.
11510                        if (permissionsState.grantInstallPermission(bp) !=
11511                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11512                            changedInstallPermission = true;
11513                        }
11514                    } break;
11515
11516                    case GRANT_RUNTIME: {
11517                        // Grant previously granted runtime permissions.
11518                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11519                            PermissionState permissionState = origPermissions
11520                                    .getRuntimePermissionState(bp.name, userId);
11521                            int flags = permissionState != null
11522                                    ? permissionState.getFlags() : 0;
11523                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11524                                // Don't propagate the permission in a permission review mode if
11525                                // the former was revoked, i.e. marked to not propagate on upgrade.
11526                                // Note that in a permission review mode install permissions are
11527                                // represented as constantly granted runtime ones since we need to
11528                                // keep a per user state associated with the permission. Also the
11529                                // revoke on upgrade flag is no longer applicable and is reset.
11530                                final boolean revokeOnUpgrade = (flags & PackageManager
11531                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11532                                if (revokeOnUpgrade) {
11533                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11534                                    // Since we changed the flags, we have to write.
11535                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11536                                            changedRuntimePermissionUserIds, userId);
11537                                }
11538                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11539                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11540                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11541                                        // If we cannot put the permission as it was,
11542                                        // we have to write.
11543                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11544                                                changedRuntimePermissionUserIds, userId);
11545                                    }
11546                                }
11547
11548                                // If the app supports runtime permissions no need for a review.
11549                                if (mPermissionReviewRequired
11550                                        && appSupportsRuntimePermissions
11551                                        && (flags & PackageManager
11552                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11553                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11554                                    // Since we changed the flags, we have to write.
11555                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11556                                            changedRuntimePermissionUserIds, userId);
11557                                }
11558                            } else if (mPermissionReviewRequired
11559                                    && !appSupportsRuntimePermissions) {
11560                                // For legacy apps that need a permission review, every new
11561                                // runtime permission is granted but it is pending a review.
11562                                // We also need to review only platform defined runtime
11563                                // permissions as these are the only ones the platform knows
11564                                // how to disable the API to simulate revocation as legacy
11565                                // apps don't expect to run with revoked permissions.
11566                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11567                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11568                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11569                                        // We changed the flags, hence have to write.
11570                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11571                                                changedRuntimePermissionUserIds, userId);
11572                                    }
11573                                }
11574                                if (permissionsState.grantRuntimePermission(bp, userId)
11575                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11576                                    // We changed the permission, hence have to write.
11577                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11578                                            changedRuntimePermissionUserIds, userId);
11579                                }
11580                            }
11581                            // Propagate the permission flags.
11582                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11583                        }
11584                    } break;
11585
11586                    case GRANT_UPGRADE: {
11587                        // Grant runtime permissions for a previously held install permission.
11588                        PermissionState permissionState = origPermissions
11589                                .getInstallPermissionState(bp.name);
11590                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11591
11592                        if (origPermissions.revokeInstallPermission(bp)
11593                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11594                            // We will be transferring the permission flags, so clear them.
11595                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11596                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11597                            changedInstallPermission = true;
11598                        }
11599
11600                        // If the permission is not to be promoted to runtime we ignore it and
11601                        // also its other flags as they are not applicable to install permissions.
11602                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11603                            for (int userId : currentUserIds) {
11604                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11605                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11606                                    // Transfer the permission flags.
11607                                    permissionsState.updatePermissionFlags(bp, userId,
11608                                            flags, flags);
11609                                    // If we granted the permission, we have to write.
11610                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11611                                            changedRuntimePermissionUserIds, userId);
11612                                }
11613                            }
11614                        }
11615                    } break;
11616
11617                    default: {
11618                        if (packageOfInterest == null
11619                                || packageOfInterest.equals(pkg.packageName)) {
11620                            Slog.w(TAG, "Not granting permission " + perm
11621                                    + " to package " + pkg.packageName
11622                                    + " because it was previously installed without");
11623                        }
11624                    } break;
11625                }
11626            } else {
11627                if (permissionsState.revokeInstallPermission(bp) !=
11628                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11629                    // Also drop the permission flags.
11630                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11631                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11632                    changedInstallPermission = true;
11633                    Slog.i(TAG, "Un-granting permission " + perm
11634                            + " from package " + pkg.packageName
11635                            + " (protectionLevel=" + bp.protectionLevel
11636                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11637                            + ")");
11638                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11639                    // Don't print warning for app op permissions, since it is fine for them
11640                    // not to be granted, there is a UI for the user to decide.
11641                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11642                        Slog.w(TAG, "Not granting permission " + perm
11643                                + " to package " + pkg.packageName
11644                                + " (protectionLevel=" + bp.protectionLevel
11645                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11646                                + ")");
11647                    }
11648                }
11649            }
11650        }
11651
11652        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11653                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11654            // This is the first that we have heard about this package, so the
11655            // permissions we have now selected are fixed until explicitly
11656            // changed.
11657            ps.installPermissionsFixed = true;
11658        }
11659
11660        // Persist the runtime permissions state for users with changes. If permissions
11661        // were revoked because no app in the shared user declares them we have to
11662        // write synchronously to avoid losing runtime permissions state.
11663        for (int userId : changedRuntimePermissionUserIds) {
11664            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11665        }
11666    }
11667
11668    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11669        boolean allowed = false;
11670        final int NP = PackageParser.NEW_PERMISSIONS.length;
11671        for (int ip=0; ip<NP; ip++) {
11672            final PackageParser.NewPermissionInfo npi
11673                    = PackageParser.NEW_PERMISSIONS[ip];
11674            if (npi.name.equals(perm)
11675                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11676                allowed = true;
11677                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11678                        + pkg.packageName);
11679                break;
11680            }
11681        }
11682        return allowed;
11683    }
11684
11685    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11686            BasePermission bp, PermissionsState origPermissions) {
11687        boolean privilegedPermission = (bp.protectionLevel
11688                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11689        boolean privappPermissionsDisable =
11690                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11691        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11692        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11693        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11694                && !platformPackage && platformPermission) {
11695            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11696                    .getPrivAppPermissions(pkg.packageName);
11697            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11698            if (!whitelisted) {
11699                Slog.w(TAG, "Privileged permission " + perm + " for package "
11700                        + pkg.packageName + " - not in privapp-permissions whitelist");
11701                if (!mSystemReady) {
11702                    if (mPrivappPermissionsViolations == null) {
11703                        mPrivappPermissionsViolations = new ArraySet<>();
11704                    }
11705                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11706                }
11707                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11708                    return false;
11709                }
11710            }
11711        }
11712        boolean allowed = (compareSignatures(
11713                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11714                        == PackageManager.SIGNATURE_MATCH)
11715                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11716                        == PackageManager.SIGNATURE_MATCH);
11717        if (!allowed && privilegedPermission) {
11718            if (isSystemApp(pkg)) {
11719                // For updated system applications, a system permission
11720                // is granted only if it had been defined by the original application.
11721                if (pkg.isUpdatedSystemApp()) {
11722                    final PackageSetting sysPs = mSettings
11723                            .getDisabledSystemPkgLPr(pkg.packageName);
11724                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11725                        // If the original was granted this permission, we take
11726                        // that grant decision as read and propagate it to the
11727                        // update.
11728                        if (sysPs.isPrivileged()) {
11729                            allowed = true;
11730                        }
11731                    } else {
11732                        // The system apk may have been updated with an older
11733                        // version of the one on the data partition, but which
11734                        // granted a new system permission that it didn't have
11735                        // before.  In this case we do want to allow the app to
11736                        // now get the new permission if the ancestral apk is
11737                        // privileged to get it.
11738                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11739                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11740                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11741                                    allowed = true;
11742                                    break;
11743                                }
11744                            }
11745                        }
11746                        // Also if a privileged parent package on the system image or any of
11747                        // its children requested a privileged permission, the updated child
11748                        // packages can also get the permission.
11749                        if (pkg.parentPackage != null) {
11750                            final PackageSetting disabledSysParentPs = mSettings
11751                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11752                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11753                                    && disabledSysParentPs.isPrivileged()) {
11754                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11755                                    allowed = true;
11756                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11757                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11758                                    for (int i = 0; i < count; i++) {
11759                                        PackageParser.Package disabledSysChildPkg =
11760                                                disabledSysParentPs.pkg.childPackages.get(i);
11761                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11762                                                perm)) {
11763                                            allowed = true;
11764                                            break;
11765                                        }
11766                                    }
11767                                }
11768                            }
11769                        }
11770                    }
11771                } else {
11772                    allowed = isPrivilegedApp(pkg);
11773                }
11774            }
11775        }
11776        if (!allowed) {
11777            if (!allowed && (bp.protectionLevel
11778                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11779                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11780                // If this was a previously normal/dangerous permission that got moved
11781                // to a system permission as part of the runtime permission redesign, then
11782                // we still want to blindly grant it to old apps.
11783                allowed = true;
11784            }
11785            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11786                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11787                // If this permission is to be granted to the system installer and
11788                // this app is an installer, then it gets the permission.
11789                allowed = true;
11790            }
11791            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11792                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11793                // If this permission is to be granted to the system verifier and
11794                // this app is a verifier, then it gets the permission.
11795                allowed = true;
11796            }
11797            if (!allowed && (bp.protectionLevel
11798                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11799                    && isSystemApp(pkg)) {
11800                // Any pre-installed system app is allowed to get this permission.
11801                allowed = true;
11802            }
11803            if (!allowed && (bp.protectionLevel
11804                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11805                // For development permissions, a development permission
11806                // is granted only if it was already granted.
11807                allowed = origPermissions.hasInstallPermission(perm);
11808            }
11809            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11810                    && pkg.packageName.equals(mSetupWizardPackage)) {
11811                // If this permission is to be granted to the system setup wizard and
11812                // this app is a setup wizard, then it gets the permission.
11813                allowed = true;
11814            }
11815        }
11816        return allowed;
11817    }
11818
11819    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11820        final int permCount = pkg.requestedPermissions.size();
11821        for (int j = 0; j < permCount; j++) {
11822            String requestedPermission = pkg.requestedPermissions.get(j);
11823            if (permission.equals(requestedPermission)) {
11824                return true;
11825            }
11826        }
11827        return false;
11828    }
11829
11830    final class ActivityIntentResolver
11831            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11832        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11833                boolean defaultOnly, int userId) {
11834            if (!sUserManager.exists(userId)) return null;
11835            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11836            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11837        }
11838
11839        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11840                int userId) {
11841            if (!sUserManager.exists(userId)) return null;
11842            mFlags = flags;
11843            return super.queryIntent(intent, resolvedType,
11844                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11845                    userId);
11846        }
11847
11848        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11849                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11850            if (!sUserManager.exists(userId)) return null;
11851            if (packageActivities == null) {
11852                return null;
11853            }
11854            mFlags = flags;
11855            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11856            final int N = packageActivities.size();
11857            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11858                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11859
11860            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11861            for (int i = 0; i < N; ++i) {
11862                intentFilters = packageActivities.get(i).intents;
11863                if (intentFilters != null && intentFilters.size() > 0) {
11864                    PackageParser.ActivityIntentInfo[] array =
11865                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11866                    intentFilters.toArray(array);
11867                    listCut.add(array);
11868                }
11869            }
11870            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11871        }
11872
11873        /**
11874         * Finds a privileged activity that matches the specified activity names.
11875         */
11876        private PackageParser.Activity findMatchingActivity(
11877                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11878            for (PackageParser.Activity sysActivity : activityList) {
11879                if (sysActivity.info.name.equals(activityInfo.name)) {
11880                    return sysActivity;
11881                }
11882                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11883                    return sysActivity;
11884                }
11885                if (sysActivity.info.targetActivity != null) {
11886                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11887                        return sysActivity;
11888                    }
11889                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11890                        return sysActivity;
11891                    }
11892                }
11893            }
11894            return null;
11895        }
11896
11897        public class IterGenerator<E> {
11898            public Iterator<E> generate(ActivityIntentInfo info) {
11899                return null;
11900            }
11901        }
11902
11903        public class ActionIterGenerator extends IterGenerator<String> {
11904            @Override
11905            public Iterator<String> generate(ActivityIntentInfo info) {
11906                return info.actionsIterator();
11907            }
11908        }
11909
11910        public class CategoriesIterGenerator extends IterGenerator<String> {
11911            @Override
11912            public Iterator<String> generate(ActivityIntentInfo info) {
11913                return info.categoriesIterator();
11914            }
11915        }
11916
11917        public class SchemesIterGenerator extends IterGenerator<String> {
11918            @Override
11919            public Iterator<String> generate(ActivityIntentInfo info) {
11920                return info.schemesIterator();
11921            }
11922        }
11923
11924        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11925            @Override
11926            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11927                return info.authoritiesIterator();
11928            }
11929        }
11930
11931        /**
11932         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11933         * MODIFIED. Do not pass in a list that should not be changed.
11934         */
11935        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11936                IterGenerator<T> generator, Iterator<T> searchIterator) {
11937            // loop through the set of actions; every one must be found in the intent filter
11938            while (searchIterator.hasNext()) {
11939                // we must have at least one filter in the list to consider a match
11940                if (intentList.size() == 0) {
11941                    break;
11942                }
11943
11944                final T searchAction = searchIterator.next();
11945
11946                // loop through the set of intent filters
11947                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11948                while (intentIter.hasNext()) {
11949                    final ActivityIntentInfo intentInfo = intentIter.next();
11950                    boolean selectionFound = false;
11951
11952                    // loop through the intent filter's selection criteria; at least one
11953                    // of them must match the searched criteria
11954                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11955                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11956                        final T intentSelection = intentSelectionIter.next();
11957                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11958                            selectionFound = true;
11959                            break;
11960                        }
11961                    }
11962
11963                    // the selection criteria wasn't found in this filter's set; this filter
11964                    // is not a potential match
11965                    if (!selectionFound) {
11966                        intentIter.remove();
11967                    }
11968                }
11969            }
11970        }
11971
11972        private boolean isProtectedAction(ActivityIntentInfo filter) {
11973            final Iterator<String> actionsIter = filter.actionsIterator();
11974            while (actionsIter != null && actionsIter.hasNext()) {
11975                final String filterAction = actionsIter.next();
11976                if (PROTECTED_ACTIONS.contains(filterAction)) {
11977                    return true;
11978                }
11979            }
11980            return false;
11981        }
11982
11983        /**
11984         * Adjusts the priority of the given intent filter according to policy.
11985         * <p>
11986         * <ul>
11987         * <li>The priority for non privileged applications is capped to '0'</li>
11988         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11989         * <li>The priority for unbundled updates to privileged applications is capped to the
11990         *      priority defined on the system partition</li>
11991         * </ul>
11992         * <p>
11993         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11994         * allowed to obtain any priority on any action.
11995         */
11996        private void adjustPriority(
11997                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11998            // nothing to do; priority is fine as-is
11999            if (intent.getPriority() <= 0) {
12000                return;
12001            }
12002
12003            final ActivityInfo activityInfo = intent.activity.info;
12004            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12005
12006            final boolean privilegedApp =
12007                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12008            if (!privilegedApp) {
12009                // non-privileged applications can never define a priority >0
12010                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12011                        + " package: " + applicationInfo.packageName
12012                        + " activity: " + intent.activity.className
12013                        + " origPrio: " + intent.getPriority());
12014                intent.setPriority(0);
12015                return;
12016            }
12017
12018            if (systemActivities == null) {
12019                // the system package is not disabled; we're parsing the system partition
12020                if (isProtectedAction(intent)) {
12021                    if (mDeferProtectedFilters) {
12022                        // We can't deal with these just yet. No component should ever obtain a
12023                        // >0 priority for a protected actions, with ONE exception -- the setup
12024                        // wizard. The setup wizard, however, cannot be known until we're able to
12025                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12026                        // until all intent filters have been processed. Chicken, meet egg.
12027                        // Let the filter temporarily have a high priority and rectify the
12028                        // priorities after all system packages have been scanned.
12029                        mProtectedFilters.add(intent);
12030                        if (DEBUG_FILTERS) {
12031                            Slog.i(TAG, "Protected action; save for later;"
12032                                    + " package: " + applicationInfo.packageName
12033                                    + " activity: " + intent.activity.className
12034                                    + " origPrio: " + intent.getPriority());
12035                        }
12036                        return;
12037                    } else {
12038                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12039                            Slog.i(TAG, "No setup wizard;"
12040                                + " All protected intents capped to priority 0");
12041                        }
12042                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12043                            if (DEBUG_FILTERS) {
12044                                Slog.i(TAG, "Found setup wizard;"
12045                                    + " allow priority " + intent.getPriority() + ";"
12046                                    + " package: " + intent.activity.info.packageName
12047                                    + " activity: " + intent.activity.className
12048                                    + " priority: " + intent.getPriority());
12049                            }
12050                            // setup wizard gets whatever it wants
12051                            return;
12052                        }
12053                        Slog.w(TAG, "Protected action; cap priority to 0;"
12054                                + " package: " + intent.activity.info.packageName
12055                                + " activity: " + intent.activity.className
12056                                + " origPrio: " + intent.getPriority());
12057                        intent.setPriority(0);
12058                        return;
12059                    }
12060                }
12061                // privileged apps on the system image get whatever priority they request
12062                return;
12063            }
12064
12065            // privileged app unbundled update ... try to find the same activity
12066            final PackageParser.Activity foundActivity =
12067                    findMatchingActivity(systemActivities, activityInfo);
12068            if (foundActivity == null) {
12069                // this is a new activity; it cannot obtain >0 priority
12070                if (DEBUG_FILTERS) {
12071                    Slog.i(TAG, "New activity; cap priority to 0;"
12072                            + " package: " + applicationInfo.packageName
12073                            + " activity: " + intent.activity.className
12074                            + " origPrio: " + intent.getPriority());
12075                }
12076                intent.setPriority(0);
12077                return;
12078            }
12079
12080            // found activity, now check for filter equivalence
12081
12082            // a shallow copy is enough; we modify the list, not its contents
12083            final List<ActivityIntentInfo> intentListCopy =
12084                    new ArrayList<>(foundActivity.intents);
12085            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12086
12087            // find matching action subsets
12088            final Iterator<String> actionsIterator = intent.actionsIterator();
12089            if (actionsIterator != null) {
12090                getIntentListSubset(
12091                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12092                if (intentListCopy.size() == 0) {
12093                    // no more intents to match; we're not equivalent
12094                    if (DEBUG_FILTERS) {
12095                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12096                                + " package: " + applicationInfo.packageName
12097                                + " activity: " + intent.activity.className
12098                                + " origPrio: " + intent.getPriority());
12099                    }
12100                    intent.setPriority(0);
12101                    return;
12102                }
12103            }
12104
12105            // find matching category subsets
12106            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12107            if (categoriesIterator != null) {
12108                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12109                        categoriesIterator);
12110                if (intentListCopy.size() == 0) {
12111                    // no more intents to match; we're not equivalent
12112                    if (DEBUG_FILTERS) {
12113                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12114                                + " package: " + applicationInfo.packageName
12115                                + " activity: " + intent.activity.className
12116                                + " origPrio: " + intent.getPriority());
12117                    }
12118                    intent.setPriority(0);
12119                    return;
12120                }
12121            }
12122
12123            // find matching schemes subsets
12124            final Iterator<String> schemesIterator = intent.schemesIterator();
12125            if (schemesIterator != null) {
12126                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12127                        schemesIterator);
12128                if (intentListCopy.size() == 0) {
12129                    // no more intents to match; we're not equivalent
12130                    if (DEBUG_FILTERS) {
12131                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12132                                + " package: " + applicationInfo.packageName
12133                                + " activity: " + intent.activity.className
12134                                + " origPrio: " + intent.getPriority());
12135                    }
12136                    intent.setPriority(0);
12137                    return;
12138                }
12139            }
12140
12141            // find matching authorities subsets
12142            final Iterator<IntentFilter.AuthorityEntry>
12143                    authoritiesIterator = intent.authoritiesIterator();
12144            if (authoritiesIterator != null) {
12145                getIntentListSubset(intentListCopy,
12146                        new AuthoritiesIterGenerator(),
12147                        authoritiesIterator);
12148                if (intentListCopy.size() == 0) {
12149                    // no more intents to match; we're not equivalent
12150                    if (DEBUG_FILTERS) {
12151                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12152                                + " package: " + applicationInfo.packageName
12153                                + " activity: " + intent.activity.className
12154                                + " origPrio: " + intent.getPriority());
12155                    }
12156                    intent.setPriority(0);
12157                    return;
12158                }
12159            }
12160
12161            // we found matching filter(s); app gets the max priority of all intents
12162            int cappedPriority = 0;
12163            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12164                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12165            }
12166            if (intent.getPriority() > cappedPriority) {
12167                if (DEBUG_FILTERS) {
12168                    Slog.i(TAG, "Found matching filter(s);"
12169                            + " cap priority to " + cappedPriority + ";"
12170                            + " package: " + applicationInfo.packageName
12171                            + " activity: " + intent.activity.className
12172                            + " origPrio: " + intent.getPriority());
12173                }
12174                intent.setPriority(cappedPriority);
12175                return;
12176            }
12177            // all this for nothing; the requested priority was <= what was on the system
12178        }
12179
12180        public final void addActivity(PackageParser.Activity a, String type) {
12181            mActivities.put(a.getComponentName(), a);
12182            if (DEBUG_SHOW_INFO)
12183                Log.v(
12184                TAG, "  " + type + " " +
12185                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12186            if (DEBUG_SHOW_INFO)
12187                Log.v(TAG, "    Class=" + a.info.name);
12188            final int NI = a.intents.size();
12189            for (int j=0; j<NI; j++) {
12190                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12191                if ("activity".equals(type)) {
12192                    final PackageSetting ps =
12193                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12194                    final List<PackageParser.Activity> systemActivities =
12195                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12196                    adjustPriority(systemActivities, intent);
12197                }
12198                if (DEBUG_SHOW_INFO) {
12199                    Log.v(TAG, "    IntentFilter:");
12200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12201                }
12202                if (!intent.debugCheck()) {
12203                    Log.w(TAG, "==> For Activity " + a.info.name);
12204                }
12205                addFilter(intent);
12206            }
12207        }
12208
12209        public final void removeActivity(PackageParser.Activity a, String type) {
12210            mActivities.remove(a.getComponentName());
12211            if (DEBUG_SHOW_INFO) {
12212                Log.v(TAG, "  " + type + " "
12213                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12214                                : a.info.name) + ":");
12215                Log.v(TAG, "    Class=" + a.info.name);
12216            }
12217            final int NI = a.intents.size();
12218            for (int j=0; j<NI; j++) {
12219                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12220                if (DEBUG_SHOW_INFO) {
12221                    Log.v(TAG, "    IntentFilter:");
12222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12223                }
12224                removeFilter(intent);
12225            }
12226        }
12227
12228        @Override
12229        protected boolean allowFilterResult(
12230                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12231            ActivityInfo filterAi = filter.activity.info;
12232            for (int i=dest.size()-1; i>=0; i--) {
12233                ActivityInfo destAi = dest.get(i).activityInfo;
12234                if (destAi.name == filterAi.name
12235                        && destAi.packageName == filterAi.packageName) {
12236                    return false;
12237                }
12238            }
12239            return true;
12240        }
12241
12242        @Override
12243        protected ActivityIntentInfo[] newArray(int size) {
12244            return new ActivityIntentInfo[size];
12245        }
12246
12247        @Override
12248        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12249            if (!sUserManager.exists(userId)) return true;
12250            PackageParser.Package p = filter.activity.owner;
12251            if (p != null) {
12252                PackageSetting ps = (PackageSetting)p.mExtras;
12253                if (ps != null) {
12254                    // System apps are never considered stopped for purposes of
12255                    // filtering, because there may be no way for the user to
12256                    // actually re-launch them.
12257                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12258                            && ps.getStopped(userId);
12259                }
12260            }
12261            return false;
12262        }
12263
12264        @Override
12265        protected boolean isPackageForFilter(String packageName,
12266                PackageParser.ActivityIntentInfo info) {
12267            return packageName.equals(info.activity.owner.packageName);
12268        }
12269
12270        @Override
12271        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12272                int match, int userId) {
12273            if (!sUserManager.exists(userId)) return null;
12274            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12275                return null;
12276            }
12277            final PackageParser.Activity activity = info.activity;
12278            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12279            if (ps == null) {
12280                return null;
12281            }
12282            final PackageUserState userState = ps.readUserState(userId);
12283            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12284                    userState, userId);
12285            if (ai == null) {
12286                return null;
12287            }
12288            final boolean matchVisibleToInstantApp =
12289                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12290            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12291            // throw out filters that aren't visible to ephemeral apps
12292            if (matchVisibleToInstantApp
12293                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12294                return null;
12295            }
12296            // throw out ephemeral filters if we're not explicitly requesting them
12297            if (!isInstantApp && userState.instantApp) {
12298                return null;
12299            }
12300            final ResolveInfo res = new ResolveInfo();
12301            res.activityInfo = ai;
12302            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12303                res.filter = info;
12304            }
12305            if (info != null) {
12306                res.handleAllWebDataURI = info.handleAllWebDataURI();
12307            }
12308            res.priority = info.getPriority();
12309            res.preferredOrder = activity.owner.mPreferredOrder;
12310            //System.out.println("Result: " + res.activityInfo.className +
12311            //                   " = " + res.priority);
12312            res.match = match;
12313            res.isDefault = info.hasDefault;
12314            res.labelRes = info.labelRes;
12315            res.nonLocalizedLabel = info.nonLocalizedLabel;
12316            if (userNeedsBadging(userId)) {
12317                res.noResourceId = true;
12318            } else {
12319                res.icon = info.icon;
12320            }
12321            res.iconResourceId = info.icon;
12322            res.system = res.activityInfo.applicationInfo.isSystemApp();
12323            return res;
12324        }
12325
12326        @Override
12327        protected void sortResults(List<ResolveInfo> results) {
12328            Collections.sort(results, mResolvePrioritySorter);
12329        }
12330
12331        @Override
12332        protected void dumpFilter(PrintWriter out, String prefix,
12333                PackageParser.ActivityIntentInfo filter) {
12334            out.print(prefix); out.print(
12335                    Integer.toHexString(System.identityHashCode(filter.activity)));
12336                    out.print(' ');
12337                    filter.activity.printComponentShortName(out);
12338                    out.print(" filter ");
12339                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12340        }
12341
12342        @Override
12343        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12344            return filter.activity;
12345        }
12346
12347        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12348            PackageParser.Activity activity = (PackageParser.Activity)label;
12349            out.print(prefix); out.print(
12350                    Integer.toHexString(System.identityHashCode(activity)));
12351                    out.print(' ');
12352                    activity.printComponentShortName(out);
12353            if (count > 1) {
12354                out.print(" ("); out.print(count); out.print(" filters)");
12355            }
12356            out.println();
12357        }
12358
12359        // Keys are String (activity class name), values are Activity.
12360        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12361                = new ArrayMap<ComponentName, PackageParser.Activity>();
12362        private int mFlags;
12363    }
12364
12365    private final class ServiceIntentResolver
12366            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12367        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12368                boolean defaultOnly, int userId) {
12369            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12370            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12371        }
12372
12373        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12374                int userId) {
12375            if (!sUserManager.exists(userId)) return null;
12376            mFlags = flags;
12377            return super.queryIntent(intent, resolvedType,
12378                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12379                    userId);
12380        }
12381
12382        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12383                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12384            if (!sUserManager.exists(userId)) return null;
12385            if (packageServices == null) {
12386                return null;
12387            }
12388            mFlags = flags;
12389            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12390            final int N = packageServices.size();
12391            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12392                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12393
12394            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12395            for (int i = 0; i < N; ++i) {
12396                intentFilters = packageServices.get(i).intents;
12397                if (intentFilters != null && intentFilters.size() > 0) {
12398                    PackageParser.ServiceIntentInfo[] array =
12399                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12400                    intentFilters.toArray(array);
12401                    listCut.add(array);
12402                }
12403            }
12404            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12405        }
12406
12407        public final void addService(PackageParser.Service s) {
12408            mServices.put(s.getComponentName(), s);
12409            if (DEBUG_SHOW_INFO) {
12410                Log.v(TAG, "  "
12411                        + (s.info.nonLocalizedLabel != null
12412                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12413                Log.v(TAG, "    Class=" + s.info.name);
12414            }
12415            final int NI = s.intents.size();
12416            int j;
12417            for (j=0; j<NI; j++) {
12418                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12419                if (DEBUG_SHOW_INFO) {
12420                    Log.v(TAG, "    IntentFilter:");
12421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12422                }
12423                if (!intent.debugCheck()) {
12424                    Log.w(TAG, "==> For Service " + s.info.name);
12425                }
12426                addFilter(intent);
12427            }
12428        }
12429
12430        public final void removeService(PackageParser.Service s) {
12431            mServices.remove(s.getComponentName());
12432            if (DEBUG_SHOW_INFO) {
12433                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12434                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12435                Log.v(TAG, "    Class=" + s.info.name);
12436            }
12437            final int NI = s.intents.size();
12438            int j;
12439            for (j=0; j<NI; j++) {
12440                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12441                if (DEBUG_SHOW_INFO) {
12442                    Log.v(TAG, "    IntentFilter:");
12443                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12444                }
12445                removeFilter(intent);
12446            }
12447        }
12448
12449        @Override
12450        protected boolean allowFilterResult(
12451                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12452            ServiceInfo filterSi = filter.service.info;
12453            for (int i=dest.size()-1; i>=0; i--) {
12454                ServiceInfo destAi = dest.get(i).serviceInfo;
12455                if (destAi.name == filterSi.name
12456                        && destAi.packageName == filterSi.packageName) {
12457                    return false;
12458                }
12459            }
12460            return true;
12461        }
12462
12463        @Override
12464        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12465            return new PackageParser.ServiceIntentInfo[size];
12466        }
12467
12468        @Override
12469        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12470            if (!sUserManager.exists(userId)) return true;
12471            PackageParser.Package p = filter.service.owner;
12472            if (p != null) {
12473                PackageSetting ps = (PackageSetting)p.mExtras;
12474                if (ps != null) {
12475                    // System apps are never considered stopped for purposes of
12476                    // filtering, because there may be no way for the user to
12477                    // actually re-launch them.
12478                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12479                            && ps.getStopped(userId);
12480                }
12481            }
12482            return false;
12483        }
12484
12485        @Override
12486        protected boolean isPackageForFilter(String packageName,
12487                PackageParser.ServiceIntentInfo info) {
12488            return packageName.equals(info.service.owner.packageName);
12489        }
12490
12491        @Override
12492        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12493                int match, int userId) {
12494            if (!sUserManager.exists(userId)) return null;
12495            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12496            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12497                return null;
12498            }
12499            final PackageParser.Service service = info.service;
12500            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12501            if (ps == null) {
12502                return null;
12503            }
12504            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12505                    ps.readUserState(userId), userId);
12506            if (si == null) {
12507                return null;
12508            }
12509            final ResolveInfo res = new ResolveInfo();
12510            res.serviceInfo = si;
12511            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12512                res.filter = filter;
12513            }
12514            res.priority = info.getPriority();
12515            res.preferredOrder = service.owner.mPreferredOrder;
12516            res.match = match;
12517            res.isDefault = info.hasDefault;
12518            res.labelRes = info.labelRes;
12519            res.nonLocalizedLabel = info.nonLocalizedLabel;
12520            res.icon = info.icon;
12521            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12522            return res;
12523        }
12524
12525        @Override
12526        protected void sortResults(List<ResolveInfo> results) {
12527            Collections.sort(results, mResolvePrioritySorter);
12528        }
12529
12530        @Override
12531        protected void dumpFilter(PrintWriter out, String prefix,
12532                PackageParser.ServiceIntentInfo filter) {
12533            out.print(prefix); out.print(
12534                    Integer.toHexString(System.identityHashCode(filter.service)));
12535                    out.print(' ');
12536                    filter.service.printComponentShortName(out);
12537                    out.print(" filter ");
12538                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12539        }
12540
12541        @Override
12542        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12543            return filter.service;
12544        }
12545
12546        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12547            PackageParser.Service service = (PackageParser.Service)label;
12548            out.print(prefix); out.print(
12549                    Integer.toHexString(System.identityHashCode(service)));
12550                    out.print(' ');
12551                    service.printComponentShortName(out);
12552            if (count > 1) {
12553                out.print(" ("); out.print(count); out.print(" filters)");
12554            }
12555            out.println();
12556        }
12557
12558//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12559//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12560//            final List<ResolveInfo> retList = Lists.newArrayList();
12561//            while (i.hasNext()) {
12562//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12563//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12564//                    retList.add(resolveInfo);
12565//                }
12566//            }
12567//            return retList;
12568//        }
12569
12570        // Keys are String (activity class name), values are Activity.
12571        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12572                = new ArrayMap<ComponentName, PackageParser.Service>();
12573        private int mFlags;
12574    }
12575
12576    private final class ProviderIntentResolver
12577            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12578        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12579                boolean defaultOnly, int userId) {
12580            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12581            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12582        }
12583
12584        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12585                int userId) {
12586            if (!sUserManager.exists(userId))
12587                return null;
12588            mFlags = flags;
12589            return super.queryIntent(intent, resolvedType,
12590                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12591                    userId);
12592        }
12593
12594        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12595                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12596            if (!sUserManager.exists(userId))
12597                return null;
12598            if (packageProviders == null) {
12599                return null;
12600            }
12601            mFlags = flags;
12602            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12603            final int N = packageProviders.size();
12604            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12605                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12606
12607            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12608            for (int i = 0; i < N; ++i) {
12609                intentFilters = packageProviders.get(i).intents;
12610                if (intentFilters != null && intentFilters.size() > 0) {
12611                    PackageParser.ProviderIntentInfo[] array =
12612                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12613                    intentFilters.toArray(array);
12614                    listCut.add(array);
12615                }
12616            }
12617            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12618        }
12619
12620        public final void addProvider(PackageParser.Provider p) {
12621            if (mProviders.containsKey(p.getComponentName())) {
12622                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12623                return;
12624            }
12625
12626            mProviders.put(p.getComponentName(), p);
12627            if (DEBUG_SHOW_INFO) {
12628                Log.v(TAG, "  "
12629                        + (p.info.nonLocalizedLabel != null
12630                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12631                Log.v(TAG, "    Class=" + p.info.name);
12632            }
12633            final int NI = p.intents.size();
12634            int j;
12635            for (j = 0; j < NI; j++) {
12636                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12637                if (DEBUG_SHOW_INFO) {
12638                    Log.v(TAG, "    IntentFilter:");
12639                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12640                }
12641                if (!intent.debugCheck()) {
12642                    Log.w(TAG, "==> For Provider " + p.info.name);
12643                }
12644                addFilter(intent);
12645            }
12646        }
12647
12648        public final void removeProvider(PackageParser.Provider p) {
12649            mProviders.remove(p.getComponentName());
12650            if (DEBUG_SHOW_INFO) {
12651                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12652                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12653                Log.v(TAG, "    Class=" + p.info.name);
12654            }
12655            final int NI = p.intents.size();
12656            int j;
12657            for (j = 0; j < NI; j++) {
12658                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12659                if (DEBUG_SHOW_INFO) {
12660                    Log.v(TAG, "    IntentFilter:");
12661                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12662                }
12663                removeFilter(intent);
12664            }
12665        }
12666
12667        @Override
12668        protected boolean allowFilterResult(
12669                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12670            ProviderInfo filterPi = filter.provider.info;
12671            for (int i = dest.size() - 1; i >= 0; i--) {
12672                ProviderInfo destPi = dest.get(i).providerInfo;
12673                if (destPi.name == filterPi.name
12674                        && destPi.packageName == filterPi.packageName) {
12675                    return false;
12676                }
12677            }
12678            return true;
12679        }
12680
12681        @Override
12682        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12683            return new PackageParser.ProviderIntentInfo[size];
12684        }
12685
12686        @Override
12687        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12688            if (!sUserManager.exists(userId))
12689                return true;
12690            PackageParser.Package p = filter.provider.owner;
12691            if (p != null) {
12692                PackageSetting ps = (PackageSetting) p.mExtras;
12693                if (ps != null) {
12694                    // System apps are never considered stopped for purposes of
12695                    // filtering, because there may be no way for the user to
12696                    // actually re-launch them.
12697                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12698                            && ps.getStopped(userId);
12699                }
12700            }
12701            return false;
12702        }
12703
12704        @Override
12705        protected boolean isPackageForFilter(String packageName,
12706                PackageParser.ProviderIntentInfo info) {
12707            return packageName.equals(info.provider.owner.packageName);
12708        }
12709
12710        @Override
12711        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12712                int match, int userId) {
12713            if (!sUserManager.exists(userId))
12714                return null;
12715            final PackageParser.ProviderIntentInfo info = filter;
12716            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12717                return null;
12718            }
12719            final PackageParser.Provider provider = info.provider;
12720            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12721            if (ps == null) {
12722                return null;
12723            }
12724            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12725                    ps.readUserState(userId), userId);
12726            if (pi == null) {
12727                return null;
12728            }
12729            final ResolveInfo res = new ResolveInfo();
12730            res.providerInfo = pi;
12731            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12732                res.filter = filter;
12733            }
12734            res.priority = info.getPriority();
12735            res.preferredOrder = provider.owner.mPreferredOrder;
12736            res.match = match;
12737            res.isDefault = info.hasDefault;
12738            res.labelRes = info.labelRes;
12739            res.nonLocalizedLabel = info.nonLocalizedLabel;
12740            res.icon = info.icon;
12741            res.system = res.providerInfo.applicationInfo.isSystemApp();
12742            return res;
12743        }
12744
12745        @Override
12746        protected void sortResults(List<ResolveInfo> results) {
12747            Collections.sort(results, mResolvePrioritySorter);
12748        }
12749
12750        @Override
12751        protected void dumpFilter(PrintWriter out, String prefix,
12752                PackageParser.ProviderIntentInfo filter) {
12753            out.print(prefix);
12754            out.print(
12755                    Integer.toHexString(System.identityHashCode(filter.provider)));
12756            out.print(' ');
12757            filter.provider.printComponentShortName(out);
12758            out.print(" filter ");
12759            out.println(Integer.toHexString(System.identityHashCode(filter)));
12760        }
12761
12762        @Override
12763        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12764            return filter.provider;
12765        }
12766
12767        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12768            PackageParser.Provider provider = (PackageParser.Provider)label;
12769            out.print(prefix); out.print(
12770                    Integer.toHexString(System.identityHashCode(provider)));
12771                    out.print(' ');
12772                    provider.printComponentShortName(out);
12773            if (count > 1) {
12774                out.print(" ("); out.print(count); out.print(" filters)");
12775            }
12776            out.println();
12777        }
12778
12779        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12780                = new ArrayMap<ComponentName, PackageParser.Provider>();
12781        private int mFlags;
12782    }
12783
12784    static final class EphemeralIntentResolver
12785            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12786        /**
12787         * The result that has the highest defined order. Ordering applies on a
12788         * per-package basis. Mapping is from package name to Pair of order and
12789         * EphemeralResolveInfo.
12790         * <p>
12791         * NOTE: This is implemented as a field variable for convenience and efficiency.
12792         * By having a field variable, we're able to track filter ordering as soon as
12793         * a non-zero order is defined. Otherwise, multiple loops across the result set
12794         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12795         * this needs to be contained entirely within {@link #filterResults()}.
12796         */
12797        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12798
12799        @Override
12800        protected AuxiliaryResolveInfo[] newArray(int size) {
12801            return new AuxiliaryResolveInfo[size];
12802        }
12803
12804        @Override
12805        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12806            return true;
12807        }
12808
12809        @Override
12810        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12811                int userId) {
12812            if (!sUserManager.exists(userId)) {
12813                return null;
12814            }
12815            final String packageName = responseObj.resolveInfo.getPackageName();
12816            final Integer order = responseObj.getOrder();
12817            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12818                    mOrderResult.get(packageName);
12819            // ordering is enabled and this item's order isn't high enough
12820            if (lastOrderResult != null && lastOrderResult.first >= order) {
12821                return null;
12822            }
12823            final EphemeralResolveInfo res = responseObj.resolveInfo;
12824            if (order > 0) {
12825                // non-zero order, enable ordering
12826                mOrderResult.put(packageName, new Pair<>(order, res));
12827            }
12828            return responseObj;
12829        }
12830
12831        @Override
12832        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12833            // only do work if ordering is enabled [most of the time it won't be]
12834            if (mOrderResult.size() == 0) {
12835                return;
12836            }
12837            int resultSize = results.size();
12838            for (int i = 0; i < resultSize; i++) {
12839                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12840                final String packageName = info.getPackageName();
12841                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12842                if (savedInfo == null) {
12843                    // package doesn't having ordering
12844                    continue;
12845                }
12846                if (savedInfo.second == info) {
12847                    // circled back to the highest ordered item; remove from order list
12848                    mOrderResult.remove(savedInfo);
12849                    if (mOrderResult.size() == 0) {
12850                        // no more ordered items
12851                        break;
12852                    }
12853                    continue;
12854                }
12855                // item has a worse order, remove it from the result list
12856                results.remove(i);
12857                resultSize--;
12858                i--;
12859            }
12860        }
12861    }
12862
12863    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12864            new Comparator<ResolveInfo>() {
12865        public int compare(ResolveInfo r1, ResolveInfo r2) {
12866            int v1 = r1.priority;
12867            int v2 = r2.priority;
12868            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12869            if (v1 != v2) {
12870                return (v1 > v2) ? -1 : 1;
12871            }
12872            v1 = r1.preferredOrder;
12873            v2 = r2.preferredOrder;
12874            if (v1 != v2) {
12875                return (v1 > v2) ? -1 : 1;
12876            }
12877            if (r1.isDefault != r2.isDefault) {
12878                return r1.isDefault ? -1 : 1;
12879            }
12880            v1 = r1.match;
12881            v2 = r2.match;
12882            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12883            if (v1 != v2) {
12884                return (v1 > v2) ? -1 : 1;
12885            }
12886            if (r1.system != r2.system) {
12887                return r1.system ? -1 : 1;
12888            }
12889            if (r1.activityInfo != null) {
12890                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12891            }
12892            if (r1.serviceInfo != null) {
12893                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12894            }
12895            if (r1.providerInfo != null) {
12896                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12897            }
12898            return 0;
12899        }
12900    };
12901
12902    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12903            new Comparator<ProviderInfo>() {
12904        public int compare(ProviderInfo p1, ProviderInfo p2) {
12905            final int v1 = p1.initOrder;
12906            final int v2 = p2.initOrder;
12907            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12908        }
12909    };
12910
12911    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12912            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12913            final int[] userIds) {
12914        mHandler.post(new Runnable() {
12915            @Override
12916            public void run() {
12917                try {
12918                    final IActivityManager am = ActivityManager.getService();
12919                    if (am == null) return;
12920                    final int[] resolvedUserIds;
12921                    if (userIds == null) {
12922                        resolvedUserIds = am.getRunningUserIds();
12923                    } else {
12924                        resolvedUserIds = userIds;
12925                    }
12926                    for (int id : resolvedUserIds) {
12927                        final Intent intent = new Intent(action,
12928                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12929                        if (extras != null) {
12930                            intent.putExtras(extras);
12931                        }
12932                        if (targetPkg != null) {
12933                            intent.setPackage(targetPkg);
12934                        }
12935                        // Modify the UID when posting to other users
12936                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12937                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12938                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12939                            intent.putExtra(Intent.EXTRA_UID, uid);
12940                        }
12941                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12942                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12943                        if (DEBUG_BROADCASTS) {
12944                            RuntimeException here = new RuntimeException("here");
12945                            here.fillInStackTrace();
12946                            Slog.d(TAG, "Sending to user " + id + ": "
12947                                    + intent.toShortString(false, true, false, false)
12948                                    + " " + intent.getExtras(), here);
12949                        }
12950                        am.broadcastIntent(null, intent, null, finishedReceiver,
12951                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12952                                null, finishedReceiver != null, false, id);
12953                    }
12954                } catch (RemoteException ex) {
12955                }
12956            }
12957        });
12958    }
12959
12960    /**
12961     * Check if the external storage media is available. This is true if there
12962     * is a mounted external storage medium or if the external storage is
12963     * emulated.
12964     */
12965    private boolean isExternalMediaAvailable() {
12966        return mMediaMounted || Environment.isExternalStorageEmulated();
12967    }
12968
12969    @Override
12970    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12971        // writer
12972        synchronized (mPackages) {
12973            if (!isExternalMediaAvailable()) {
12974                // If the external storage is no longer mounted at this point,
12975                // the caller may not have been able to delete all of this
12976                // packages files and can not delete any more.  Bail.
12977                return null;
12978            }
12979            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12980            if (lastPackage != null) {
12981                pkgs.remove(lastPackage);
12982            }
12983            if (pkgs.size() > 0) {
12984                return pkgs.get(0);
12985            }
12986        }
12987        return null;
12988    }
12989
12990    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12991        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12992                userId, andCode ? 1 : 0, packageName);
12993        if (mSystemReady) {
12994            msg.sendToTarget();
12995        } else {
12996            if (mPostSystemReadyMessages == null) {
12997                mPostSystemReadyMessages = new ArrayList<>();
12998            }
12999            mPostSystemReadyMessages.add(msg);
13000        }
13001    }
13002
13003    void startCleaningPackages() {
13004        // reader
13005        if (!isExternalMediaAvailable()) {
13006            return;
13007        }
13008        synchronized (mPackages) {
13009            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13010                return;
13011            }
13012        }
13013        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13014        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13015        IActivityManager am = ActivityManager.getService();
13016        if (am != null) {
13017            try {
13018                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
13019                        UserHandle.USER_SYSTEM);
13020            } catch (RemoteException e) {
13021            }
13022        }
13023    }
13024
13025    @Override
13026    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13027            int installFlags, String installerPackageName, int userId) {
13028        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13029
13030        final int callingUid = Binder.getCallingUid();
13031        enforceCrossUserPermission(callingUid, userId,
13032                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13033
13034        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13035            try {
13036                if (observer != null) {
13037                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13038                }
13039            } catch (RemoteException re) {
13040            }
13041            return;
13042        }
13043
13044        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13045            installFlags |= PackageManager.INSTALL_FROM_ADB;
13046
13047        } else {
13048            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13049            // about installerPackageName.
13050
13051            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13052            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13053        }
13054
13055        UserHandle user;
13056        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13057            user = UserHandle.ALL;
13058        } else {
13059            user = new UserHandle(userId);
13060        }
13061
13062        // Only system components can circumvent runtime permissions when installing.
13063        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13064                && mContext.checkCallingOrSelfPermission(Manifest.permission
13065                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13066            throw new SecurityException("You need the "
13067                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13068                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13069        }
13070
13071        final File originFile = new File(originPath);
13072        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13073
13074        final Message msg = mHandler.obtainMessage(INIT_COPY);
13075        final VerificationInfo verificationInfo = new VerificationInfo(
13076                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13077        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13078                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13079                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13080                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13081        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13082        msg.obj = params;
13083
13084        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13085                System.identityHashCode(msg.obj));
13086        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13087                System.identityHashCode(msg.obj));
13088
13089        mHandler.sendMessage(msg);
13090    }
13091
13092
13093    /**
13094     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13095     * it is acting on behalf on an enterprise or the user).
13096     *
13097     * Note that the ordering of the conditionals in this method is important. The checks we perform
13098     * are as follows, in this order:
13099     *
13100     * 1) If the install is being performed by a system app, we can trust the app to have set the
13101     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13102     *    what it is.
13103     * 2) If the install is being performed by a device or profile owner app, the install reason
13104     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13105     *    set the install reason correctly. If the app targets an older SDK version where install
13106     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13107     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13108     * 3) In all other cases, the install is being performed by a regular app that is neither part
13109     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13110     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13111     *    set to enterprise policy and if so, change it to unknown instead.
13112     */
13113    private int fixUpInstallReason(String installerPackageName, int installerUid,
13114            int installReason) {
13115        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13116                == PERMISSION_GRANTED) {
13117            // If the install is being performed by a system app, we trust that app to have set the
13118            // install reason correctly.
13119            return installReason;
13120        }
13121
13122        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13123            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13124        if (dpm != null) {
13125            ComponentName owner = null;
13126            try {
13127                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13128                if (owner == null) {
13129                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13130                }
13131            } catch (RemoteException e) {
13132            }
13133            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13134                // If the install is being performed by a device or profile owner, the install
13135                // reason should be enterprise policy.
13136                return PackageManager.INSTALL_REASON_POLICY;
13137            }
13138        }
13139
13140        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13141            // If the install is being performed by a regular app (i.e. neither system app nor
13142            // device or profile owner), we have no reason to believe that the app is acting on
13143            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13144            // change it to unknown instead.
13145            return PackageManager.INSTALL_REASON_UNKNOWN;
13146        }
13147
13148        // If the install is being performed by a regular app and the install reason was set to any
13149        // value but enterprise policy, leave the install reason unchanged.
13150        return installReason;
13151    }
13152
13153    void installStage(String packageName, File stagedDir, String stagedCid,
13154            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13155            String installerPackageName, int installerUid, UserHandle user,
13156            Certificate[][] certificates) {
13157        if (DEBUG_EPHEMERAL) {
13158            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13159                Slog.d(TAG, "Ephemeral install of " + packageName);
13160            }
13161        }
13162        final VerificationInfo verificationInfo = new VerificationInfo(
13163                sessionParams.originatingUri, sessionParams.referrerUri,
13164                sessionParams.originatingUid, installerUid);
13165
13166        final OriginInfo origin;
13167        if (stagedDir != null) {
13168            origin = OriginInfo.fromStagedFile(stagedDir);
13169        } else {
13170            origin = OriginInfo.fromStagedContainer(stagedCid);
13171        }
13172
13173        final Message msg = mHandler.obtainMessage(INIT_COPY);
13174        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13175                sessionParams.installReason);
13176        final InstallParams params = new InstallParams(origin, null, observer,
13177                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13178                verificationInfo, user, sessionParams.abiOverride,
13179                sessionParams.grantedRuntimePermissions, certificates, installReason);
13180        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13181        msg.obj = params;
13182
13183        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13184                System.identityHashCode(msg.obj));
13185        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13186                System.identityHashCode(msg.obj));
13187
13188        mHandler.sendMessage(msg);
13189    }
13190
13191    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13192            int userId) {
13193        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13194        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13195    }
13196
13197    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13198            int appId, int... userIds) {
13199        if (ArrayUtils.isEmpty(userIds)) {
13200            return;
13201        }
13202        Bundle extras = new Bundle(1);
13203        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13204        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13205
13206        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13207                packageName, extras, 0, null, null, userIds);
13208        if (isSystem) {
13209            mHandler.post(() -> {
13210                        for (int userId : userIds) {
13211                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13212                        }
13213                    }
13214            );
13215        }
13216    }
13217
13218    /**
13219     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13220     * automatically without needing an explicit launch.
13221     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13222     */
13223    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13224        // If user is not running, the app didn't miss any broadcast
13225        if (!mUserManagerInternal.isUserRunning(userId)) {
13226            return;
13227        }
13228        final IActivityManager am = ActivityManager.getService();
13229        try {
13230            // Deliver LOCKED_BOOT_COMPLETED first
13231            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13232                    .setPackage(packageName);
13233            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13234            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13235                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13236
13237            // Deliver BOOT_COMPLETED only if user is unlocked
13238            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13239                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13240                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13241                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13242            }
13243        } catch (RemoteException e) {
13244            throw e.rethrowFromSystemServer();
13245        }
13246    }
13247
13248    @Override
13249    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13250            int userId) {
13251        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13252        PackageSetting pkgSetting;
13253        final int uid = Binder.getCallingUid();
13254        enforceCrossUserPermission(uid, userId,
13255                true /* requireFullPermission */, true /* checkShell */,
13256                "setApplicationHiddenSetting for user " + userId);
13257
13258        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13259            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13260            return false;
13261        }
13262
13263        long callingId = Binder.clearCallingIdentity();
13264        try {
13265            boolean sendAdded = false;
13266            boolean sendRemoved = false;
13267            // writer
13268            synchronized (mPackages) {
13269                pkgSetting = mSettings.mPackages.get(packageName);
13270                if (pkgSetting == null) {
13271                    return false;
13272                }
13273                // Do not allow "android" is being disabled
13274                if ("android".equals(packageName)) {
13275                    Slog.w(TAG, "Cannot hide package: android");
13276                    return false;
13277                }
13278                // Cannot hide static shared libs as they are considered
13279                // a part of the using app (emulating static linking). Also
13280                // static libs are installed always on internal storage.
13281                PackageParser.Package pkg = mPackages.get(packageName);
13282                if (pkg != null && pkg.staticSharedLibName != null) {
13283                    Slog.w(TAG, "Cannot hide package: " + packageName
13284                            + " providing static shared library: "
13285                            + pkg.staticSharedLibName);
13286                    return false;
13287                }
13288                // Only allow protected packages to hide themselves.
13289                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13290                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13291                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13292                    return false;
13293                }
13294
13295                if (pkgSetting.getHidden(userId) != hidden) {
13296                    pkgSetting.setHidden(hidden, userId);
13297                    mSettings.writePackageRestrictionsLPr(userId);
13298                    if (hidden) {
13299                        sendRemoved = true;
13300                    } else {
13301                        sendAdded = true;
13302                    }
13303                }
13304            }
13305            if (sendAdded) {
13306                sendPackageAddedForUser(packageName, pkgSetting, userId);
13307                return true;
13308            }
13309            if (sendRemoved) {
13310                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13311                        "hiding pkg");
13312                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13313                return true;
13314            }
13315        } finally {
13316            Binder.restoreCallingIdentity(callingId);
13317        }
13318        return false;
13319    }
13320
13321    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13322            int userId) {
13323        final PackageRemovedInfo info = new PackageRemovedInfo();
13324        info.removedPackage = packageName;
13325        info.removedUsers = new int[] {userId};
13326        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13327        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13328    }
13329
13330    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13331        if (pkgList.length > 0) {
13332            Bundle extras = new Bundle(1);
13333            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13334
13335            sendPackageBroadcast(
13336                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13337                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13338                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13339                    new int[] {userId});
13340        }
13341    }
13342
13343    /**
13344     * Returns true if application is not found or there was an error. Otherwise it returns
13345     * the hidden state of the package for the given user.
13346     */
13347    @Override
13348    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13351                true /* requireFullPermission */, false /* checkShell */,
13352                "getApplicationHidden for user " + userId);
13353        PackageSetting pkgSetting;
13354        long callingId = Binder.clearCallingIdentity();
13355        try {
13356            // writer
13357            synchronized (mPackages) {
13358                pkgSetting = mSettings.mPackages.get(packageName);
13359                if (pkgSetting == null) {
13360                    return true;
13361                }
13362                return pkgSetting.getHidden(userId);
13363            }
13364        } finally {
13365            Binder.restoreCallingIdentity(callingId);
13366        }
13367    }
13368
13369    /**
13370     * @hide
13371     */
13372    @Override
13373    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13374            int installReason) {
13375        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13376                null);
13377        PackageSetting pkgSetting;
13378        final int uid = Binder.getCallingUid();
13379        enforceCrossUserPermission(uid, userId,
13380                true /* requireFullPermission */, true /* checkShell */,
13381                "installExistingPackage for user " + userId);
13382        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13383            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13384        }
13385
13386        long callingId = Binder.clearCallingIdentity();
13387        try {
13388            boolean installed = false;
13389            final boolean instantApp =
13390                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13391            final boolean fullApp =
13392                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13393
13394            // writer
13395            synchronized (mPackages) {
13396                pkgSetting = mSettings.mPackages.get(packageName);
13397                if (pkgSetting == null) {
13398                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13399                }
13400                if (!pkgSetting.getInstalled(userId)) {
13401                    pkgSetting.setInstalled(true, userId);
13402                    pkgSetting.setHidden(false, userId);
13403                    pkgSetting.setInstallReason(installReason, userId);
13404                    mSettings.writePackageRestrictionsLPr(userId);
13405                    mSettings.writeKernelMappingLPr(pkgSetting);
13406                    installed = true;
13407                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13408                    // upgrade app from instant to full; we don't allow app downgrade
13409                    installed = true;
13410                }
13411                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13412            }
13413
13414            if (installed) {
13415                if (pkgSetting.pkg != null) {
13416                    synchronized (mInstallLock) {
13417                        // We don't need to freeze for a brand new install
13418                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13419                    }
13420                }
13421                sendPackageAddedForUser(packageName, pkgSetting, userId);
13422                synchronized (mPackages) {
13423                    updateSequenceNumberLP(packageName, new int[]{ userId });
13424                }
13425            }
13426        } finally {
13427            Binder.restoreCallingIdentity(callingId);
13428        }
13429
13430        return PackageManager.INSTALL_SUCCEEDED;
13431    }
13432
13433    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13434            boolean instantApp, boolean fullApp) {
13435        // no state specified; do nothing
13436        if (!instantApp && !fullApp) {
13437            return;
13438        }
13439        if (userId != UserHandle.USER_ALL) {
13440            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13441                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13442            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13443                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13444            }
13445        } else {
13446            for (int currentUserId : sUserManager.getUserIds()) {
13447                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13448                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13449                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13450                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13451                }
13452            }
13453        }
13454    }
13455
13456    boolean isUserRestricted(int userId, String restrictionKey) {
13457        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13458        if (restrictions.getBoolean(restrictionKey, false)) {
13459            Log.w(TAG, "User is restricted: " + restrictionKey);
13460            return true;
13461        }
13462        return false;
13463    }
13464
13465    @Override
13466    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13467            int userId) {
13468        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13469        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13470                true /* requireFullPermission */, true /* checkShell */,
13471                "setPackagesSuspended for user " + userId);
13472
13473        if (ArrayUtils.isEmpty(packageNames)) {
13474            return packageNames;
13475        }
13476
13477        // List of package names for whom the suspended state has changed.
13478        List<String> changedPackages = new ArrayList<>(packageNames.length);
13479        // List of package names for whom the suspended state is not set as requested in this
13480        // method.
13481        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13482        long callingId = Binder.clearCallingIdentity();
13483        try {
13484            for (int i = 0; i < packageNames.length; i++) {
13485                String packageName = packageNames[i];
13486                boolean changed = false;
13487                final int appId;
13488                synchronized (mPackages) {
13489                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13490                    if (pkgSetting == null) {
13491                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13492                                + "\". Skipping suspending/un-suspending.");
13493                        unactionedPackages.add(packageName);
13494                        continue;
13495                    }
13496                    appId = pkgSetting.appId;
13497                    if (pkgSetting.getSuspended(userId) != suspended) {
13498                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13499                            unactionedPackages.add(packageName);
13500                            continue;
13501                        }
13502                        pkgSetting.setSuspended(suspended, userId);
13503                        mSettings.writePackageRestrictionsLPr(userId);
13504                        changed = true;
13505                        changedPackages.add(packageName);
13506                    }
13507                }
13508
13509                if (changed && suspended) {
13510                    killApplication(packageName, UserHandle.getUid(userId, appId),
13511                            "suspending package");
13512                }
13513            }
13514        } finally {
13515            Binder.restoreCallingIdentity(callingId);
13516        }
13517
13518        if (!changedPackages.isEmpty()) {
13519            sendPackagesSuspendedForUser(changedPackages.toArray(
13520                    new String[changedPackages.size()]), userId, suspended);
13521        }
13522
13523        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13524    }
13525
13526    @Override
13527    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13528        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13529                true /* requireFullPermission */, false /* checkShell */,
13530                "isPackageSuspendedForUser for user " + userId);
13531        synchronized (mPackages) {
13532            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13533            if (pkgSetting == null) {
13534                throw new IllegalArgumentException("Unknown target package: " + packageName);
13535            }
13536            return pkgSetting.getSuspended(userId);
13537        }
13538    }
13539
13540    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13541        if (isPackageDeviceAdmin(packageName, userId)) {
13542            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13543                    + "\": has an active device admin");
13544            return false;
13545        }
13546
13547        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13548        if (packageName.equals(activeLauncherPackageName)) {
13549            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13550                    + "\": contains the active launcher");
13551            return false;
13552        }
13553
13554        if (packageName.equals(mRequiredInstallerPackage)) {
13555            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13556                    + "\": required for package installation");
13557            return false;
13558        }
13559
13560        if (packageName.equals(mRequiredUninstallerPackage)) {
13561            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13562                    + "\": required for package uninstallation");
13563            return false;
13564        }
13565
13566        if (packageName.equals(mRequiredVerifierPackage)) {
13567            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13568                    + "\": required for package verification");
13569            return false;
13570        }
13571
13572        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13573            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13574                    + "\": is the default dialer");
13575            return false;
13576        }
13577
13578        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13579            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13580                    + "\": protected package");
13581            return false;
13582        }
13583
13584        // Cannot suspend static shared libs as they are considered
13585        // a part of the using app (emulating static linking). Also
13586        // static libs are installed always on internal storage.
13587        PackageParser.Package pkg = mPackages.get(packageName);
13588        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13589            Slog.w(TAG, "Cannot suspend package: " + packageName
13590                    + " providing static shared library: "
13591                    + pkg.staticSharedLibName);
13592            return false;
13593        }
13594
13595        return true;
13596    }
13597
13598    private String getActiveLauncherPackageName(int userId) {
13599        Intent intent = new Intent(Intent.ACTION_MAIN);
13600        intent.addCategory(Intent.CATEGORY_HOME);
13601        ResolveInfo resolveInfo = resolveIntent(
13602                intent,
13603                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13604                PackageManager.MATCH_DEFAULT_ONLY,
13605                userId);
13606
13607        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13608    }
13609
13610    private String getDefaultDialerPackageName(int userId) {
13611        synchronized (mPackages) {
13612            return mSettings.getDefaultDialerPackageNameLPw(userId);
13613        }
13614    }
13615
13616    @Override
13617    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13618        mContext.enforceCallingOrSelfPermission(
13619                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13620                "Only package verification agents can verify applications");
13621
13622        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13623        final PackageVerificationResponse response = new PackageVerificationResponse(
13624                verificationCode, Binder.getCallingUid());
13625        msg.arg1 = id;
13626        msg.obj = response;
13627        mHandler.sendMessage(msg);
13628    }
13629
13630    @Override
13631    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13632            long millisecondsToDelay) {
13633        mContext.enforceCallingOrSelfPermission(
13634                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13635                "Only package verification agents can extend verification timeouts");
13636
13637        final PackageVerificationState state = mPendingVerification.get(id);
13638        final PackageVerificationResponse response = new PackageVerificationResponse(
13639                verificationCodeAtTimeout, Binder.getCallingUid());
13640
13641        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13642            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13643        }
13644        if (millisecondsToDelay < 0) {
13645            millisecondsToDelay = 0;
13646        }
13647        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13648                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13649            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13650        }
13651
13652        if ((state != null) && !state.timeoutExtended()) {
13653            state.extendTimeout();
13654
13655            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13656            msg.arg1 = id;
13657            msg.obj = response;
13658            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13659        }
13660    }
13661
13662    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13663            int verificationCode, UserHandle user) {
13664        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13665        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13666        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13667        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13668        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13669
13670        mContext.sendBroadcastAsUser(intent, user,
13671                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13672    }
13673
13674    private ComponentName matchComponentForVerifier(String packageName,
13675            List<ResolveInfo> receivers) {
13676        ActivityInfo targetReceiver = null;
13677
13678        final int NR = receivers.size();
13679        for (int i = 0; i < NR; i++) {
13680            final ResolveInfo info = receivers.get(i);
13681            if (info.activityInfo == null) {
13682                continue;
13683            }
13684
13685            if (packageName.equals(info.activityInfo.packageName)) {
13686                targetReceiver = info.activityInfo;
13687                break;
13688            }
13689        }
13690
13691        if (targetReceiver == null) {
13692            return null;
13693        }
13694
13695        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13696    }
13697
13698    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13699            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13700        if (pkgInfo.verifiers.length == 0) {
13701            return null;
13702        }
13703
13704        final int N = pkgInfo.verifiers.length;
13705        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13706        for (int i = 0; i < N; i++) {
13707            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13708
13709            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13710                    receivers);
13711            if (comp == null) {
13712                continue;
13713            }
13714
13715            final int verifierUid = getUidForVerifier(verifierInfo);
13716            if (verifierUid == -1) {
13717                continue;
13718            }
13719
13720            if (DEBUG_VERIFY) {
13721                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13722                        + " with the correct signature");
13723            }
13724            sufficientVerifiers.add(comp);
13725            verificationState.addSufficientVerifier(verifierUid);
13726        }
13727
13728        return sufficientVerifiers;
13729    }
13730
13731    private int getUidForVerifier(VerifierInfo verifierInfo) {
13732        synchronized (mPackages) {
13733            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13734            if (pkg == null) {
13735                return -1;
13736            } else if (pkg.mSignatures.length != 1) {
13737                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13738                        + " has more than one signature; ignoring");
13739                return -1;
13740            }
13741
13742            /*
13743             * If the public key of the package's signature does not match
13744             * our expected public key, then this is a different package and
13745             * we should skip.
13746             */
13747
13748            final byte[] expectedPublicKey;
13749            try {
13750                final Signature verifierSig = pkg.mSignatures[0];
13751                final PublicKey publicKey = verifierSig.getPublicKey();
13752                expectedPublicKey = publicKey.getEncoded();
13753            } catch (CertificateException e) {
13754                return -1;
13755            }
13756
13757            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13758
13759            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13760                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13761                        + " does not have the expected public key; ignoring");
13762                return -1;
13763            }
13764
13765            return pkg.applicationInfo.uid;
13766        }
13767    }
13768
13769    @Override
13770    public void finishPackageInstall(int token, boolean didLaunch) {
13771        enforceSystemOrRoot("Only the system is allowed to finish installs");
13772
13773        if (DEBUG_INSTALL) {
13774            Slog.v(TAG, "BM finishing package install for " + token);
13775        }
13776        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13777
13778        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13779        mHandler.sendMessage(msg);
13780    }
13781
13782    /**
13783     * Get the verification agent timeout.
13784     *
13785     * @return verification timeout in milliseconds
13786     */
13787    private long getVerificationTimeout() {
13788        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13789                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13790                DEFAULT_VERIFICATION_TIMEOUT);
13791    }
13792
13793    /**
13794     * Get the default verification agent response code.
13795     *
13796     * @return default verification response code
13797     */
13798    private int getDefaultVerificationResponse() {
13799        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13800                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13801                DEFAULT_VERIFICATION_RESPONSE);
13802    }
13803
13804    /**
13805     * Check whether or not package verification has been enabled.
13806     *
13807     * @return true if verification should be performed
13808     */
13809    private boolean isVerificationEnabled(int userId, int installFlags) {
13810        if (!DEFAULT_VERIFY_ENABLE) {
13811            return false;
13812        }
13813        // Ephemeral apps don't get the full verification treatment
13814        if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13815            if (DEBUG_EPHEMERAL) {
13816                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13817            }
13818            return false;
13819        }
13820
13821        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13822
13823        // Check if installing from ADB
13824        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13825            // Do not run verification in a test harness environment
13826            if (ActivityManager.isRunningInTestHarness()) {
13827                return false;
13828            }
13829            if (ensureVerifyAppsEnabled) {
13830                return true;
13831            }
13832            // Check if the developer does not want package verification for ADB installs
13833            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13834                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13835                return false;
13836            }
13837        }
13838
13839        if (ensureVerifyAppsEnabled) {
13840            return true;
13841        }
13842
13843        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13844                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13845    }
13846
13847    @Override
13848    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13849            throws RemoteException {
13850        mContext.enforceCallingOrSelfPermission(
13851                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13852                "Only intentfilter verification agents can verify applications");
13853
13854        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13855        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13856                Binder.getCallingUid(), verificationCode, failedDomains);
13857        msg.arg1 = id;
13858        msg.obj = response;
13859        mHandler.sendMessage(msg);
13860    }
13861
13862    @Override
13863    public int getIntentVerificationStatus(String packageName, int userId) {
13864        synchronized (mPackages) {
13865            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13866        }
13867    }
13868
13869    @Override
13870    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13871        mContext.enforceCallingOrSelfPermission(
13872                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13873
13874        boolean result = false;
13875        synchronized (mPackages) {
13876            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13877        }
13878        if (result) {
13879            scheduleWritePackageRestrictionsLocked(userId);
13880        }
13881        return result;
13882    }
13883
13884    @Override
13885    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13886            String packageName) {
13887        synchronized (mPackages) {
13888            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13889        }
13890    }
13891
13892    @Override
13893    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13894        if (TextUtils.isEmpty(packageName)) {
13895            return ParceledListSlice.emptyList();
13896        }
13897        synchronized (mPackages) {
13898            PackageParser.Package pkg = mPackages.get(packageName);
13899            if (pkg == null || pkg.activities == null) {
13900                return ParceledListSlice.emptyList();
13901            }
13902            final int count = pkg.activities.size();
13903            ArrayList<IntentFilter> result = new ArrayList<>();
13904            for (int n=0; n<count; n++) {
13905                PackageParser.Activity activity = pkg.activities.get(n);
13906                if (activity.intents != null && activity.intents.size() > 0) {
13907                    result.addAll(activity.intents);
13908                }
13909            }
13910            return new ParceledListSlice<>(result);
13911        }
13912    }
13913
13914    @Override
13915    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13916        mContext.enforceCallingOrSelfPermission(
13917                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13918
13919        synchronized (mPackages) {
13920            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13921            if (packageName != null) {
13922                result |= updateIntentVerificationStatus(packageName,
13923                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13924                        userId);
13925                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13926                        packageName, userId);
13927            }
13928            return result;
13929        }
13930    }
13931
13932    @Override
13933    public String getDefaultBrowserPackageName(int userId) {
13934        synchronized (mPackages) {
13935            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13936        }
13937    }
13938
13939    /**
13940     * Get the "allow unknown sources" setting.
13941     *
13942     * @return the current "allow unknown sources" setting
13943     */
13944    private int getUnknownSourcesSettings() {
13945        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13946                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13947                -1);
13948    }
13949
13950    @Override
13951    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13952        final int uid = Binder.getCallingUid();
13953        // writer
13954        synchronized (mPackages) {
13955            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13956            if (targetPackageSetting == null) {
13957                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13958            }
13959
13960            PackageSetting installerPackageSetting;
13961            if (installerPackageName != null) {
13962                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13963                if (installerPackageSetting == null) {
13964                    throw new IllegalArgumentException("Unknown installer package: "
13965                            + installerPackageName);
13966                }
13967            } else {
13968                installerPackageSetting = null;
13969            }
13970
13971            Signature[] callerSignature;
13972            Object obj = mSettings.getUserIdLPr(uid);
13973            if (obj != null) {
13974                if (obj instanceof SharedUserSetting) {
13975                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13976                } else if (obj instanceof PackageSetting) {
13977                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13978                } else {
13979                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13980                }
13981            } else {
13982                throw new SecurityException("Unknown calling UID: " + uid);
13983            }
13984
13985            // Verify: can't set installerPackageName to a package that is
13986            // not signed with the same cert as the caller.
13987            if (installerPackageSetting != null) {
13988                if (compareSignatures(callerSignature,
13989                        installerPackageSetting.signatures.mSignatures)
13990                        != PackageManager.SIGNATURE_MATCH) {
13991                    throw new SecurityException(
13992                            "Caller does not have same cert as new installer package "
13993                            + installerPackageName);
13994                }
13995            }
13996
13997            // Verify: if target already has an installer package, it must
13998            // be signed with the same cert as the caller.
13999            if (targetPackageSetting.installerPackageName != null) {
14000                PackageSetting setting = mSettings.mPackages.get(
14001                        targetPackageSetting.installerPackageName);
14002                // If the currently set package isn't valid, then it's always
14003                // okay to change it.
14004                if (setting != null) {
14005                    if (compareSignatures(callerSignature,
14006                            setting.signatures.mSignatures)
14007                            != PackageManager.SIGNATURE_MATCH) {
14008                        throw new SecurityException(
14009                                "Caller does not have same cert as old installer package "
14010                                + targetPackageSetting.installerPackageName);
14011                    }
14012                }
14013            }
14014
14015            // Okay!
14016            targetPackageSetting.installerPackageName = installerPackageName;
14017            if (installerPackageName != null) {
14018                mSettings.mInstallerPackages.add(installerPackageName);
14019            }
14020            scheduleWriteSettingsLocked();
14021        }
14022    }
14023
14024    @Override
14025    public void setApplicationCategoryHint(String packageName, int categoryHint,
14026            String callerPackageName) {
14027        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14028                callerPackageName);
14029        synchronized (mPackages) {
14030            PackageSetting ps = mSettings.mPackages.get(packageName);
14031            if (ps == null) {
14032                throw new IllegalArgumentException("Unknown target package " + packageName);
14033            }
14034
14035            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14036                throw new IllegalArgumentException("Calling package " + callerPackageName
14037                        + " is not installer for " + packageName);
14038            }
14039
14040            if (ps.categoryHint != categoryHint) {
14041                ps.categoryHint = categoryHint;
14042                scheduleWriteSettingsLocked();
14043            }
14044        }
14045    }
14046
14047    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14048        // Queue up an async operation since the package installation may take a little while.
14049        mHandler.post(new Runnable() {
14050            public void run() {
14051                mHandler.removeCallbacks(this);
14052                 // Result object to be returned
14053                PackageInstalledInfo res = new PackageInstalledInfo();
14054                res.setReturnCode(currentStatus);
14055                res.uid = -1;
14056                res.pkg = null;
14057                res.removedInfo = null;
14058                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14059                    args.doPreInstall(res.returnCode);
14060                    synchronized (mInstallLock) {
14061                        installPackageTracedLI(args, res);
14062                    }
14063                    args.doPostInstall(res.returnCode, res.uid);
14064                }
14065
14066                // A restore should be performed at this point if (a) the install
14067                // succeeded, (b) the operation is not an update, and (c) the new
14068                // package has not opted out of backup participation.
14069                final boolean update = res.removedInfo != null
14070                        && res.removedInfo.removedPackage != null;
14071                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14072                boolean doRestore = !update
14073                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14074
14075                // Set up the post-install work request bookkeeping.  This will be used
14076                // and cleaned up by the post-install event handling regardless of whether
14077                // there's a restore pass performed.  Token values are >= 1.
14078                int token;
14079                if (mNextInstallToken < 0) mNextInstallToken = 1;
14080                token = mNextInstallToken++;
14081
14082                PostInstallData data = new PostInstallData(args, res);
14083                mRunningInstalls.put(token, data);
14084                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14085
14086                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14087                    // Pass responsibility to the Backup Manager.  It will perform a
14088                    // restore if appropriate, then pass responsibility back to the
14089                    // Package Manager to run the post-install observer callbacks
14090                    // and broadcasts.
14091                    IBackupManager bm = IBackupManager.Stub.asInterface(
14092                            ServiceManager.getService(Context.BACKUP_SERVICE));
14093                    if (bm != null) {
14094                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14095                                + " to BM for possible restore");
14096                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14097                        try {
14098                            // TODO: http://b/22388012
14099                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14100                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14101                            } else {
14102                                doRestore = false;
14103                            }
14104                        } catch (RemoteException e) {
14105                            // can't happen; the backup manager is local
14106                        } catch (Exception e) {
14107                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14108                            doRestore = false;
14109                        }
14110                    } else {
14111                        Slog.e(TAG, "Backup Manager not found!");
14112                        doRestore = false;
14113                    }
14114                }
14115
14116                if (!doRestore) {
14117                    // No restore possible, or the Backup Manager was mysteriously not
14118                    // available -- just fire the post-install work request directly.
14119                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14120
14121                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14122
14123                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14124                    mHandler.sendMessage(msg);
14125                }
14126            }
14127        });
14128    }
14129
14130    /**
14131     * Callback from PackageSettings whenever an app is first transitioned out of the
14132     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14133     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14134     * here whether the app is the target of an ongoing install, and only send the
14135     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14136     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14137     * handling.
14138     */
14139    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14140        // Serialize this with the rest of the install-process message chain.  In the
14141        // restore-at-install case, this Runnable will necessarily run before the
14142        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14143        // are coherent.  In the non-restore case, the app has already completed install
14144        // and been launched through some other means, so it is not in a problematic
14145        // state for observers to see the FIRST_LAUNCH signal.
14146        mHandler.post(new Runnable() {
14147            @Override
14148            public void run() {
14149                for (int i = 0; i < mRunningInstalls.size(); i++) {
14150                    final PostInstallData data = mRunningInstalls.valueAt(i);
14151                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14152                        continue;
14153                    }
14154                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14155                        // right package; but is it for the right user?
14156                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14157                            if (userId == data.res.newUsers[uIndex]) {
14158                                if (DEBUG_BACKUP) {
14159                                    Slog.i(TAG, "Package " + pkgName
14160                                            + " being restored so deferring FIRST_LAUNCH");
14161                                }
14162                                return;
14163                            }
14164                        }
14165                    }
14166                }
14167                // didn't find it, so not being restored
14168                if (DEBUG_BACKUP) {
14169                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14170                }
14171                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14172            }
14173        });
14174    }
14175
14176    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14177        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14178                installerPkg, null, userIds);
14179    }
14180
14181    private abstract class HandlerParams {
14182        private static final int MAX_RETRIES = 4;
14183
14184        /**
14185         * Number of times startCopy() has been attempted and had a non-fatal
14186         * error.
14187         */
14188        private int mRetries = 0;
14189
14190        /** User handle for the user requesting the information or installation. */
14191        private final UserHandle mUser;
14192        String traceMethod;
14193        int traceCookie;
14194
14195        HandlerParams(UserHandle user) {
14196            mUser = user;
14197        }
14198
14199        UserHandle getUser() {
14200            return mUser;
14201        }
14202
14203        HandlerParams setTraceMethod(String traceMethod) {
14204            this.traceMethod = traceMethod;
14205            return this;
14206        }
14207
14208        HandlerParams setTraceCookie(int traceCookie) {
14209            this.traceCookie = traceCookie;
14210            return this;
14211        }
14212
14213        final boolean startCopy() {
14214            boolean res;
14215            try {
14216                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14217
14218                if (++mRetries > MAX_RETRIES) {
14219                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14220                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14221                    handleServiceError();
14222                    return false;
14223                } else {
14224                    handleStartCopy();
14225                    res = true;
14226                }
14227            } catch (RemoteException e) {
14228                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14229                mHandler.sendEmptyMessage(MCS_RECONNECT);
14230                res = false;
14231            }
14232            handleReturnCode();
14233            return res;
14234        }
14235
14236        final void serviceError() {
14237            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14238            handleServiceError();
14239            handleReturnCode();
14240        }
14241
14242        abstract void handleStartCopy() throws RemoteException;
14243        abstract void handleServiceError();
14244        abstract void handleReturnCode();
14245    }
14246
14247    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14248        for (File path : paths) {
14249            try {
14250                mcs.clearDirectory(path.getAbsolutePath());
14251            } catch (RemoteException e) {
14252            }
14253        }
14254    }
14255
14256    static class OriginInfo {
14257        /**
14258         * Location where install is coming from, before it has been
14259         * copied/renamed into place. This could be a single monolithic APK
14260         * file, or a cluster directory. This location may be untrusted.
14261         */
14262        final File file;
14263        final String cid;
14264
14265        /**
14266         * Flag indicating that {@link #file} or {@link #cid} has already been
14267         * staged, meaning downstream users don't need to defensively copy the
14268         * contents.
14269         */
14270        final boolean staged;
14271
14272        /**
14273         * Flag indicating that {@link #file} or {@link #cid} is an already
14274         * installed app that is being moved.
14275         */
14276        final boolean existing;
14277
14278        final String resolvedPath;
14279        final File resolvedFile;
14280
14281        static OriginInfo fromNothing() {
14282            return new OriginInfo(null, null, false, false);
14283        }
14284
14285        static OriginInfo fromUntrustedFile(File file) {
14286            return new OriginInfo(file, null, false, false);
14287        }
14288
14289        static OriginInfo fromExistingFile(File file) {
14290            return new OriginInfo(file, null, false, true);
14291        }
14292
14293        static OriginInfo fromStagedFile(File file) {
14294            return new OriginInfo(file, null, true, false);
14295        }
14296
14297        static OriginInfo fromStagedContainer(String cid) {
14298            return new OriginInfo(null, cid, true, false);
14299        }
14300
14301        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14302            this.file = file;
14303            this.cid = cid;
14304            this.staged = staged;
14305            this.existing = existing;
14306
14307            if (cid != null) {
14308                resolvedPath = PackageHelper.getSdDir(cid);
14309                resolvedFile = new File(resolvedPath);
14310            } else if (file != null) {
14311                resolvedPath = file.getAbsolutePath();
14312                resolvedFile = file;
14313            } else {
14314                resolvedPath = null;
14315                resolvedFile = null;
14316            }
14317        }
14318    }
14319
14320    static class MoveInfo {
14321        final int moveId;
14322        final String fromUuid;
14323        final String toUuid;
14324        final String packageName;
14325        final String dataAppName;
14326        final int appId;
14327        final String seinfo;
14328        final int targetSdkVersion;
14329
14330        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14331                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14332            this.moveId = moveId;
14333            this.fromUuid = fromUuid;
14334            this.toUuid = toUuid;
14335            this.packageName = packageName;
14336            this.dataAppName = dataAppName;
14337            this.appId = appId;
14338            this.seinfo = seinfo;
14339            this.targetSdkVersion = targetSdkVersion;
14340        }
14341    }
14342
14343    static class VerificationInfo {
14344        /** A constant used to indicate that a uid value is not present. */
14345        public static final int NO_UID = -1;
14346
14347        /** URI referencing where the package was downloaded from. */
14348        final Uri originatingUri;
14349
14350        /** HTTP referrer URI associated with the originatingURI. */
14351        final Uri referrer;
14352
14353        /** UID of the application that the install request originated from. */
14354        final int originatingUid;
14355
14356        /** UID of application requesting the install */
14357        final int installerUid;
14358
14359        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14360            this.originatingUri = originatingUri;
14361            this.referrer = referrer;
14362            this.originatingUid = originatingUid;
14363            this.installerUid = installerUid;
14364        }
14365    }
14366
14367    class InstallParams extends HandlerParams {
14368        final OriginInfo origin;
14369        final MoveInfo move;
14370        final IPackageInstallObserver2 observer;
14371        int installFlags;
14372        final String installerPackageName;
14373        final String volumeUuid;
14374        private InstallArgs mArgs;
14375        private int mRet;
14376        final String packageAbiOverride;
14377        final String[] grantedRuntimePermissions;
14378        final VerificationInfo verificationInfo;
14379        final Certificate[][] certificates;
14380        final int installReason;
14381
14382        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14383                int installFlags, String installerPackageName, String volumeUuid,
14384                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14385                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14386            super(user);
14387            this.origin = origin;
14388            this.move = move;
14389            this.observer = observer;
14390            this.installFlags = installFlags;
14391            this.installerPackageName = installerPackageName;
14392            this.volumeUuid = volumeUuid;
14393            this.verificationInfo = verificationInfo;
14394            this.packageAbiOverride = packageAbiOverride;
14395            this.grantedRuntimePermissions = grantedPermissions;
14396            this.certificates = certificates;
14397            this.installReason = installReason;
14398        }
14399
14400        @Override
14401        public String toString() {
14402            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14403                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14404        }
14405
14406        private int installLocationPolicy(PackageInfoLite pkgLite) {
14407            String packageName = pkgLite.packageName;
14408            int installLocation = pkgLite.installLocation;
14409            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14410            // reader
14411            synchronized (mPackages) {
14412                // Currently installed package which the new package is attempting to replace or
14413                // null if no such package is installed.
14414                PackageParser.Package installedPkg = mPackages.get(packageName);
14415                // Package which currently owns the data which the new package will own if installed.
14416                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14417                // will be null whereas dataOwnerPkg will contain information about the package
14418                // which was uninstalled while keeping its data.
14419                PackageParser.Package dataOwnerPkg = installedPkg;
14420                if (dataOwnerPkg  == null) {
14421                    PackageSetting ps = mSettings.mPackages.get(packageName);
14422                    if (ps != null) {
14423                        dataOwnerPkg = ps.pkg;
14424                    }
14425                }
14426
14427                if (dataOwnerPkg != null) {
14428                    // If installed, the package will get access to data left on the device by its
14429                    // predecessor. As a security measure, this is permited only if this is not a
14430                    // version downgrade or if the predecessor package is marked as debuggable and
14431                    // a downgrade is explicitly requested.
14432                    //
14433                    // On debuggable platform builds, downgrades are permitted even for
14434                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14435                    // not offer security guarantees and thus it's OK to disable some security
14436                    // mechanisms to make debugging/testing easier on those builds. However, even on
14437                    // debuggable builds downgrades of packages are permitted only if requested via
14438                    // installFlags. This is because we aim to keep the behavior of debuggable
14439                    // platform builds as close as possible to the behavior of non-debuggable
14440                    // platform builds.
14441                    final boolean downgradeRequested =
14442                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14443                    final boolean packageDebuggable =
14444                                (dataOwnerPkg.applicationInfo.flags
14445                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14446                    final boolean downgradePermitted =
14447                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14448                    if (!downgradePermitted) {
14449                        try {
14450                            checkDowngrade(dataOwnerPkg, pkgLite);
14451                        } catch (PackageManagerException e) {
14452                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14453                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14454                        }
14455                    }
14456                }
14457
14458                if (installedPkg != null) {
14459                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14460                        // Check for updated system application.
14461                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14462                            if (onSd) {
14463                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14464                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14465                            }
14466                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14467                        } else {
14468                            if (onSd) {
14469                                // Install flag overrides everything.
14470                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14471                            }
14472                            // If current upgrade specifies particular preference
14473                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14474                                // Application explicitly specified internal.
14475                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14476                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14477                                // App explictly prefers external. Let policy decide
14478                            } else {
14479                                // Prefer previous location
14480                                if (isExternal(installedPkg)) {
14481                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14482                                }
14483                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14484                            }
14485                        }
14486                    } else {
14487                        // Invalid install. Return error code
14488                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14489                    }
14490                }
14491            }
14492            // All the special cases have been taken care of.
14493            // Return result based on recommended install location.
14494            if (onSd) {
14495                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14496            }
14497            return pkgLite.recommendedInstallLocation;
14498        }
14499
14500        /*
14501         * Invoke remote method to get package information and install
14502         * location values. Override install location based on default
14503         * policy if needed and then create install arguments based
14504         * on the install location.
14505         */
14506        public void handleStartCopy() throws RemoteException {
14507            int ret = PackageManager.INSTALL_SUCCEEDED;
14508
14509            // If we're already staged, we've firmly committed to an install location
14510            if (origin.staged) {
14511                if (origin.file != null) {
14512                    installFlags |= PackageManager.INSTALL_INTERNAL;
14513                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14514                } else if (origin.cid != null) {
14515                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14516                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14517                } else {
14518                    throw new IllegalStateException("Invalid stage location");
14519                }
14520            }
14521
14522            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14523            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14524            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14525            PackageInfoLite pkgLite = null;
14526
14527            if (onInt && onSd) {
14528                // Check if both bits are set.
14529                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14530                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14531            } else if (onSd && ephemeral) {
14532                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14533                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14534            } else {
14535                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14536                        packageAbiOverride);
14537
14538                if (DEBUG_EPHEMERAL && ephemeral) {
14539                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14540                }
14541
14542                /*
14543                 * If we have too little free space, try to free cache
14544                 * before giving up.
14545                 */
14546                if (!origin.staged && pkgLite.recommendedInstallLocation
14547                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14548                    // TODO: focus freeing disk space on the target device
14549                    final StorageManager storage = StorageManager.from(mContext);
14550                    final long lowThreshold = storage.getStorageLowBytes(
14551                            Environment.getDataDirectory());
14552
14553                    final long sizeBytes = mContainerService.calculateInstalledSize(
14554                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14555
14556                    try {
14557                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14558                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14559                                installFlags, packageAbiOverride);
14560                    } catch (InstallerException e) {
14561                        Slog.w(TAG, "Failed to free cache", e);
14562                    }
14563
14564                    /*
14565                     * The cache free must have deleted the file we
14566                     * downloaded to install.
14567                     *
14568                     * TODO: fix the "freeCache" call to not delete
14569                     *       the file we care about.
14570                     */
14571                    if (pkgLite.recommendedInstallLocation
14572                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14573                        pkgLite.recommendedInstallLocation
14574                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14575                    }
14576                }
14577            }
14578
14579            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14580                int loc = pkgLite.recommendedInstallLocation;
14581                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14582                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14583                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14584                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14585                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14586                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14587                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14588                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14589                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14590                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14591                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14592                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14593                } else {
14594                    // Override with defaults if needed.
14595                    loc = installLocationPolicy(pkgLite);
14596                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14597                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14598                    } else if (!onSd && !onInt) {
14599                        // Override install location with flags
14600                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14601                            // Set the flag to install on external media.
14602                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14603                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14604                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14605                            if (DEBUG_EPHEMERAL) {
14606                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14607                            }
14608                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14609                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14610                                    |PackageManager.INSTALL_INTERNAL);
14611                        } else {
14612                            // Make sure the flag for installing on external
14613                            // media is unset
14614                            installFlags |= PackageManager.INSTALL_INTERNAL;
14615                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14616                        }
14617                    }
14618                }
14619            }
14620
14621            final InstallArgs args = createInstallArgs(this);
14622            mArgs = args;
14623
14624            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14625                // TODO: http://b/22976637
14626                // Apps installed for "all" users use the device owner to verify the app
14627                UserHandle verifierUser = getUser();
14628                if (verifierUser == UserHandle.ALL) {
14629                    verifierUser = UserHandle.SYSTEM;
14630                }
14631
14632                /*
14633                 * Determine if we have any installed package verifiers. If we
14634                 * do, then we'll defer to them to verify the packages.
14635                 */
14636                final int requiredUid = mRequiredVerifierPackage == null ? -1
14637                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14638                                verifierUser.getIdentifier());
14639                if (!origin.existing && requiredUid != -1
14640                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14641                    final Intent verification = new Intent(
14642                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14643                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14644                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14645                            PACKAGE_MIME_TYPE);
14646                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14647
14648                    // Query all live verifiers based on current user state
14649                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14650                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14651
14652                    if (DEBUG_VERIFY) {
14653                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14654                                + verification.toString() + " with " + pkgLite.verifiers.length
14655                                + " optional verifiers");
14656                    }
14657
14658                    final int verificationId = mPendingVerificationToken++;
14659
14660                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14661
14662                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14663                            installerPackageName);
14664
14665                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14666                            installFlags);
14667
14668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14669                            pkgLite.packageName);
14670
14671                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14672                            pkgLite.versionCode);
14673
14674                    if (verificationInfo != null) {
14675                        if (verificationInfo.originatingUri != null) {
14676                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14677                                    verificationInfo.originatingUri);
14678                        }
14679                        if (verificationInfo.referrer != null) {
14680                            verification.putExtra(Intent.EXTRA_REFERRER,
14681                                    verificationInfo.referrer);
14682                        }
14683                        if (verificationInfo.originatingUid >= 0) {
14684                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14685                                    verificationInfo.originatingUid);
14686                        }
14687                        if (verificationInfo.installerUid >= 0) {
14688                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14689                                    verificationInfo.installerUid);
14690                        }
14691                    }
14692
14693                    final PackageVerificationState verificationState = new PackageVerificationState(
14694                            requiredUid, args);
14695
14696                    mPendingVerification.append(verificationId, verificationState);
14697
14698                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14699                            receivers, verificationState);
14700
14701                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14702                    final long idleDuration = getVerificationTimeout();
14703
14704                    /*
14705                     * If any sufficient verifiers were listed in the package
14706                     * manifest, attempt to ask them.
14707                     */
14708                    if (sufficientVerifiers != null) {
14709                        final int N = sufficientVerifiers.size();
14710                        if (N == 0) {
14711                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14712                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14713                        } else {
14714                            for (int i = 0; i < N; i++) {
14715                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14716                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14717                                        verifierComponent.getPackageName(), idleDuration,
14718                                        verifierUser.getIdentifier(), false, "package verifier");
14719
14720                                final Intent sufficientIntent = new Intent(verification);
14721                                sufficientIntent.setComponent(verifierComponent);
14722                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14723                            }
14724                        }
14725                    }
14726
14727                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14728                            mRequiredVerifierPackage, receivers);
14729                    if (ret == PackageManager.INSTALL_SUCCEEDED
14730                            && mRequiredVerifierPackage != null) {
14731                        Trace.asyncTraceBegin(
14732                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14733                        /*
14734                         * Send the intent to the required verification agent,
14735                         * but only start the verification timeout after the
14736                         * target BroadcastReceivers have run.
14737                         */
14738                        verification.setComponent(requiredVerifierComponent);
14739                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14740                                requiredVerifierComponent.getPackageName(), idleDuration,
14741                                verifierUser.getIdentifier(), false, "package verifier");
14742                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14743                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14744                                new BroadcastReceiver() {
14745                                    @Override
14746                                    public void onReceive(Context context, Intent intent) {
14747                                        final Message msg = mHandler
14748                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14749                                        msg.arg1 = verificationId;
14750                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14751                                    }
14752                                }, null, 0, null, null);
14753
14754                        /*
14755                         * We don't want the copy to proceed until verification
14756                         * succeeds, so null out this field.
14757                         */
14758                        mArgs = null;
14759                    }
14760                } else {
14761                    /*
14762                     * No package verification is enabled, so immediately start
14763                     * the remote call to initiate copy using temporary file.
14764                     */
14765                    ret = args.copyApk(mContainerService, true);
14766                }
14767            }
14768
14769            mRet = ret;
14770        }
14771
14772        @Override
14773        void handleReturnCode() {
14774            // If mArgs is null, then MCS couldn't be reached. When it
14775            // reconnects, it will try again to install. At that point, this
14776            // will succeed.
14777            if (mArgs != null) {
14778                processPendingInstall(mArgs, mRet);
14779            }
14780        }
14781
14782        @Override
14783        void handleServiceError() {
14784            mArgs = createInstallArgs(this);
14785            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14786        }
14787
14788        public boolean isForwardLocked() {
14789            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14790        }
14791    }
14792
14793    /**
14794     * Used during creation of InstallArgs
14795     *
14796     * @param installFlags package installation flags
14797     * @return true if should be installed on external storage
14798     */
14799    private static boolean installOnExternalAsec(int installFlags) {
14800        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14801            return false;
14802        }
14803        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14804            return true;
14805        }
14806        return false;
14807    }
14808
14809    /**
14810     * Used during creation of InstallArgs
14811     *
14812     * @param installFlags package installation flags
14813     * @return true if should be installed as forward locked
14814     */
14815    private static boolean installForwardLocked(int installFlags) {
14816        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14817    }
14818
14819    private InstallArgs createInstallArgs(InstallParams params) {
14820        if (params.move != null) {
14821            return new MoveInstallArgs(params);
14822        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14823            return new AsecInstallArgs(params);
14824        } else {
14825            return new FileInstallArgs(params);
14826        }
14827    }
14828
14829    /**
14830     * Create args that describe an existing installed package. Typically used
14831     * when cleaning up old installs, or used as a move source.
14832     */
14833    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14834            String resourcePath, String[] instructionSets) {
14835        final boolean isInAsec;
14836        if (installOnExternalAsec(installFlags)) {
14837            /* Apps on SD card are always in ASEC containers. */
14838            isInAsec = true;
14839        } else if (installForwardLocked(installFlags)
14840                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14841            /*
14842             * Forward-locked apps are only in ASEC containers if they're the
14843             * new style
14844             */
14845            isInAsec = true;
14846        } else {
14847            isInAsec = false;
14848        }
14849
14850        if (isInAsec) {
14851            return new AsecInstallArgs(codePath, instructionSets,
14852                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14853        } else {
14854            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14855        }
14856    }
14857
14858    static abstract class InstallArgs {
14859        /** @see InstallParams#origin */
14860        final OriginInfo origin;
14861        /** @see InstallParams#move */
14862        final MoveInfo move;
14863
14864        final IPackageInstallObserver2 observer;
14865        // Always refers to PackageManager flags only
14866        final int installFlags;
14867        final String installerPackageName;
14868        final String volumeUuid;
14869        final UserHandle user;
14870        final String abiOverride;
14871        final String[] installGrantPermissions;
14872        /** If non-null, drop an async trace when the install completes */
14873        final String traceMethod;
14874        final int traceCookie;
14875        final Certificate[][] certificates;
14876        final int installReason;
14877
14878        // The list of instruction sets supported by this app. This is currently
14879        // only used during the rmdex() phase to clean up resources. We can get rid of this
14880        // if we move dex files under the common app path.
14881        /* nullable */ String[] instructionSets;
14882
14883        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14884                int installFlags, String installerPackageName, String volumeUuid,
14885                UserHandle user, String[] instructionSets,
14886                String abiOverride, String[] installGrantPermissions,
14887                String traceMethod, int traceCookie, Certificate[][] certificates,
14888                int installReason) {
14889            this.origin = origin;
14890            this.move = move;
14891            this.installFlags = installFlags;
14892            this.observer = observer;
14893            this.installerPackageName = installerPackageName;
14894            this.volumeUuid = volumeUuid;
14895            this.user = user;
14896            this.instructionSets = instructionSets;
14897            this.abiOverride = abiOverride;
14898            this.installGrantPermissions = installGrantPermissions;
14899            this.traceMethod = traceMethod;
14900            this.traceCookie = traceCookie;
14901            this.certificates = certificates;
14902            this.installReason = installReason;
14903        }
14904
14905        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14906        abstract int doPreInstall(int status);
14907
14908        /**
14909         * Rename package into final resting place. All paths on the given
14910         * scanned package should be updated to reflect the rename.
14911         */
14912        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14913        abstract int doPostInstall(int status, int uid);
14914
14915        /** @see PackageSettingBase#codePathString */
14916        abstract String getCodePath();
14917        /** @see PackageSettingBase#resourcePathString */
14918        abstract String getResourcePath();
14919
14920        // Need installer lock especially for dex file removal.
14921        abstract void cleanUpResourcesLI();
14922        abstract boolean doPostDeleteLI(boolean delete);
14923
14924        /**
14925         * Called before the source arguments are copied. This is used mostly
14926         * for MoveParams when it needs to read the source file to put it in the
14927         * destination.
14928         */
14929        int doPreCopy() {
14930            return PackageManager.INSTALL_SUCCEEDED;
14931        }
14932
14933        /**
14934         * Called after the source arguments are copied. This is used mostly for
14935         * MoveParams when it needs to read the source file to put it in the
14936         * destination.
14937         */
14938        int doPostCopy(int uid) {
14939            return PackageManager.INSTALL_SUCCEEDED;
14940        }
14941
14942        protected boolean isFwdLocked() {
14943            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14944        }
14945
14946        protected boolean isExternalAsec() {
14947            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14948        }
14949
14950        protected boolean isEphemeral() {
14951            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14952        }
14953
14954        UserHandle getUser() {
14955            return user;
14956        }
14957    }
14958
14959    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14960        if (!allCodePaths.isEmpty()) {
14961            if (instructionSets == null) {
14962                throw new IllegalStateException("instructionSet == null");
14963            }
14964            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14965            for (String codePath : allCodePaths) {
14966                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14967                    try {
14968                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14969                    } catch (InstallerException ignored) {
14970                    }
14971                }
14972            }
14973        }
14974    }
14975
14976    /**
14977     * Logic to handle installation of non-ASEC applications, including copying
14978     * and renaming logic.
14979     */
14980    class FileInstallArgs extends InstallArgs {
14981        private File codeFile;
14982        private File resourceFile;
14983
14984        // Example topology:
14985        // /data/app/com.example/base.apk
14986        // /data/app/com.example/split_foo.apk
14987        // /data/app/com.example/lib/arm/libfoo.so
14988        // /data/app/com.example/lib/arm64/libfoo.so
14989        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14990
14991        /** New install */
14992        FileInstallArgs(InstallParams params) {
14993            super(params.origin, params.move, params.observer, params.installFlags,
14994                    params.installerPackageName, params.volumeUuid,
14995                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14996                    params.grantedRuntimePermissions,
14997                    params.traceMethod, params.traceCookie, params.certificates,
14998                    params.installReason);
14999            if (isFwdLocked()) {
15000                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15001            }
15002        }
15003
15004        /** Existing install */
15005        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15006            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15007                    null, null, null, 0, null /*certificates*/,
15008                    PackageManager.INSTALL_REASON_UNKNOWN);
15009            this.codeFile = (codePath != null) ? new File(codePath) : null;
15010            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15011        }
15012
15013        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15014            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15015            try {
15016                return doCopyApk(imcs, temp);
15017            } finally {
15018                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15019            }
15020        }
15021
15022        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15023            if (origin.staged) {
15024                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15025                codeFile = origin.file;
15026                resourceFile = origin.file;
15027                return PackageManager.INSTALL_SUCCEEDED;
15028            }
15029
15030            try {
15031                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15032                final File tempDir =
15033                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15034                codeFile = tempDir;
15035                resourceFile = tempDir;
15036            } catch (IOException e) {
15037                Slog.w(TAG, "Failed to create copy file: " + e);
15038                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15039            }
15040
15041            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15042                @Override
15043                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15044                    if (!FileUtils.isValidExtFilename(name)) {
15045                        throw new IllegalArgumentException("Invalid filename: " + name);
15046                    }
15047                    try {
15048                        final File file = new File(codeFile, name);
15049                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15050                                O_RDWR | O_CREAT, 0644);
15051                        Os.chmod(file.getAbsolutePath(), 0644);
15052                        return new ParcelFileDescriptor(fd);
15053                    } catch (ErrnoException e) {
15054                        throw new RemoteException("Failed to open: " + e.getMessage());
15055                    }
15056                }
15057            };
15058
15059            int ret = PackageManager.INSTALL_SUCCEEDED;
15060            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15061            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15062                Slog.e(TAG, "Failed to copy package");
15063                return ret;
15064            }
15065
15066            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15067            NativeLibraryHelper.Handle handle = null;
15068            try {
15069                handle = NativeLibraryHelper.Handle.create(codeFile);
15070                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15071                        abiOverride);
15072            } catch (IOException e) {
15073                Slog.e(TAG, "Copying native libraries failed", e);
15074                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15075            } finally {
15076                IoUtils.closeQuietly(handle);
15077            }
15078
15079            return ret;
15080        }
15081
15082        int doPreInstall(int status) {
15083            if (status != PackageManager.INSTALL_SUCCEEDED) {
15084                cleanUp();
15085            }
15086            return status;
15087        }
15088
15089        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15090            if (status != PackageManager.INSTALL_SUCCEEDED) {
15091                cleanUp();
15092                return false;
15093            }
15094
15095            final File targetDir = codeFile.getParentFile();
15096            final File beforeCodeFile = codeFile;
15097            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15098
15099            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15100            try {
15101                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15102            } catch (ErrnoException e) {
15103                Slog.w(TAG, "Failed to rename", e);
15104                return false;
15105            }
15106
15107            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15108                Slog.w(TAG, "Failed to restorecon");
15109                return false;
15110            }
15111
15112            // Reflect the rename internally
15113            codeFile = afterCodeFile;
15114            resourceFile = afterCodeFile;
15115
15116            // Reflect the rename in scanned details
15117            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15118            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15119                    afterCodeFile, pkg.baseCodePath));
15120            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15121                    afterCodeFile, pkg.splitCodePaths));
15122
15123            // Reflect the rename in app info
15124            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15125            pkg.setApplicationInfoCodePath(pkg.codePath);
15126            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15127            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15128            pkg.setApplicationInfoResourcePath(pkg.codePath);
15129            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15130            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15131
15132            return true;
15133        }
15134
15135        int doPostInstall(int status, int uid) {
15136            if (status != PackageManager.INSTALL_SUCCEEDED) {
15137                cleanUp();
15138            }
15139            return status;
15140        }
15141
15142        @Override
15143        String getCodePath() {
15144            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15145        }
15146
15147        @Override
15148        String getResourcePath() {
15149            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15150        }
15151
15152        private boolean cleanUp() {
15153            if (codeFile == null || !codeFile.exists()) {
15154                return false;
15155            }
15156
15157            removeCodePathLI(codeFile);
15158
15159            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15160                resourceFile.delete();
15161            }
15162
15163            return true;
15164        }
15165
15166        void cleanUpResourcesLI() {
15167            // Try enumerating all code paths before deleting
15168            List<String> allCodePaths = Collections.EMPTY_LIST;
15169            if (codeFile != null && codeFile.exists()) {
15170                try {
15171                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15172                    allCodePaths = pkg.getAllCodePaths();
15173                } catch (PackageParserException e) {
15174                    // Ignored; we tried our best
15175                }
15176            }
15177
15178            cleanUp();
15179            removeDexFiles(allCodePaths, instructionSets);
15180        }
15181
15182        boolean doPostDeleteLI(boolean delete) {
15183            // XXX err, shouldn't we respect the delete flag?
15184            cleanUpResourcesLI();
15185            return true;
15186        }
15187    }
15188
15189    private boolean isAsecExternal(String cid) {
15190        final String asecPath = PackageHelper.getSdFilesystem(cid);
15191        return !asecPath.startsWith(mAsecInternalPath);
15192    }
15193
15194    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15195            PackageManagerException {
15196        if (copyRet < 0) {
15197            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15198                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15199                throw new PackageManagerException(copyRet, message);
15200            }
15201        }
15202    }
15203
15204    /**
15205     * Extract the StorageManagerService "container ID" from the full code path of an
15206     * .apk.
15207     */
15208    static String cidFromCodePath(String fullCodePath) {
15209        int eidx = fullCodePath.lastIndexOf("/");
15210        String subStr1 = fullCodePath.substring(0, eidx);
15211        int sidx = subStr1.lastIndexOf("/");
15212        return subStr1.substring(sidx+1, eidx);
15213    }
15214
15215    /**
15216     * Logic to handle installation of ASEC applications, including copying and
15217     * renaming logic.
15218     */
15219    class AsecInstallArgs extends InstallArgs {
15220        static final String RES_FILE_NAME = "pkg.apk";
15221        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15222
15223        String cid;
15224        String packagePath;
15225        String resourcePath;
15226
15227        /** New install */
15228        AsecInstallArgs(InstallParams params) {
15229            super(params.origin, params.move, params.observer, params.installFlags,
15230                    params.installerPackageName, params.volumeUuid,
15231                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15232                    params.grantedRuntimePermissions,
15233                    params.traceMethod, params.traceCookie, params.certificates,
15234                    params.installReason);
15235        }
15236
15237        /** Existing install */
15238        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15239                        boolean isExternal, boolean isForwardLocked) {
15240            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15241                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15242                    instructionSets, null, null, null, 0, null /*certificates*/,
15243                    PackageManager.INSTALL_REASON_UNKNOWN);
15244            // Hackily pretend we're still looking at a full code path
15245            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15246                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15247            }
15248
15249            // Extract cid from fullCodePath
15250            int eidx = fullCodePath.lastIndexOf("/");
15251            String subStr1 = fullCodePath.substring(0, eidx);
15252            int sidx = subStr1.lastIndexOf("/");
15253            cid = subStr1.substring(sidx+1, eidx);
15254            setMountPath(subStr1);
15255        }
15256
15257        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15258            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15259                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15260                    instructionSets, null, null, null, 0, null /*certificates*/,
15261                    PackageManager.INSTALL_REASON_UNKNOWN);
15262            this.cid = cid;
15263            setMountPath(PackageHelper.getSdDir(cid));
15264        }
15265
15266        void createCopyFile() {
15267            cid = mInstallerService.allocateExternalStageCidLegacy();
15268        }
15269
15270        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15271            if (origin.staged && origin.cid != null) {
15272                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15273                cid = origin.cid;
15274                setMountPath(PackageHelper.getSdDir(cid));
15275                return PackageManager.INSTALL_SUCCEEDED;
15276            }
15277
15278            if (temp) {
15279                createCopyFile();
15280            } else {
15281                /*
15282                 * Pre-emptively destroy the container since it's destroyed if
15283                 * copying fails due to it existing anyway.
15284                 */
15285                PackageHelper.destroySdDir(cid);
15286            }
15287
15288            final String newMountPath = imcs.copyPackageToContainer(
15289                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15290                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15291
15292            if (newMountPath != null) {
15293                setMountPath(newMountPath);
15294                return PackageManager.INSTALL_SUCCEEDED;
15295            } else {
15296                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15297            }
15298        }
15299
15300        @Override
15301        String getCodePath() {
15302            return packagePath;
15303        }
15304
15305        @Override
15306        String getResourcePath() {
15307            return resourcePath;
15308        }
15309
15310        int doPreInstall(int status) {
15311            if (status != PackageManager.INSTALL_SUCCEEDED) {
15312                // Destroy container
15313                PackageHelper.destroySdDir(cid);
15314            } else {
15315                boolean mounted = PackageHelper.isContainerMounted(cid);
15316                if (!mounted) {
15317                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15318                            Process.SYSTEM_UID);
15319                    if (newMountPath != null) {
15320                        setMountPath(newMountPath);
15321                    } else {
15322                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15323                    }
15324                }
15325            }
15326            return status;
15327        }
15328
15329        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15330            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15331            String newMountPath = null;
15332            if (PackageHelper.isContainerMounted(cid)) {
15333                // Unmount the container
15334                if (!PackageHelper.unMountSdDir(cid)) {
15335                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15336                    return false;
15337                }
15338            }
15339            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15340                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15341                        " which might be stale. Will try to clean up.");
15342                // Clean up the stale container and proceed to recreate.
15343                if (!PackageHelper.destroySdDir(newCacheId)) {
15344                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15345                    return false;
15346                }
15347                // Successfully cleaned up stale container. Try to rename again.
15348                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15349                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15350                            + " inspite of cleaning it up.");
15351                    return false;
15352                }
15353            }
15354            if (!PackageHelper.isContainerMounted(newCacheId)) {
15355                Slog.w(TAG, "Mounting container " + newCacheId);
15356                newMountPath = PackageHelper.mountSdDir(newCacheId,
15357                        getEncryptKey(), Process.SYSTEM_UID);
15358            } else {
15359                newMountPath = PackageHelper.getSdDir(newCacheId);
15360            }
15361            if (newMountPath == null) {
15362                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15363                return false;
15364            }
15365            Log.i(TAG, "Succesfully renamed " + cid +
15366                    " to " + newCacheId +
15367                    " at new path: " + newMountPath);
15368            cid = newCacheId;
15369
15370            final File beforeCodeFile = new File(packagePath);
15371            setMountPath(newMountPath);
15372            final File afterCodeFile = new File(packagePath);
15373
15374            // Reflect the rename in scanned details
15375            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15376            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15377                    afterCodeFile, pkg.baseCodePath));
15378            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15379                    afterCodeFile, pkg.splitCodePaths));
15380
15381            // Reflect the rename in app info
15382            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15383            pkg.setApplicationInfoCodePath(pkg.codePath);
15384            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15385            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15386            pkg.setApplicationInfoResourcePath(pkg.codePath);
15387            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15388            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15389
15390            return true;
15391        }
15392
15393        private void setMountPath(String mountPath) {
15394            final File mountFile = new File(mountPath);
15395
15396            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15397            if (monolithicFile.exists()) {
15398                packagePath = monolithicFile.getAbsolutePath();
15399                if (isFwdLocked()) {
15400                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15401                } else {
15402                    resourcePath = packagePath;
15403                }
15404            } else {
15405                packagePath = mountFile.getAbsolutePath();
15406                resourcePath = packagePath;
15407            }
15408        }
15409
15410        int doPostInstall(int status, int uid) {
15411            if (status != PackageManager.INSTALL_SUCCEEDED) {
15412                cleanUp();
15413            } else {
15414                final int groupOwner;
15415                final String protectedFile;
15416                if (isFwdLocked()) {
15417                    groupOwner = UserHandle.getSharedAppGid(uid);
15418                    protectedFile = RES_FILE_NAME;
15419                } else {
15420                    groupOwner = -1;
15421                    protectedFile = null;
15422                }
15423
15424                if (uid < Process.FIRST_APPLICATION_UID
15425                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15426                    Slog.e(TAG, "Failed to finalize " + cid);
15427                    PackageHelper.destroySdDir(cid);
15428                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15429                }
15430
15431                boolean mounted = PackageHelper.isContainerMounted(cid);
15432                if (!mounted) {
15433                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15434                }
15435            }
15436            return status;
15437        }
15438
15439        private void cleanUp() {
15440            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15441
15442            // Destroy secure container
15443            PackageHelper.destroySdDir(cid);
15444        }
15445
15446        private List<String> getAllCodePaths() {
15447            final File codeFile = new File(getCodePath());
15448            if (codeFile != null && codeFile.exists()) {
15449                try {
15450                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15451                    return pkg.getAllCodePaths();
15452                } catch (PackageParserException e) {
15453                    // Ignored; we tried our best
15454                }
15455            }
15456            return Collections.EMPTY_LIST;
15457        }
15458
15459        void cleanUpResourcesLI() {
15460            // Enumerate all code paths before deleting
15461            cleanUpResourcesLI(getAllCodePaths());
15462        }
15463
15464        private void cleanUpResourcesLI(List<String> allCodePaths) {
15465            cleanUp();
15466            removeDexFiles(allCodePaths, instructionSets);
15467        }
15468
15469        String getPackageName() {
15470            return getAsecPackageName(cid);
15471        }
15472
15473        boolean doPostDeleteLI(boolean delete) {
15474            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15475            final List<String> allCodePaths = getAllCodePaths();
15476            boolean mounted = PackageHelper.isContainerMounted(cid);
15477            if (mounted) {
15478                // Unmount first
15479                if (PackageHelper.unMountSdDir(cid)) {
15480                    mounted = false;
15481                }
15482            }
15483            if (!mounted && delete) {
15484                cleanUpResourcesLI(allCodePaths);
15485            }
15486            return !mounted;
15487        }
15488
15489        @Override
15490        int doPreCopy() {
15491            if (isFwdLocked()) {
15492                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15493                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15494                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15495                }
15496            }
15497
15498            return PackageManager.INSTALL_SUCCEEDED;
15499        }
15500
15501        @Override
15502        int doPostCopy(int uid) {
15503            if (isFwdLocked()) {
15504                if (uid < Process.FIRST_APPLICATION_UID
15505                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15506                                RES_FILE_NAME)) {
15507                    Slog.e(TAG, "Failed to finalize " + cid);
15508                    PackageHelper.destroySdDir(cid);
15509                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15510                }
15511            }
15512
15513            return PackageManager.INSTALL_SUCCEEDED;
15514        }
15515    }
15516
15517    /**
15518     * Logic to handle movement of existing installed applications.
15519     */
15520    class MoveInstallArgs extends InstallArgs {
15521        private File codeFile;
15522        private File resourceFile;
15523
15524        /** New install */
15525        MoveInstallArgs(InstallParams params) {
15526            super(params.origin, params.move, params.observer, params.installFlags,
15527                    params.installerPackageName, params.volumeUuid,
15528                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15529                    params.grantedRuntimePermissions,
15530                    params.traceMethod, params.traceCookie, params.certificates,
15531                    params.installReason);
15532        }
15533
15534        int copyApk(IMediaContainerService imcs, boolean temp) {
15535            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15536                    + move.fromUuid + " to " + move.toUuid);
15537            synchronized (mInstaller) {
15538                try {
15539                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15540                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15541                } catch (InstallerException e) {
15542                    Slog.w(TAG, "Failed to move app", e);
15543                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15544                }
15545            }
15546
15547            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15548            resourceFile = codeFile;
15549            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15550
15551            return PackageManager.INSTALL_SUCCEEDED;
15552        }
15553
15554        int doPreInstall(int status) {
15555            if (status != PackageManager.INSTALL_SUCCEEDED) {
15556                cleanUp(move.toUuid);
15557            }
15558            return status;
15559        }
15560
15561        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15562            if (status != PackageManager.INSTALL_SUCCEEDED) {
15563                cleanUp(move.toUuid);
15564                return false;
15565            }
15566
15567            // Reflect the move in app info
15568            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15569            pkg.setApplicationInfoCodePath(pkg.codePath);
15570            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15571            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15572            pkg.setApplicationInfoResourcePath(pkg.codePath);
15573            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15574            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15575
15576            return true;
15577        }
15578
15579        int doPostInstall(int status, int uid) {
15580            if (status == PackageManager.INSTALL_SUCCEEDED) {
15581                cleanUp(move.fromUuid);
15582            } else {
15583                cleanUp(move.toUuid);
15584            }
15585            return status;
15586        }
15587
15588        @Override
15589        String getCodePath() {
15590            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15591        }
15592
15593        @Override
15594        String getResourcePath() {
15595            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15596        }
15597
15598        private boolean cleanUp(String volumeUuid) {
15599            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15600                    move.dataAppName);
15601            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15602            final int[] userIds = sUserManager.getUserIds();
15603            synchronized (mInstallLock) {
15604                // Clean up both app data and code
15605                // All package moves are frozen until finished
15606                for (int userId : userIds) {
15607                    try {
15608                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15609                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15610                    } catch (InstallerException e) {
15611                        Slog.w(TAG, String.valueOf(e));
15612                    }
15613                }
15614                removeCodePathLI(codeFile);
15615            }
15616            return true;
15617        }
15618
15619        void cleanUpResourcesLI() {
15620            throw new UnsupportedOperationException();
15621        }
15622
15623        boolean doPostDeleteLI(boolean delete) {
15624            throw new UnsupportedOperationException();
15625        }
15626    }
15627
15628    static String getAsecPackageName(String packageCid) {
15629        int idx = packageCid.lastIndexOf("-");
15630        if (idx == -1) {
15631            return packageCid;
15632        }
15633        return packageCid.substring(0, idx);
15634    }
15635
15636    // Utility method used to create code paths based on package name and available index.
15637    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15638        String idxStr = "";
15639        int idx = 1;
15640        // Fall back to default value of idx=1 if prefix is not
15641        // part of oldCodePath
15642        if (oldCodePath != null) {
15643            String subStr = oldCodePath;
15644            // Drop the suffix right away
15645            if (suffix != null && subStr.endsWith(suffix)) {
15646                subStr = subStr.substring(0, subStr.length() - suffix.length());
15647            }
15648            // If oldCodePath already contains prefix find out the
15649            // ending index to either increment or decrement.
15650            int sidx = subStr.lastIndexOf(prefix);
15651            if (sidx != -1) {
15652                subStr = subStr.substring(sidx + prefix.length());
15653                if (subStr != null) {
15654                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15655                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15656                    }
15657                    try {
15658                        idx = Integer.parseInt(subStr);
15659                        if (idx <= 1) {
15660                            idx++;
15661                        } else {
15662                            idx--;
15663                        }
15664                    } catch(NumberFormatException e) {
15665                    }
15666                }
15667            }
15668        }
15669        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15670        return prefix + idxStr;
15671    }
15672
15673    private File getNextCodePath(File targetDir, String packageName) {
15674        File result;
15675        SecureRandom random = new SecureRandom();
15676        byte[] bytes = new byte[16];
15677        do {
15678            random.nextBytes(bytes);
15679            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15680            result = new File(targetDir, packageName + "-" + suffix);
15681        } while (result.exists());
15682        return result;
15683    }
15684
15685    // Utility method that returns the relative package path with respect
15686    // to the installation directory. Like say for /data/data/com.test-1.apk
15687    // string com.test-1 is returned.
15688    static String deriveCodePathName(String codePath) {
15689        if (codePath == null) {
15690            return null;
15691        }
15692        final File codeFile = new File(codePath);
15693        final String name = codeFile.getName();
15694        if (codeFile.isDirectory()) {
15695            return name;
15696        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15697            final int lastDot = name.lastIndexOf('.');
15698            return name.substring(0, lastDot);
15699        } else {
15700            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15701            return null;
15702        }
15703    }
15704
15705    static class PackageInstalledInfo {
15706        String name;
15707        int uid;
15708        // The set of users that originally had this package installed.
15709        int[] origUsers;
15710        // The set of users that now have this package installed.
15711        int[] newUsers;
15712        PackageParser.Package pkg;
15713        int returnCode;
15714        String returnMsg;
15715        PackageRemovedInfo removedInfo;
15716        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15717
15718        public void setError(int code, String msg) {
15719            setReturnCode(code);
15720            setReturnMessage(msg);
15721            Slog.w(TAG, msg);
15722        }
15723
15724        public void setError(String msg, PackageParserException e) {
15725            setReturnCode(e.error);
15726            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15727            Slog.w(TAG, msg, e);
15728        }
15729
15730        public void setError(String msg, PackageManagerException e) {
15731            returnCode = e.error;
15732            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15733            Slog.w(TAG, msg, e);
15734        }
15735
15736        public void setReturnCode(int returnCode) {
15737            this.returnCode = returnCode;
15738            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15739            for (int i = 0; i < childCount; i++) {
15740                addedChildPackages.valueAt(i).returnCode = returnCode;
15741            }
15742        }
15743
15744        private void setReturnMessage(String returnMsg) {
15745            this.returnMsg = returnMsg;
15746            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15747            for (int i = 0; i < childCount; i++) {
15748                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15749            }
15750        }
15751
15752        // In some error cases we want to convey more info back to the observer
15753        String origPackage;
15754        String origPermission;
15755    }
15756
15757    /*
15758     * Install a non-existing package.
15759     */
15760    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15761            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15762            PackageInstalledInfo res, int installReason) {
15763        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15764
15765        // Remember this for later, in case we need to rollback this install
15766        String pkgName = pkg.packageName;
15767
15768        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15769
15770        synchronized(mPackages) {
15771            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15772            if (renamedPackage != null) {
15773                // A package with the same name is already installed, though
15774                // it has been renamed to an older name.  The package we
15775                // are trying to install should be installed as an update to
15776                // the existing one, but that has not been requested, so bail.
15777                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15778                        + " without first uninstalling package running as "
15779                        + renamedPackage);
15780                return;
15781            }
15782            if (mPackages.containsKey(pkgName)) {
15783                // Don't allow installation over an existing package with the same name.
15784                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15785                        + " without first uninstalling.");
15786                return;
15787            }
15788        }
15789
15790        try {
15791            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15792                    System.currentTimeMillis(), user);
15793
15794            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15795
15796            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15797                prepareAppDataAfterInstallLIF(newPackage);
15798
15799            } else {
15800                // Remove package from internal structures, but keep around any
15801                // data that might have already existed
15802                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15803                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15804            }
15805        } catch (PackageManagerException e) {
15806            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15807        }
15808
15809        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15810    }
15811
15812    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15813        // Can't rotate keys during boot or if sharedUser.
15814        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15815                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15816            return false;
15817        }
15818        // app is using upgradeKeySets; make sure all are valid
15819        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15820        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15821        for (int i = 0; i < upgradeKeySets.length; i++) {
15822            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15823                Slog.wtf(TAG, "Package "
15824                         + (oldPs.name != null ? oldPs.name : "<null>")
15825                         + " contains upgrade-key-set reference to unknown key-set: "
15826                         + upgradeKeySets[i]
15827                         + " reverting to signatures check.");
15828                return false;
15829            }
15830        }
15831        return true;
15832    }
15833
15834    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15835        // Upgrade keysets are being used.  Determine if new package has a superset of the
15836        // required keys.
15837        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15838        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15839        for (int i = 0; i < upgradeKeySets.length; i++) {
15840            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15841            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15842                return true;
15843            }
15844        }
15845        return false;
15846    }
15847
15848    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15849        try (DigestInputStream digestStream =
15850                new DigestInputStream(new FileInputStream(file), digest)) {
15851            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15852        }
15853    }
15854
15855    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15856            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15857            int installReason) {
15858        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15859
15860        final PackageParser.Package oldPackage;
15861        final String pkgName = pkg.packageName;
15862        final int[] allUsers;
15863        final int[] installedUsers;
15864
15865        synchronized(mPackages) {
15866            oldPackage = mPackages.get(pkgName);
15867            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15868
15869            // don't allow upgrade to target a release SDK from a pre-release SDK
15870            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15871                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15872            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15873                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15874            if (oldTargetsPreRelease
15875                    && !newTargetsPreRelease
15876                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15877                Slog.w(TAG, "Can't install package targeting released sdk");
15878                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15879                return;
15880            }
15881
15882            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15883
15884            // don't allow an upgrade from full to ephemeral
15885            if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) {
15886                // can't downgrade from full to instant
15887                Slog.w(TAG, "Can't replace app with instant app: " + pkgName);
15888                res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15889                return;
15890            }
15891
15892            // verify signatures are valid
15893            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15894                if (!checkUpgradeKeySetLP(ps, pkg)) {
15895                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15896                            "New package not signed by keys specified by upgrade-keysets: "
15897                                    + pkgName);
15898                    return;
15899                }
15900            } else {
15901                // default to original signature matching
15902                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15903                        != PackageManager.SIGNATURE_MATCH) {
15904                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15905                            "New package has a different signature: " + pkgName);
15906                    return;
15907                }
15908            }
15909
15910            // don't allow a system upgrade unless the upgrade hash matches
15911            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15912                byte[] digestBytes = null;
15913                try {
15914                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15915                    updateDigest(digest, new File(pkg.baseCodePath));
15916                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15917                        for (String path : pkg.splitCodePaths) {
15918                            updateDigest(digest, new File(path));
15919                        }
15920                    }
15921                    digestBytes = digest.digest();
15922                } catch (NoSuchAlgorithmException | IOException e) {
15923                    res.setError(INSTALL_FAILED_INVALID_APK,
15924                            "Could not compute hash: " + pkgName);
15925                    return;
15926                }
15927                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15928                    res.setError(INSTALL_FAILED_INVALID_APK,
15929                            "New package fails restrict-update check: " + pkgName);
15930                    return;
15931                }
15932                // retain upgrade restriction
15933                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15934            }
15935
15936            // Check for shared user id changes
15937            String invalidPackageName =
15938                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15939            if (invalidPackageName != null) {
15940                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15941                        "Package " + invalidPackageName + " tried to change user "
15942                                + oldPackage.mSharedUserId);
15943                return;
15944            }
15945
15946            // In case of rollback, remember per-user/profile install state
15947            allUsers = sUserManager.getUserIds();
15948            installedUsers = ps.queryInstalledUsers(allUsers, true);
15949        }
15950
15951        // Update what is removed
15952        res.removedInfo = new PackageRemovedInfo();
15953        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15954        res.removedInfo.removedPackage = oldPackage.packageName;
15955        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15956        res.removedInfo.isUpdate = true;
15957        res.removedInfo.origUsers = installedUsers;
15958        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15959        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15960        for (int i = 0; i < installedUsers.length; i++) {
15961            final int userId = installedUsers[i];
15962            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15963        }
15964
15965        final int childCount = (oldPackage.childPackages != null)
15966                ? oldPackage.childPackages.size() : 0;
15967        for (int i = 0; i < childCount; i++) {
15968            boolean childPackageUpdated = false;
15969            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15970            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15971            if (res.addedChildPackages != null) {
15972                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15973                if (childRes != null) {
15974                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15975                    childRes.removedInfo.removedPackage = childPkg.packageName;
15976                    childRes.removedInfo.isUpdate = true;
15977                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15978                    childPackageUpdated = true;
15979                }
15980            }
15981            if (!childPackageUpdated) {
15982                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15983                childRemovedRes.removedPackage = childPkg.packageName;
15984                childRemovedRes.isUpdate = false;
15985                childRemovedRes.dataRemoved = true;
15986                synchronized (mPackages) {
15987                    if (childPs != null) {
15988                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15989                    }
15990                }
15991                if (res.removedInfo.removedChildPackages == null) {
15992                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15993                }
15994                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15995            }
15996        }
15997
15998        boolean sysPkg = (isSystemApp(oldPackage));
15999        if (sysPkg) {
16000            // Set the system/privileged flags as needed
16001            final boolean privileged =
16002                    (oldPackage.applicationInfo.privateFlags
16003                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16004            final int systemPolicyFlags = policyFlags
16005                    | PackageParser.PARSE_IS_SYSTEM
16006                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16007
16008            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16009                    user, allUsers, installerPackageName, res, installReason);
16010        } else {
16011            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16012                    user, allUsers, installerPackageName, res, installReason);
16013        }
16014    }
16015
16016    public List<String> getPreviousCodePaths(String packageName) {
16017        final PackageSetting ps = mSettings.mPackages.get(packageName);
16018        final List<String> result = new ArrayList<String>();
16019        if (ps != null && ps.oldCodePaths != null) {
16020            result.addAll(ps.oldCodePaths);
16021        }
16022        return result;
16023    }
16024
16025    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16026            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16027            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16028            int installReason) {
16029        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16030                + deletedPackage);
16031
16032        String pkgName = deletedPackage.packageName;
16033        boolean deletedPkg = true;
16034        boolean addedPkg = false;
16035        boolean updatedSettings = false;
16036        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16037        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16038                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16039
16040        final long origUpdateTime = (pkg.mExtras != null)
16041                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16042
16043        // First delete the existing package while retaining the data directory
16044        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16045                res.removedInfo, true, pkg)) {
16046            // If the existing package wasn't successfully deleted
16047            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16048            deletedPkg = false;
16049        } else {
16050            // Successfully deleted the old package; proceed with replace.
16051
16052            // If deleted package lived in a container, give users a chance to
16053            // relinquish resources before killing.
16054            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16055                if (DEBUG_INSTALL) {
16056                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16057                }
16058                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16059                final ArrayList<String> pkgList = new ArrayList<String>(1);
16060                pkgList.add(deletedPackage.applicationInfo.packageName);
16061                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16062            }
16063
16064            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16065                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16066            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16067
16068            try {
16069                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16070                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16071                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16072                        installReason);
16073
16074                // Update the in-memory copy of the previous code paths.
16075                PackageSetting ps = mSettings.mPackages.get(pkgName);
16076                if (!killApp) {
16077                    if (ps.oldCodePaths == null) {
16078                        ps.oldCodePaths = new ArraySet<>();
16079                    }
16080                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16081                    if (deletedPackage.splitCodePaths != null) {
16082                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16083                    }
16084                } else {
16085                    ps.oldCodePaths = null;
16086                }
16087                if (ps.childPackageNames != null) {
16088                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16089                        final String childPkgName = ps.childPackageNames.get(i);
16090                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16091                        childPs.oldCodePaths = ps.oldCodePaths;
16092                    }
16093                }
16094                // set instant app status, but, only if it's explicitly specified
16095                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16096                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16097                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16098                prepareAppDataAfterInstallLIF(newPackage);
16099                addedPkg = true;
16100            } catch (PackageManagerException e) {
16101                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16102            }
16103        }
16104
16105        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16106            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16107
16108            // Revert all internal state mutations and added folders for the failed install
16109            if (addedPkg) {
16110                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16111                        res.removedInfo, true, null);
16112            }
16113
16114            // Restore the old package
16115            if (deletedPkg) {
16116                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16117                File restoreFile = new File(deletedPackage.codePath);
16118                // Parse old package
16119                boolean oldExternal = isExternal(deletedPackage);
16120                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16121                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16122                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16123                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16124                try {
16125                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16126                            null);
16127                } catch (PackageManagerException e) {
16128                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16129                            + e.getMessage());
16130                    return;
16131                }
16132
16133                synchronized (mPackages) {
16134                    // Ensure the installer package name up to date
16135                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16136
16137                    // Update permissions for restored package
16138                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16139
16140                    mSettings.writeLPr();
16141                }
16142
16143                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16144            }
16145        } else {
16146            synchronized (mPackages) {
16147                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16148                if (ps != null) {
16149                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16150                    if (res.removedInfo.removedChildPackages != null) {
16151                        final int childCount = res.removedInfo.removedChildPackages.size();
16152                        // Iterate in reverse as we may modify the collection
16153                        for (int i = childCount - 1; i >= 0; i--) {
16154                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16155                            if (res.addedChildPackages.containsKey(childPackageName)) {
16156                                res.removedInfo.removedChildPackages.removeAt(i);
16157                            } else {
16158                                PackageRemovedInfo childInfo = res.removedInfo
16159                                        .removedChildPackages.valueAt(i);
16160                                childInfo.removedForAllUsers = mPackages.get(
16161                                        childInfo.removedPackage) == null;
16162                            }
16163                        }
16164                    }
16165                }
16166            }
16167        }
16168    }
16169
16170    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16171            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16172            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16173            int installReason) {
16174        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16175                + ", old=" + deletedPackage);
16176
16177        final boolean disabledSystem;
16178
16179        // Remove existing system package
16180        removePackageLI(deletedPackage, true);
16181
16182        synchronized (mPackages) {
16183            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16184        }
16185        if (!disabledSystem) {
16186            // We didn't need to disable the .apk as a current system package,
16187            // which means we are replacing another update that is already
16188            // installed.  We need to make sure to delete the older one's .apk.
16189            res.removedInfo.args = createInstallArgsForExisting(0,
16190                    deletedPackage.applicationInfo.getCodePath(),
16191                    deletedPackage.applicationInfo.getResourcePath(),
16192                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16193        } else {
16194            res.removedInfo.args = null;
16195        }
16196
16197        // Successfully disabled the old package. Now proceed with re-installation
16198        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16199                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16200        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16201
16202        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16203        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16204                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16205
16206        PackageParser.Package newPackage = null;
16207        try {
16208            // Add the package to the internal data structures
16209            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16210
16211            // Set the update and install times
16212            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16213            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16214                    System.currentTimeMillis());
16215
16216            // Update the package dynamic state if succeeded
16217            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16218                // Now that the install succeeded make sure we remove data
16219                // directories for any child package the update removed.
16220                final int deletedChildCount = (deletedPackage.childPackages != null)
16221                        ? deletedPackage.childPackages.size() : 0;
16222                final int newChildCount = (newPackage.childPackages != null)
16223                        ? newPackage.childPackages.size() : 0;
16224                for (int i = 0; i < deletedChildCount; i++) {
16225                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16226                    boolean childPackageDeleted = true;
16227                    for (int j = 0; j < newChildCount; j++) {
16228                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16229                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16230                            childPackageDeleted = false;
16231                            break;
16232                        }
16233                    }
16234                    if (childPackageDeleted) {
16235                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16236                                deletedChildPkg.packageName);
16237                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16238                            PackageRemovedInfo removedChildRes = res.removedInfo
16239                                    .removedChildPackages.get(deletedChildPkg.packageName);
16240                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16241                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16242                        }
16243                    }
16244                }
16245
16246                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16247                        installReason);
16248                prepareAppDataAfterInstallLIF(newPackage);
16249            }
16250        } catch (PackageManagerException e) {
16251            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16252            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16253        }
16254
16255        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16256            // Re installation failed. Restore old information
16257            // Remove new pkg information
16258            if (newPackage != null) {
16259                removeInstalledPackageLI(newPackage, true);
16260            }
16261            // Add back the old system package
16262            try {
16263                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16264            } catch (PackageManagerException e) {
16265                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16266            }
16267
16268            synchronized (mPackages) {
16269                if (disabledSystem) {
16270                    enableSystemPackageLPw(deletedPackage);
16271                }
16272
16273                // Ensure the installer package name up to date
16274                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16275
16276                // Update permissions for restored package
16277                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16278
16279                mSettings.writeLPr();
16280            }
16281
16282            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16283                    + " after failed upgrade");
16284        }
16285    }
16286
16287    /**
16288     * Checks whether the parent or any of the child packages have a change shared
16289     * user. For a package to be a valid update the shred users of the parent and
16290     * the children should match. We may later support changing child shared users.
16291     * @param oldPkg The updated package.
16292     * @param newPkg The update package.
16293     * @return The shared user that change between the versions.
16294     */
16295    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16296            PackageParser.Package newPkg) {
16297        // Check parent shared user
16298        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16299            return newPkg.packageName;
16300        }
16301        // Check child shared users
16302        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16303        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16304        for (int i = 0; i < newChildCount; i++) {
16305            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16306            // If this child was present, did it have the same shared user?
16307            for (int j = 0; j < oldChildCount; j++) {
16308                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16309                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16310                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16311                    return newChildPkg.packageName;
16312                }
16313            }
16314        }
16315        return null;
16316    }
16317
16318    private void removeNativeBinariesLI(PackageSetting ps) {
16319        // Remove the lib path for the parent package
16320        if (ps != null) {
16321            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16322            // Remove the lib path for the child packages
16323            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16324            for (int i = 0; i < childCount; i++) {
16325                PackageSetting childPs = null;
16326                synchronized (mPackages) {
16327                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16328                }
16329                if (childPs != null) {
16330                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16331                            .legacyNativeLibraryPathString);
16332                }
16333            }
16334        }
16335    }
16336
16337    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16338        // Enable the parent package
16339        mSettings.enableSystemPackageLPw(pkg.packageName);
16340        // Enable the child packages
16341        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16342        for (int i = 0; i < childCount; i++) {
16343            PackageParser.Package childPkg = pkg.childPackages.get(i);
16344            mSettings.enableSystemPackageLPw(childPkg.packageName);
16345        }
16346    }
16347
16348    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16349            PackageParser.Package newPkg) {
16350        // Disable the parent package (parent always replaced)
16351        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16352        // Disable the child packages
16353        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16354        for (int i = 0; i < childCount; i++) {
16355            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16356            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16357            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16358        }
16359        return disabled;
16360    }
16361
16362    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16363            String installerPackageName) {
16364        // Enable the parent package
16365        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16366        // Enable the child packages
16367        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16368        for (int i = 0; i < childCount; i++) {
16369            PackageParser.Package childPkg = pkg.childPackages.get(i);
16370            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16371        }
16372    }
16373
16374    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16375        // Collect all used permissions in the UID
16376        ArraySet<String> usedPermissions = new ArraySet<>();
16377        final int packageCount = su.packages.size();
16378        for (int i = 0; i < packageCount; i++) {
16379            PackageSetting ps = su.packages.valueAt(i);
16380            if (ps.pkg == null) {
16381                continue;
16382            }
16383            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16384            for (int j = 0; j < requestedPermCount; j++) {
16385                String permission = ps.pkg.requestedPermissions.get(j);
16386                BasePermission bp = mSettings.mPermissions.get(permission);
16387                if (bp != null) {
16388                    usedPermissions.add(permission);
16389                }
16390            }
16391        }
16392
16393        PermissionsState permissionsState = su.getPermissionsState();
16394        // Prune install permissions
16395        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16396        final int installPermCount = installPermStates.size();
16397        for (int i = installPermCount - 1; i >= 0;  i--) {
16398            PermissionState permissionState = installPermStates.get(i);
16399            if (!usedPermissions.contains(permissionState.getName())) {
16400                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16401                if (bp != null) {
16402                    permissionsState.revokeInstallPermission(bp);
16403                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16404                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16405                }
16406            }
16407        }
16408
16409        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16410
16411        // Prune runtime permissions
16412        for (int userId : allUserIds) {
16413            List<PermissionState> runtimePermStates = permissionsState
16414                    .getRuntimePermissionStates(userId);
16415            final int runtimePermCount = runtimePermStates.size();
16416            for (int i = runtimePermCount - 1; i >= 0; i--) {
16417                PermissionState permissionState = runtimePermStates.get(i);
16418                if (!usedPermissions.contains(permissionState.getName())) {
16419                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16420                    if (bp != null) {
16421                        permissionsState.revokeRuntimePermission(bp, userId);
16422                        permissionsState.updatePermissionFlags(bp, userId,
16423                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16424                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16425                                runtimePermissionChangedUserIds, userId);
16426                    }
16427                }
16428            }
16429        }
16430
16431        return runtimePermissionChangedUserIds;
16432    }
16433
16434    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16435            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16436        // Update the parent package setting
16437        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16438                res, user, installReason);
16439        // Update the child packages setting
16440        final int childCount = (newPackage.childPackages != null)
16441                ? newPackage.childPackages.size() : 0;
16442        for (int i = 0; i < childCount; i++) {
16443            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16444            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16445            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16446                    childRes.origUsers, childRes, user, installReason);
16447        }
16448    }
16449
16450    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16451            String installerPackageName, int[] allUsers, int[] installedForUsers,
16452            PackageInstalledInfo res, UserHandle user, int installReason) {
16453        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16454
16455        String pkgName = newPackage.packageName;
16456        synchronized (mPackages) {
16457            //write settings. the installStatus will be incomplete at this stage.
16458            //note that the new package setting would have already been
16459            //added to mPackages. It hasn't been persisted yet.
16460            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16461            // TODO: Remove this write? It's also written at the end of this method
16462            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16463            mSettings.writeLPr();
16464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16465        }
16466
16467        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16468        synchronized (mPackages) {
16469            updatePermissionsLPw(newPackage.packageName, newPackage,
16470                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16471                            ? UPDATE_PERMISSIONS_ALL : 0));
16472            // For system-bundled packages, we assume that installing an upgraded version
16473            // of the package implies that the user actually wants to run that new code,
16474            // so we enable the package.
16475            PackageSetting ps = mSettings.mPackages.get(pkgName);
16476            final int userId = user.getIdentifier();
16477            if (ps != null) {
16478                if (isSystemApp(newPackage)) {
16479                    if (DEBUG_INSTALL) {
16480                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16481                    }
16482                    // Enable system package for requested users
16483                    if (res.origUsers != null) {
16484                        for (int origUserId : res.origUsers) {
16485                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16486                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16487                                        origUserId, installerPackageName);
16488                            }
16489                        }
16490                    }
16491                    // Also convey the prior install/uninstall state
16492                    if (allUsers != null && installedForUsers != null) {
16493                        for (int currentUserId : allUsers) {
16494                            final boolean installed = ArrayUtils.contains(
16495                                    installedForUsers, currentUserId);
16496                            if (DEBUG_INSTALL) {
16497                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16498                            }
16499                            ps.setInstalled(installed, currentUserId);
16500                        }
16501                        // these install state changes will be persisted in the
16502                        // upcoming call to mSettings.writeLPr().
16503                    }
16504                }
16505                // It's implied that when a user requests installation, they want the app to be
16506                // installed and enabled.
16507                if (userId != UserHandle.USER_ALL) {
16508                    ps.setInstalled(true, userId);
16509                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16510                }
16511
16512                // When replacing an existing package, preserve the original install reason for all
16513                // users that had the package installed before.
16514                final Set<Integer> previousUserIds = new ArraySet<>();
16515                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16516                    final int installReasonCount = res.removedInfo.installReasons.size();
16517                    for (int i = 0; i < installReasonCount; i++) {
16518                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16519                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16520                        ps.setInstallReason(previousInstallReason, previousUserId);
16521                        previousUserIds.add(previousUserId);
16522                    }
16523                }
16524
16525                // Set install reason for users that are having the package newly installed.
16526                if (userId == UserHandle.USER_ALL) {
16527                    for (int currentUserId : sUserManager.getUserIds()) {
16528                        if (!previousUserIds.contains(currentUserId)) {
16529                            ps.setInstallReason(installReason, currentUserId);
16530                        }
16531                    }
16532                } else if (!previousUserIds.contains(userId)) {
16533                    ps.setInstallReason(installReason, userId);
16534                }
16535                mSettings.writeKernelMappingLPr(ps);
16536            }
16537            res.name = pkgName;
16538            res.uid = newPackage.applicationInfo.uid;
16539            res.pkg = newPackage;
16540            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16541            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16542            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16543            //to update install status
16544            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16545            mSettings.writeLPr();
16546            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16547        }
16548
16549        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16550    }
16551
16552    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16553        try {
16554            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16555            installPackageLI(args, res);
16556        } finally {
16557            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16558        }
16559    }
16560
16561    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16562        final int installFlags = args.installFlags;
16563        final String installerPackageName = args.installerPackageName;
16564        final String volumeUuid = args.volumeUuid;
16565        final File tmpPackageFile = new File(args.getCodePath());
16566        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16567        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16568                || (args.volumeUuid != null));
16569        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16570        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16571        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16572        boolean replace = false;
16573        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16574        if (args.move != null) {
16575            // moving a complete application; perform an initial scan on the new install location
16576            scanFlags |= SCAN_INITIAL;
16577        }
16578        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16579            scanFlags |= SCAN_DONT_KILL_APP;
16580        }
16581        if (instantApp) {
16582            scanFlags |= SCAN_AS_INSTANT_APP;
16583        }
16584        if (fullApp) {
16585            scanFlags |= SCAN_AS_FULL_APP;
16586        }
16587
16588        // Result object to be returned
16589        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16590
16591        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16592
16593        // Sanity check
16594        if (instantApp && (forwardLocked || onExternal)) {
16595            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16596                    + " external=" + onExternal);
16597            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16598            return;
16599        }
16600
16601        // Retrieve PackageSettings and parse package
16602        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16603                | PackageParser.PARSE_ENFORCE_CODE
16604                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16605                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16606                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16607                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16608        PackageParser pp = new PackageParser();
16609        pp.setSeparateProcesses(mSeparateProcesses);
16610        pp.setDisplayMetrics(mMetrics);
16611
16612        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16613        final PackageParser.Package pkg;
16614        try {
16615            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16616        } catch (PackageParserException e) {
16617            res.setError("Failed parse during installPackageLI", e);
16618            return;
16619        } finally {
16620            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16621        }
16622
16623//        // Ephemeral apps must have target SDK >= O.
16624//        // TODO: Update conditional and error message when O gets locked down
16625//        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16626//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16627//                    "Ephemeral apps must have target SDK version of at least O");
16628//            return;
16629//        }
16630
16631        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16632            // Static shared libraries have synthetic package names
16633            renameStaticSharedLibraryPackage(pkg);
16634
16635            // No static shared libs on external storage
16636            if (onExternal) {
16637                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16638                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16639                        "Packages declaring static-shared libs cannot be updated");
16640                return;
16641            }
16642        }
16643
16644        // If we are installing a clustered package add results for the children
16645        if (pkg.childPackages != null) {
16646            synchronized (mPackages) {
16647                final int childCount = pkg.childPackages.size();
16648                for (int i = 0; i < childCount; i++) {
16649                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16650                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16651                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16652                    childRes.pkg = childPkg;
16653                    childRes.name = childPkg.packageName;
16654                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16655                    if (childPs != null) {
16656                        childRes.origUsers = childPs.queryInstalledUsers(
16657                                sUserManager.getUserIds(), true);
16658                    }
16659                    if ((mPackages.containsKey(childPkg.packageName))) {
16660                        childRes.removedInfo = new PackageRemovedInfo();
16661                        childRes.removedInfo.removedPackage = childPkg.packageName;
16662                    }
16663                    if (res.addedChildPackages == null) {
16664                        res.addedChildPackages = new ArrayMap<>();
16665                    }
16666                    res.addedChildPackages.put(childPkg.packageName, childRes);
16667                }
16668            }
16669        }
16670
16671        // If package doesn't declare API override, mark that we have an install
16672        // time CPU ABI override.
16673        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16674            pkg.cpuAbiOverride = args.abiOverride;
16675        }
16676
16677        String pkgName = res.name = pkg.packageName;
16678        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16679            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16680                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16681                return;
16682            }
16683        }
16684
16685        try {
16686            // either use what we've been given or parse directly from the APK
16687            if (args.certificates != null) {
16688                try {
16689                    PackageParser.populateCertificates(pkg, args.certificates);
16690                } catch (PackageParserException e) {
16691                    // there was something wrong with the certificates we were given;
16692                    // try to pull them from the APK
16693                    PackageParser.collectCertificates(pkg, parseFlags);
16694                }
16695            } else {
16696                PackageParser.collectCertificates(pkg, parseFlags);
16697            }
16698        } catch (PackageParserException e) {
16699            res.setError("Failed collect during installPackageLI", e);
16700            return;
16701        }
16702
16703        // Get rid of all references to package scan path via parser.
16704        pp = null;
16705        String oldCodePath = null;
16706        boolean systemApp = false;
16707        synchronized (mPackages) {
16708            // Check if installing already existing package
16709            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16710                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16711                if (pkg.mOriginalPackages != null
16712                        && pkg.mOriginalPackages.contains(oldName)
16713                        && mPackages.containsKey(oldName)) {
16714                    // This package is derived from an original package,
16715                    // and this device has been updating from that original
16716                    // name.  We must continue using the original name, so
16717                    // rename the new package here.
16718                    pkg.setPackageName(oldName);
16719                    pkgName = pkg.packageName;
16720                    replace = true;
16721                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16722                            + oldName + " pkgName=" + pkgName);
16723                } else if (mPackages.containsKey(pkgName)) {
16724                    // This package, under its official name, already exists
16725                    // on the device; we should replace it.
16726                    replace = true;
16727                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16728                }
16729
16730                // Child packages are installed through the parent package
16731                if (pkg.parentPackage != null) {
16732                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16733                            "Package " + pkg.packageName + " is child of package "
16734                                    + pkg.parentPackage.parentPackage + ". Child packages "
16735                                    + "can be updated only through the parent package.");
16736                    return;
16737                }
16738
16739                if (replace) {
16740                    // Prevent apps opting out from runtime permissions
16741                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16742                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16743                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16744                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16745                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16746                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16747                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16748                                        + " doesn't support runtime permissions but the old"
16749                                        + " target SDK " + oldTargetSdk + " does.");
16750                        return;
16751                    }
16752
16753                    // Prevent installing of child packages
16754                    if (oldPackage.parentPackage != null) {
16755                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16756                                "Package " + pkg.packageName + " is child of package "
16757                                        + oldPackage.parentPackage + ". Child packages "
16758                                        + "can be updated only through the parent package.");
16759                        return;
16760                    }
16761                }
16762            }
16763
16764            PackageSetting ps = mSettings.mPackages.get(pkgName);
16765            if (ps != null) {
16766                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16767
16768                // Static shared libs have same package with different versions where
16769                // we internally use a synthetic package name to allow multiple versions
16770                // of the same package, therefore we need to compare signatures against
16771                // the package setting for the latest library version.
16772                PackageSetting signatureCheckPs = ps;
16773                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16774                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16775                    if (libraryEntry != null) {
16776                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16777                    }
16778                }
16779
16780                // Quick sanity check that we're signed correctly if updating;
16781                // we'll check this again later when scanning, but we want to
16782                // bail early here before tripping over redefined permissions.
16783                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16784                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16785                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16786                                + pkg.packageName + " upgrade keys do not match the "
16787                                + "previously installed version");
16788                        return;
16789                    }
16790                } else {
16791                    try {
16792                        verifySignaturesLP(signatureCheckPs, pkg);
16793                    } catch (PackageManagerException e) {
16794                        res.setError(e.error, e.getMessage());
16795                        return;
16796                    }
16797                }
16798
16799                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16800                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16801                    systemApp = (ps.pkg.applicationInfo.flags &
16802                            ApplicationInfo.FLAG_SYSTEM) != 0;
16803                }
16804                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16805            }
16806
16807            // Check whether the newly-scanned package wants to define an already-defined perm
16808            int N = pkg.permissions.size();
16809            for (int i = N-1; i >= 0; i--) {
16810                PackageParser.Permission perm = pkg.permissions.get(i);
16811                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16812                if (bp != null) {
16813                    // If the defining package is signed with our cert, it's okay.  This
16814                    // also includes the "updating the same package" case, of course.
16815                    // "updating same package" could also involve key-rotation.
16816                    final boolean sigsOk;
16817                    if (bp.sourcePackage.equals(pkg.packageName)
16818                            && (bp.packageSetting instanceof PackageSetting)
16819                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16820                                    scanFlags))) {
16821                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16822                    } else {
16823                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16824                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16825                    }
16826                    if (!sigsOk) {
16827                        // If the owning package is the system itself, we log but allow
16828                        // install to proceed; we fail the install on all other permission
16829                        // redefinitions.
16830                        if (!bp.sourcePackage.equals("android")) {
16831                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16832                                    + pkg.packageName + " attempting to redeclare permission "
16833                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16834                            res.origPermission = perm.info.name;
16835                            res.origPackage = bp.sourcePackage;
16836                            return;
16837                        } else {
16838                            Slog.w(TAG, "Package " + pkg.packageName
16839                                    + " attempting to redeclare system permission "
16840                                    + perm.info.name + "; ignoring new declaration");
16841                            pkg.permissions.remove(i);
16842                        }
16843                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16844                        // Prevent apps to change protection level to dangerous from any other
16845                        // type as this would allow a privilege escalation where an app adds a
16846                        // normal/signature permission in other app's group and later redefines
16847                        // it as dangerous leading to the group auto-grant.
16848                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16849                                == PermissionInfo.PROTECTION_DANGEROUS) {
16850                            if (bp != null && !bp.isRuntime()) {
16851                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16852                                        + "non-runtime permission " + perm.info.name
16853                                        + " to runtime; keeping old protection level");
16854                                perm.info.protectionLevel = bp.protectionLevel;
16855                            }
16856                        }
16857                    }
16858                }
16859            }
16860        }
16861
16862        if (systemApp) {
16863            if (onExternal) {
16864                // Abort update; system app can't be replaced with app on sdcard
16865                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16866                        "Cannot install updates to system apps on sdcard");
16867                return;
16868            } else if (instantApp) {
16869                // Abort update; system app can't be replaced with an instant app
16870                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16871                        "Cannot update a system app with an instant app");
16872                return;
16873            }
16874        }
16875
16876        if (args.move != null) {
16877            // We did an in-place move, so dex is ready to roll
16878            scanFlags |= SCAN_NO_DEX;
16879            scanFlags |= SCAN_MOVE;
16880
16881            synchronized (mPackages) {
16882                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16883                if (ps == null) {
16884                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16885                            "Missing settings for moved package " + pkgName);
16886                }
16887
16888                // We moved the entire application as-is, so bring over the
16889                // previously derived ABI information.
16890                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16891                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16892            }
16893
16894        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16895            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16896            scanFlags |= SCAN_NO_DEX;
16897
16898            try {
16899                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16900                    args.abiOverride : pkg.cpuAbiOverride);
16901                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16902                        true /*extractLibs*/, mAppLib32InstallDir);
16903            } catch (PackageManagerException pme) {
16904                Slog.e(TAG, "Error deriving application ABI", pme);
16905                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16906                return;
16907            }
16908
16909            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16910            // Do not run PackageDexOptimizer through the local performDexOpt
16911            // method because `pkg` may not be in `mPackages` yet.
16912            //
16913            // Also, don't fail application installs if the dexopt step fails.
16914            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16915                    null /* instructionSets */, false /* checkProfiles */,
16916                    getCompilerFilterForReason(REASON_INSTALL),
16917                    getOrCreateCompilerPackageStats(pkg));
16918            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16919
16920            // Notify BackgroundDexOptJobService that the package has been changed.
16921            // If this is an update of a package which used to fail to compile,
16922            // BDOS will remove it from its blacklist.
16923            // TODO: Layering violation
16924            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16925        }
16926
16927        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16928            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16929            return;
16930        }
16931
16932        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16933
16934        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16935                "installPackageLI")) {
16936            if (replace) {
16937                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16938                    // Static libs have a synthetic package name containing the version
16939                    // and cannot be updated as an update would get a new package name,
16940                    // unless this is the exact same version code which is useful for
16941                    // development.
16942                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16943                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16944                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16945                                + "static-shared libs cannot be updated");
16946                        return;
16947                    }
16948                }
16949                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16950                        installerPackageName, res, args.installReason);
16951            } else {
16952                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16953                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16954            }
16955        }
16956        synchronized (mPackages) {
16957            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16958            if (ps != null) {
16959                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16960            }
16961
16962            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16963            for (int i = 0; i < childCount; i++) {
16964                PackageParser.Package childPkg = pkg.childPackages.get(i);
16965                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16966                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16967                if (childPs != null) {
16968                    childRes.newUsers = childPs.queryInstalledUsers(
16969                            sUserManager.getUserIds(), true);
16970                }
16971            }
16972
16973            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16974                updateSequenceNumberLP(pkgName, res.newUsers);
16975            }
16976        }
16977    }
16978
16979    private void startIntentFilterVerifications(int userId, boolean replacing,
16980            PackageParser.Package pkg) {
16981        if (mIntentFilterVerifierComponent == null) {
16982            Slog.w(TAG, "No IntentFilter verification will not be done as "
16983                    + "there is no IntentFilterVerifier available!");
16984            return;
16985        }
16986
16987        final int verifierUid = getPackageUid(
16988                mIntentFilterVerifierComponent.getPackageName(),
16989                MATCH_DEBUG_TRIAGED_MISSING,
16990                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16991
16992        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16993        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16994        mHandler.sendMessage(msg);
16995
16996        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16997        for (int i = 0; i < childCount; i++) {
16998            PackageParser.Package childPkg = pkg.childPackages.get(i);
16999            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17000            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17001            mHandler.sendMessage(msg);
17002        }
17003    }
17004
17005    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17006            PackageParser.Package pkg) {
17007        int size = pkg.activities.size();
17008        if (size == 0) {
17009            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17010                    "No activity, so no need to verify any IntentFilter!");
17011            return;
17012        }
17013
17014        final boolean hasDomainURLs = hasDomainURLs(pkg);
17015        if (!hasDomainURLs) {
17016            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17017                    "No domain URLs, so no need to verify any IntentFilter!");
17018            return;
17019        }
17020
17021        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17022                + " if any IntentFilter from the " + size
17023                + " Activities needs verification ...");
17024
17025        int count = 0;
17026        final String packageName = pkg.packageName;
17027
17028        synchronized (mPackages) {
17029            // If this is a new install and we see that we've already run verification for this
17030            // package, we have nothing to do: it means the state was restored from backup.
17031            if (!replacing) {
17032                IntentFilterVerificationInfo ivi =
17033                        mSettings.getIntentFilterVerificationLPr(packageName);
17034                if (ivi != null) {
17035                    if (DEBUG_DOMAIN_VERIFICATION) {
17036                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17037                                + ivi.getStatusString());
17038                    }
17039                    return;
17040                }
17041            }
17042
17043            // If any filters need to be verified, then all need to be.
17044            boolean needToVerify = false;
17045            for (PackageParser.Activity a : pkg.activities) {
17046                for (ActivityIntentInfo filter : a.intents) {
17047                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17048                        if (DEBUG_DOMAIN_VERIFICATION) {
17049                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17050                        }
17051                        needToVerify = true;
17052                        break;
17053                    }
17054                }
17055            }
17056
17057            if (needToVerify) {
17058                final int verificationId = mIntentFilterVerificationToken++;
17059                for (PackageParser.Activity a : pkg.activities) {
17060                    for (ActivityIntentInfo filter : a.intents) {
17061                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17062                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17063                                    "Verification needed for IntentFilter:" + filter.toString());
17064                            mIntentFilterVerifier.addOneIntentFilterVerification(
17065                                    verifierUid, userId, verificationId, filter, packageName);
17066                            count++;
17067                        }
17068                    }
17069                }
17070            }
17071        }
17072
17073        if (count > 0) {
17074            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17075                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17076                    +  " for userId:" + userId);
17077            mIntentFilterVerifier.startVerifications(userId);
17078        } else {
17079            if (DEBUG_DOMAIN_VERIFICATION) {
17080                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17081            }
17082        }
17083    }
17084
17085    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17086        final ComponentName cn  = filter.activity.getComponentName();
17087        final String packageName = cn.getPackageName();
17088
17089        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17090                packageName);
17091        if (ivi == null) {
17092            return true;
17093        }
17094        int status = ivi.getStatus();
17095        switch (status) {
17096            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17097            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17098                return true;
17099
17100            default:
17101                // Nothing to do
17102                return false;
17103        }
17104    }
17105
17106    private static boolean isMultiArch(ApplicationInfo info) {
17107        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17108    }
17109
17110    private static boolean isExternal(PackageParser.Package pkg) {
17111        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17112    }
17113
17114    private static boolean isExternal(PackageSetting ps) {
17115        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17116    }
17117
17118    private static boolean isSystemApp(PackageParser.Package pkg) {
17119        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17120    }
17121
17122    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17123        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17124    }
17125
17126    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17127        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17128    }
17129
17130    private static boolean isSystemApp(PackageSetting ps) {
17131        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17132    }
17133
17134    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17135        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17136    }
17137
17138    private int packageFlagsToInstallFlags(PackageSetting ps) {
17139        int installFlags = 0;
17140        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17141            // This existing package was an external ASEC install when we have
17142            // the external flag without a UUID
17143            installFlags |= PackageManager.INSTALL_EXTERNAL;
17144        }
17145        if (ps.isForwardLocked()) {
17146            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17147        }
17148        return installFlags;
17149    }
17150
17151    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17152        if (isExternal(pkg)) {
17153            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17154                return StorageManager.UUID_PRIMARY_PHYSICAL;
17155            } else {
17156                return pkg.volumeUuid;
17157            }
17158        } else {
17159            return StorageManager.UUID_PRIVATE_INTERNAL;
17160        }
17161    }
17162
17163    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17164        if (isExternal(pkg)) {
17165            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17166                return mSettings.getExternalVersion();
17167            } else {
17168                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17169            }
17170        } else {
17171            return mSettings.getInternalVersion();
17172        }
17173    }
17174
17175    private void deleteTempPackageFiles() {
17176        final FilenameFilter filter = new FilenameFilter() {
17177            public boolean accept(File dir, String name) {
17178                return name.startsWith("vmdl") && name.endsWith(".tmp");
17179            }
17180        };
17181        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17182            file.delete();
17183        }
17184    }
17185
17186    @Override
17187    public void deletePackageAsUser(String packageName, int versionCode,
17188            IPackageDeleteObserver observer, int userId, int flags) {
17189        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17190                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17191    }
17192
17193    @Override
17194    public void deletePackageVersioned(VersionedPackage versionedPackage,
17195            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17196        mContext.enforceCallingOrSelfPermission(
17197                android.Manifest.permission.DELETE_PACKAGES, null);
17198        Preconditions.checkNotNull(versionedPackage);
17199        Preconditions.checkNotNull(observer);
17200        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17201                PackageManager.VERSION_CODE_HIGHEST,
17202                Integer.MAX_VALUE, "versionCode must be >= -1");
17203
17204        final String packageName = versionedPackage.getPackageName();
17205        // TODO: We will change version code to long, so in the new API it is long
17206        final int versionCode = (int) versionedPackage.getVersionCode();
17207        final String internalPackageName;
17208        synchronized (mPackages) {
17209            // Normalize package name to handle renamed packages and static libs
17210            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17211                    // TODO: We will change version code to long, so in the new API it is long
17212                    (int) versionedPackage.getVersionCode());
17213        }
17214
17215        final int uid = Binder.getCallingUid();
17216        if (!isOrphaned(internalPackageName)
17217                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17218            try {
17219                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17220                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17221                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17222                observer.onUserActionRequired(intent);
17223            } catch (RemoteException re) {
17224            }
17225            return;
17226        }
17227        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17228        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17229        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17230            mContext.enforceCallingOrSelfPermission(
17231                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17232                    "deletePackage for user " + userId);
17233        }
17234
17235        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17236            try {
17237                observer.onPackageDeleted(packageName,
17238                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17239            } catch (RemoteException re) {
17240            }
17241            return;
17242        }
17243
17244        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17245            try {
17246                observer.onPackageDeleted(packageName,
17247                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17248            } catch (RemoteException re) {
17249            }
17250            return;
17251        }
17252
17253        if (DEBUG_REMOVE) {
17254            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17255                    + " deleteAllUsers: " + deleteAllUsers + " version="
17256                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17257                    ? "VERSION_CODE_HIGHEST" : versionCode));
17258        }
17259        // Queue up an async operation since the package deletion may take a little while.
17260        mHandler.post(new Runnable() {
17261            public void run() {
17262                mHandler.removeCallbacks(this);
17263                int returnCode;
17264                if (!deleteAllUsers) {
17265                    returnCode = deletePackageX(internalPackageName, versionCode,
17266                            userId, deleteFlags);
17267                } else {
17268                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17269                            internalPackageName, users);
17270                    // If nobody is blocking uninstall, proceed with delete for all users
17271                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17272                        returnCode = deletePackageX(internalPackageName, versionCode,
17273                                userId, deleteFlags);
17274                    } else {
17275                        // Otherwise uninstall individually for users with blockUninstalls=false
17276                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17277                        for (int userId : users) {
17278                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17279                                returnCode = deletePackageX(internalPackageName, versionCode,
17280                                        userId, userFlags);
17281                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17282                                    Slog.w(TAG, "Package delete failed for user " + userId
17283                                            + ", returnCode " + returnCode);
17284                                }
17285                            }
17286                        }
17287                        // The app has only been marked uninstalled for certain users.
17288                        // We still need to report that delete was blocked
17289                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17290                    }
17291                }
17292                try {
17293                    observer.onPackageDeleted(packageName, returnCode, null);
17294                } catch (RemoteException e) {
17295                    Log.i(TAG, "Observer no longer exists.");
17296                } //end catch
17297            } //end run
17298        });
17299    }
17300
17301    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17302        if (pkg.staticSharedLibName != null) {
17303            return pkg.manifestPackageName;
17304        }
17305        return pkg.packageName;
17306    }
17307
17308    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17309        // Handle renamed packages
17310        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17311        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17312
17313        // Is this a static library?
17314        SparseArray<SharedLibraryEntry> versionedLib =
17315                mStaticLibsByDeclaringPackage.get(packageName);
17316        if (versionedLib == null || versionedLib.size() <= 0) {
17317            return packageName;
17318        }
17319
17320        // Figure out which lib versions the caller can see
17321        SparseIntArray versionsCallerCanSee = null;
17322        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17323        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17324                && callingAppId != Process.ROOT_UID) {
17325            versionsCallerCanSee = new SparseIntArray();
17326            String libName = versionedLib.valueAt(0).info.getName();
17327            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17328            if (uidPackages != null) {
17329                for (String uidPackage : uidPackages) {
17330                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17331                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17332                    if (libIdx >= 0) {
17333                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17334                        versionsCallerCanSee.append(libVersion, libVersion);
17335                    }
17336                }
17337            }
17338        }
17339
17340        // Caller can see nothing - done
17341        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17342            return packageName;
17343        }
17344
17345        // Find the version the caller can see and the app version code
17346        SharedLibraryEntry highestVersion = null;
17347        final int versionCount = versionedLib.size();
17348        for (int i = 0; i < versionCount; i++) {
17349            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17350            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17351                    libEntry.info.getVersion()) < 0) {
17352                continue;
17353            }
17354            // TODO: We will change version code to long, so in the new API it is long
17355            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17356            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17357                if (libVersionCode == versionCode) {
17358                    return libEntry.apk;
17359                }
17360            } else if (highestVersion == null) {
17361                highestVersion = libEntry;
17362            } else if (libVersionCode  > highestVersion.info
17363                    .getDeclaringPackage().getVersionCode()) {
17364                highestVersion = libEntry;
17365            }
17366        }
17367
17368        if (highestVersion != null) {
17369            return highestVersion.apk;
17370        }
17371
17372        return packageName;
17373    }
17374
17375    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17376        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17377              || callingUid == Process.SYSTEM_UID) {
17378            return true;
17379        }
17380        final int callingUserId = UserHandle.getUserId(callingUid);
17381        // If the caller installed the pkgName, then allow it to silently uninstall.
17382        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17383            return true;
17384        }
17385
17386        // Allow package verifier to silently uninstall.
17387        if (mRequiredVerifierPackage != null &&
17388                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17389            return true;
17390        }
17391
17392        // Allow package uninstaller to silently uninstall.
17393        if (mRequiredUninstallerPackage != null &&
17394                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17395            return true;
17396        }
17397
17398        // Allow storage manager to silently uninstall.
17399        if (mStorageManagerPackage != null &&
17400                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17401            return true;
17402        }
17403        return false;
17404    }
17405
17406    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17407        int[] result = EMPTY_INT_ARRAY;
17408        for (int userId : userIds) {
17409            if (getBlockUninstallForUser(packageName, userId)) {
17410                result = ArrayUtils.appendInt(result, userId);
17411            }
17412        }
17413        return result;
17414    }
17415
17416    @Override
17417    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17418        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17419    }
17420
17421    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17422        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17423                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17424        try {
17425            if (dpm != null) {
17426                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17427                        /* callingUserOnly =*/ false);
17428                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17429                        : deviceOwnerComponentName.getPackageName();
17430                // Does the package contains the device owner?
17431                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17432                // this check is probably not needed, since DO should be registered as a device
17433                // admin on some user too. (Original bug for this: b/17657954)
17434                if (packageName.equals(deviceOwnerPackageName)) {
17435                    return true;
17436                }
17437                // Does it contain a device admin for any user?
17438                int[] users;
17439                if (userId == UserHandle.USER_ALL) {
17440                    users = sUserManager.getUserIds();
17441                } else {
17442                    users = new int[]{userId};
17443                }
17444                for (int i = 0; i < users.length; ++i) {
17445                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17446                        return true;
17447                    }
17448                }
17449            }
17450        } catch (RemoteException e) {
17451        }
17452        return false;
17453    }
17454
17455    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17456        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17457    }
17458
17459    /**
17460     *  This method is an internal method that could be get invoked either
17461     *  to delete an installed package or to clean up a failed installation.
17462     *  After deleting an installed package, a broadcast is sent to notify any
17463     *  listeners that the package has been removed. For cleaning up a failed
17464     *  installation, the broadcast is not necessary since the package's
17465     *  installation wouldn't have sent the initial broadcast either
17466     *  The key steps in deleting a package are
17467     *  deleting the package information in internal structures like mPackages,
17468     *  deleting the packages base directories through installd
17469     *  updating mSettings to reflect current status
17470     *  persisting settings for later use
17471     *  sending a broadcast if necessary
17472     */
17473    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17474        final PackageRemovedInfo info = new PackageRemovedInfo();
17475        final boolean res;
17476
17477        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17478                ? UserHandle.USER_ALL : userId;
17479
17480        if (isPackageDeviceAdmin(packageName, removeUser)) {
17481            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17482            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17483        }
17484
17485        PackageSetting uninstalledPs = null;
17486
17487        // for the uninstall-updates case and restricted profiles, remember the per-
17488        // user handle installed state
17489        int[] allUsers;
17490        synchronized (mPackages) {
17491            uninstalledPs = mSettings.mPackages.get(packageName);
17492            if (uninstalledPs == null) {
17493                Slog.w(TAG, "Not removing non-existent package " + packageName);
17494                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17495            }
17496
17497            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17498                    && uninstalledPs.versionCode != versionCode) {
17499                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17500                        + uninstalledPs.versionCode + " != " + versionCode);
17501                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17502            }
17503
17504            // Static shared libs can be declared by any package, so let us not
17505            // allow removing a package if it provides a lib others depend on.
17506            PackageParser.Package pkg = mPackages.get(packageName);
17507            if (pkg != null && pkg.staticSharedLibName != null) {
17508                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17509                        pkg.staticSharedLibVersion);
17510                if (libEntry != null) {
17511                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17512                            libEntry.info, 0, userId);
17513                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17514                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17515                                + " hosting lib " + libEntry.info.getName() + " version "
17516                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17517                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17518                    }
17519                }
17520            }
17521
17522            allUsers = sUserManager.getUserIds();
17523            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17524        }
17525
17526        final int freezeUser;
17527        if (isUpdatedSystemApp(uninstalledPs)
17528                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17529            // We're downgrading a system app, which will apply to all users, so
17530            // freeze them all during the downgrade
17531            freezeUser = UserHandle.USER_ALL;
17532        } else {
17533            freezeUser = removeUser;
17534        }
17535
17536        synchronized (mInstallLock) {
17537            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17538            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17539                    deleteFlags, "deletePackageX")) {
17540                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17541                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17542            }
17543            synchronized (mPackages) {
17544                if (res) {
17545                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17546                            info.removedUsers);
17547                    updateSequenceNumberLP(packageName, info.removedUsers);
17548                }
17549            }
17550        }
17551
17552        if (res) {
17553            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17554            info.sendPackageRemovedBroadcasts(killApp);
17555            info.sendSystemPackageUpdatedBroadcasts();
17556            info.sendSystemPackageAppearedBroadcasts();
17557        }
17558        // Force a gc here.
17559        Runtime.getRuntime().gc();
17560        // Delete the resources here after sending the broadcast to let
17561        // other processes clean up before deleting resources.
17562        if (info.args != null) {
17563            synchronized (mInstallLock) {
17564                info.args.doPostDeleteLI(true);
17565            }
17566        }
17567
17568        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17569    }
17570
17571    class PackageRemovedInfo {
17572        String removedPackage;
17573        int uid = -1;
17574        int removedAppId = -1;
17575        int[] origUsers;
17576        int[] removedUsers = null;
17577        SparseArray<Integer> installReasons;
17578        boolean isRemovedPackageSystemUpdate = false;
17579        boolean isUpdate;
17580        boolean dataRemoved;
17581        boolean removedForAllUsers;
17582        boolean isStaticSharedLib;
17583        // Clean up resources deleted packages.
17584        InstallArgs args = null;
17585        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17586        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17587
17588        void sendPackageRemovedBroadcasts(boolean killApp) {
17589            sendPackageRemovedBroadcastInternal(killApp);
17590            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17591            for (int i = 0; i < childCount; i++) {
17592                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17593                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17594            }
17595        }
17596
17597        void sendSystemPackageUpdatedBroadcasts() {
17598            if (isRemovedPackageSystemUpdate) {
17599                sendSystemPackageUpdatedBroadcastsInternal();
17600                final int childCount = (removedChildPackages != null)
17601                        ? removedChildPackages.size() : 0;
17602                for (int i = 0; i < childCount; i++) {
17603                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17604                    if (childInfo.isRemovedPackageSystemUpdate) {
17605                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17606                    }
17607                }
17608            }
17609        }
17610
17611        void sendSystemPackageAppearedBroadcasts() {
17612            final int packageCount = (appearedChildPackages != null)
17613                    ? appearedChildPackages.size() : 0;
17614            for (int i = 0; i < packageCount; i++) {
17615                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17616                sendPackageAddedForNewUsers(installedInfo.name, true,
17617                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17618            }
17619        }
17620
17621        private void sendSystemPackageUpdatedBroadcastsInternal() {
17622            Bundle extras = new Bundle(2);
17623            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17624            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17625            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17626                    extras, 0, null, null, null);
17627            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17628                    extras, 0, null, null, null);
17629            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17630                    null, 0, removedPackage, null, null);
17631        }
17632
17633        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17634            // Don't send static shared library removal broadcasts as these
17635            // libs are visible only the the apps that depend on them an one
17636            // cannot remove the library if it has a dependency.
17637            if (isStaticSharedLib) {
17638                return;
17639            }
17640            Bundle extras = new Bundle(2);
17641            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17642            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17643            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17644            if (isUpdate || isRemovedPackageSystemUpdate) {
17645                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17646            }
17647            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17648            if (removedPackage != null) {
17649                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17650                        extras, 0, null, null, removedUsers);
17651                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17652                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17653                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17654                            null, null, removedUsers);
17655                }
17656            }
17657            if (removedAppId >= 0) {
17658                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17659                        removedUsers);
17660            }
17661        }
17662    }
17663
17664    /*
17665     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17666     * flag is not set, the data directory is removed as well.
17667     * make sure this flag is set for partially installed apps. If not its meaningless to
17668     * delete a partially installed application.
17669     */
17670    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17671            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17672        String packageName = ps.name;
17673        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17674        // Retrieve object to delete permissions for shared user later on
17675        final PackageParser.Package deletedPkg;
17676        final PackageSetting deletedPs;
17677        // reader
17678        synchronized (mPackages) {
17679            deletedPkg = mPackages.get(packageName);
17680            deletedPs = mSettings.mPackages.get(packageName);
17681            if (outInfo != null) {
17682                outInfo.removedPackage = packageName;
17683                outInfo.isStaticSharedLib = deletedPkg != null
17684                        && deletedPkg.staticSharedLibName != null;
17685                outInfo.removedUsers = deletedPs != null
17686                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17687                        : null;
17688            }
17689        }
17690
17691        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17692
17693        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17694            final PackageParser.Package resolvedPkg;
17695            if (deletedPkg != null) {
17696                resolvedPkg = deletedPkg;
17697            } else {
17698                // We don't have a parsed package when it lives on an ejected
17699                // adopted storage device, so fake something together
17700                resolvedPkg = new PackageParser.Package(ps.name);
17701                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17702            }
17703            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17704                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17705            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17706            if (outInfo != null) {
17707                outInfo.dataRemoved = true;
17708            }
17709            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17710        }
17711
17712        int removedAppId = -1;
17713
17714        // writer
17715        synchronized (mPackages) {
17716            boolean installedStateChanged = false;
17717            if (deletedPs != null) {
17718                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17719                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17720                    clearDefaultBrowserIfNeeded(packageName);
17721                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17722                    removedAppId = mSettings.removePackageLPw(packageName);
17723                    if (outInfo != null) {
17724                        outInfo.removedAppId = removedAppId;
17725                    }
17726                    updatePermissionsLPw(deletedPs.name, null, 0);
17727                    if (deletedPs.sharedUser != null) {
17728                        // Remove permissions associated with package. Since runtime
17729                        // permissions are per user we have to kill the removed package
17730                        // or packages running under the shared user of the removed
17731                        // package if revoking the permissions requested only by the removed
17732                        // package is successful and this causes a change in gids.
17733                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17734                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17735                                    userId);
17736                            if (userIdToKill == UserHandle.USER_ALL
17737                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17738                                // If gids changed for this user, kill all affected packages.
17739                                mHandler.post(new Runnable() {
17740                                    @Override
17741                                    public void run() {
17742                                        // This has to happen with no lock held.
17743                                        killApplication(deletedPs.name, deletedPs.appId,
17744                                                KILL_APP_REASON_GIDS_CHANGED);
17745                                    }
17746                                });
17747                                break;
17748                            }
17749                        }
17750                    }
17751                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17752                }
17753                // make sure to preserve per-user disabled state if this removal was just
17754                // a downgrade of a system app to the factory package
17755                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17756                    if (DEBUG_REMOVE) {
17757                        Slog.d(TAG, "Propagating install state across downgrade");
17758                    }
17759                    for (int userId : allUserHandles) {
17760                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17761                        if (DEBUG_REMOVE) {
17762                            Slog.d(TAG, "    user " + userId + " => " + installed);
17763                        }
17764                        if (installed != ps.getInstalled(userId)) {
17765                            installedStateChanged = true;
17766                        }
17767                        ps.setInstalled(installed, userId);
17768                    }
17769                }
17770            }
17771            // can downgrade to reader
17772            if (writeSettings) {
17773                // Save settings now
17774                mSettings.writeLPr();
17775            }
17776            if (installedStateChanged) {
17777                mSettings.writeKernelMappingLPr(ps);
17778            }
17779        }
17780        if (removedAppId != -1) {
17781            // A user ID was deleted here. Go through all users and remove it
17782            // from KeyStore.
17783            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17784        }
17785    }
17786
17787    static boolean locationIsPrivileged(File path) {
17788        try {
17789            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17790                    .getCanonicalPath();
17791            return path.getCanonicalPath().startsWith(privilegedAppDir);
17792        } catch (IOException e) {
17793            Slog.e(TAG, "Unable to access code path " + path);
17794        }
17795        return false;
17796    }
17797
17798    /*
17799     * Tries to delete system package.
17800     */
17801    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17802            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17803            boolean writeSettings) {
17804        if (deletedPs.parentPackageName != null) {
17805            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17806            return false;
17807        }
17808
17809        final boolean applyUserRestrictions
17810                = (allUserHandles != null) && (outInfo.origUsers != null);
17811        final PackageSetting disabledPs;
17812        // Confirm if the system package has been updated
17813        // An updated system app can be deleted. This will also have to restore
17814        // the system pkg from system partition
17815        // reader
17816        synchronized (mPackages) {
17817            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17818        }
17819
17820        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17821                + " disabledPs=" + disabledPs);
17822
17823        if (disabledPs == null) {
17824            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17825            return false;
17826        } else if (DEBUG_REMOVE) {
17827            Slog.d(TAG, "Deleting system pkg from data partition");
17828        }
17829
17830        if (DEBUG_REMOVE) {
17831            if (applyUserRestrictions) {
17832                Slog.d(TAG, "Remembering install states:");
17833                for (int userId : allUserHandles) {
17834                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17835                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17836                }
17837            }
17838        }
17839
17840        // Delete the updated package
17841        outInfo.isRemovedPackageSystemUpdate = true;
17842        if (outInfo.removedChildPackages != null) {
17843            final int childCount = (deletedPs.childPackageNames != null)
17844                    ? deletedPs.childPackageNames.size() : 0;
17845            for (int i = 0; i < childCount; i++) {
17846                String childPackageName = deletedPs.childPackageNames.get(i);
17847                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17848                        .contains(childPackageName)) {
17849                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17850                            childPackageName);
17851                    if (childInfo != null) {
17852                        childInfo.isRemovedPackageSystemUpdate = true;
17853                    }
17854                }
17855            }
17856        }
17857
17858        if (disabledPs.versionCode < deletedPs.versionCode) {
17859            // Delete data for downgrades
17860            flags &= ~PackageManager.DELETE_KEEP_DATA;
17861        } else {
17862            // Preserve data by setting flag
17863            flags |= PackageManager.DELETE_KEEP_DATA;
17864        }
17865
17866        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17867                outInfo, writeSettings, disabledPs.pkg);
17868        if (!ret) {
17869            return false;
17870        }
17871
17872        // writer
17873        synchronized (mPackages) {
17874            // Reinstate the old system package
17875            enableSystemPackageLPw(disabledPs.pkg);
17876            // Remove any native libraries from the upgraded package.
17877            removeNativeBinariesLI(deletedPs);
17878        }
17879
17880        // Install the system package
17881        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17882        int parseFlags = mDefParseFlags
17883                | PackageParser.PARSE_MUST_BE_APK
17884                | PackageParser.PARSE_IS_SYSTEM
17885                | PackageParser.PARSE_IS_SYSTEM_DIR;
17886        if (locationIsPrivileged(disabledPs.codePath)) {
17887            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17888        }
17889
17890        final PackageParser.Package newPkg;
17891        try {
17892            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17893                0 /* currentTime */, null);
17894        } catch (PackageManagerException e) {
17895            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17896                    + e.getMessage());
17897            return false;
17898        }
17899
17900        try {
17901            // update shared libraries for the newly re-installed system package
17902            updateSharedLibrariesLPr(newPkg, null);
17903        } catch (PackageManagerException e) {
17904            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17905        }
17906
17907        prepareAppDataAfterInstallLIF(newPkg);
17908
17909        // writer
17910        synchronized (mPackages) {
17911            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17912
17913            // Propagate the permissions state as we do not want to drop on the floor
17914            // runtime permissions. The update permissions method below will take
17915            // care of removing obsolete permissions and grant install permissions.
17916            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17917            updatePermissionsLPw(newPkg.packageName, newPkg,
17918                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17919
17920            if (applyUserRestrictions) {
17921                boolean installedStateChanged = false;
17922                if (DEBUG_REMOVE) {
17923                    Slog.d(TAG, "Propagating install state across reinstall");
17924                }
17925                for (int userId : allUserHandles) {
17926                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17927                    if (DEBUG_REMOVE) {
17928                        Slog.d(TAG, "    user " + userId + " => " + installed);
17929                    }
17930                    if (installed != ps.getInstalled(userId)) {
17931                        installedStateChanged = true;
17932                    }
17933                    ps.setInstalled(installed, userId);
17934
17935                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17936                }
17937                // Regardless of writeSettings we need to ensure that this restriction
17938                // state propagation is persisted
17939                mSettings.writeAllUsersPackageRestrictionsLPr();
17940                if (installedStateChanged) {
17941                    mSettings.writeKernelMappingLPr(ps);
17942                }
17943            }
17944            // can downgrade to reader here
17945            if (writeSettings) {
17946                mSettings.writeLPr();
17947            }
17948        }
17949        return true;
17950    }
17951
17952    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17953            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17954            PackageRemovedInfo outInfo, boolean writeSettings,
17955            PackageParser.Package replacingPackage) {
17956        synchronized (mPackages) {
17957            if (outInfo != null) {
17958                outInfo.uid = ps.appId;
17959            }
17960
17961            if (outInfo != null && outInfo.removedChildPackages != null) {
17962                final int childCount = (ps.childPackageNames != null)
17963                        ? ps.childPackageNames.size() : 0;
17964                for (int i = 0; i < childCount; i++) {
17965                    String childPackageName = ps.childPackageNames.get(i);
17966                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17967                    if (childPs == null) {
17968                        return false;
17969                    }
17970                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17971                            childPackageName);
17972                    if (childInfo != null) {
17973                        childInfo.uid = childPs.appId;
17974                    }
17975                }
17976            }
17977        }
17978
17979        // Delete package data from internal structures and also remove data if flag is set
17980        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17981
17982        // Delete the child packages data
17983        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17984        for (int i = 0; i < childCount; i++) {
17985            PackageSetting childPs;
17986            synchronized (mPackages) {
17987                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17988            }
17989            if (childPs != null) {
17990                PackageRemovedInfo childOutInfo = (outInfo != null
17991                        && outInfo.removedChildPackages != null)
17992                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17993                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17994                        && (replacingPackage != null
17995                        && !replacingPackage.hasChildPackage(childPs.name))
17996                        ? flags & ~DELETE_KEEP_DATA : flags;
17997                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17998                        deleteFlags, writeSettings);
17999            }
18000        }
18001
18002        // Delete application code and resources only for parent packages
18003        if (ps.parentPackageName == null) {
18004            if (deleteCodeAndResources && (outInfo != null)) {
18005                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18006                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18007                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18008            }
18009        }
18010
18011        return true;
18012    }
18013
18014    @Override
18015    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18016            int userId) {
18017        mContext.enforceCallingOrSelfPermission(
18018                android.Manifest.permission.DELETE_PACKAGES, null);
18019        synchronized (mPackages) {
18020            PackageSetting ps = mSettings.mPackages.get(packageName);
18021            if (ps == null) {
18022                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18023                return false;
18024            }
18025            // Cannot block uninstall of static shared libs as they are
18026            // considered a part of the using app (emulating static linking).
18027            // Also static libs are installed always on internal storage.
18028            PackageParser.Package pkg = mPackages.get(packageName);
18029            if (pkg != null && pkg.staticSharedLibName != null) {
18030                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18031                        + " providing static shared library: " + pkg.staticSharedLibName);
18032                return false;
18033            }
18034            if (!ps.getInstalled(userId)) {
18035                // Can't block uninstall for an app that is not installed or enabled.
18036                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18037                return false;
18038            }
18039            ps.setBlockUninstall(blockUninstall, userId);
18040            mSettings.writePackageRestrictionsLPr(userId);
18041        }
18042        return true;
18043    }
18044
18045    @Override
18046    public boolean getBlockUninstallForUser(String packageName, int userId) {
18047        synchronized (mPackages) {
18048            PackageSetting ps = mSettings.mPackages.get(packageName);
18049            if (ps == null) {
18050                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18051                return false;
18052            }
18053            return ps.getBlockUninstall(userId);
18054        }
18055    }
18056
18057    @Override
18058    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18059        int callingUid = Binder.getCallingUid();
18060        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18061            throw new SecurityException(
18062                    "setRequiredForSystemUser can only be run by the system or root");
18063        }
18064        synchronized (mPackages) {
18065            PackageSetting ps = mSettings.mPackages.get(packageName);
18066            if (ps == null) {
18067                Log.w(TAG, "Package doesn't exist: " + packageName);
18068                return false;
18069            }
18070            if (systemUserApp) {
18071                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18072            } else {
18073                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18074            }
18075            mSettings.writeLPr();
18076        }
18077        return true;
18078    }
18079
18080    /*
18081     * This method handles package deletion in general
18082     */
18083    private boolean deletePackageLIF(String packageName, UserHandle user,
18084            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18085            PackageRemovedInfo outInfo, boolean writeSettings,
18086            PackageParser.Package replacingPackage) {
18087        if (packageName == null) {
18088            Slog.w(TAG, "Attempt to delete null packageName.");
18089            return false;
18090        }
18091
18092        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18093
18094        PackageSetting ps;
18095        synchronized (mPackages) {
18096            ps = mSettings.mPackages.get(packageName);
18097            if (ps == null) {
18098                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18099                return false;
18100            }
18101
18102            if (ps.parentPackageName != null && (!isSystemApp(ps)
18103                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18104                if (DEBUG_REMOVE) {
18105                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18106                            + ((user == null) ? UserHandle.USER_ALL : user));
18107                }
18108                final int removedUserId = (user != null) ? user.getIdentifier()
18109                        : UserHandle.USER_ALL;
18110                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18111                    return false;
18112                }
18113                markPackageUninstalledForUserLPw(ps, user);
18114                scheduleWritePackageRestrictionsLocked(user);
18115                return true;
18116            }
18117        }
18118
18119        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18120                && user.getIdentifier() != UserHandle.USER_ALL)) {
18121            // The caller is asking that the package only be deleted for a single
18122            // user.  To do this, we just mark its uninstalled state and delete
18123            // its data. If this is a system app, we only allow this to happen if
18124            // they have set the special DELETE_SYSTEM_APP which requests different
18125            // semantics than normal for uninstalling system apps.
18126            markPackageUninstalledForUserLPw(ps, user);
18127
18128            if (!isSystemApp(ps)) {
18129                // Do not uninstall the APK if an app should be cached
18130                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18131                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18132                    // Other user still have this package installed, so all
18133                    // we need to do is clear this user's data and save that
18134                    // it is uninstalled.
18135                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18136                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18137                        return false;
18138                    }
18139                    scheduleWritePackageRestrictionsLocked(user);
18140                    return true;
18141                } else {
18142                    // We need to set it back to 'installed' so the uninstall
18143                    // broadcasts will be sent correctly.
18144                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18145                    ps.setInstalled(true, user.getIdentifier());
18146                    mSettings.writeKernelMappingLPr(ps);
18147                }
18148            } else {
18149                // This is a system app, so we assume that the
18150                // other users still have this package installed, so all
18151                // we need to do is clear this user's data and save that
18152                // it is uninstalled.
18153                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18154                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18155                    return false;
18156                }
18157                scheduleWritePackageRestrictionsLocked(user);
18158                return true;
18159            }
18160        }
18161
18162        // If we are deleting a composite package for all users, keep track
18163        // of result for each child.
18164        if (ps.childPackageNames != null && outInfo != null) {
18165            synchronized (mPackages) {
18166                final int childCount = ps.childPackageNames.size();
18167                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18168                for (int i = 0; i < childCount; i++) {
18169                    String childPackageName = ps.childPackageNames.get(i);
18170                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18171                    childInfo.removedPackage = childPackageName;
18172                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18173                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18174                    if (childPs != null) {
18175                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18176                    }
18177                }
18178            }
18179        }
18180
18181        boolean ret = false;
18182        if (isSystemApp(ps)) {
18183            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18184            // When an updated system application is deleted we delete the existing resources
18185            // as well and fall back to existing code in system partition
18186            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18187        } else {
18188            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18189            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18190                    outInfo, writeSettings, replacingPackage);
18191        }
18192
18193        // Take a note whether we deleted the package for all users
18194        if (outInfo != null) {
18195            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18196            if (outInfo.removedChildPackages != null) {
18197                synchronized (mPackages) {
18198                    final int childCount = outInfo.removedChildPackages.size();
18199                    for (int i = 0; i < childCount; i++) {
18200                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18201                        if (childInfo != null) {
18202                            childInfo.removedForAllUsers = mPackages.get(
18203                                    childInfo.removedPackage) == null;
18204                        }
18205                    }
18206                }
18207            }
18208            // If we uninstalled an update to a system app there may be some
18209            // child packages that appeared as they are declared in the system
18210            // app but were not declared in the update.
18211            if (isSystemApp(ps)) {
18212                synchronized (mPackages) {
18213                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18214                    final int childCount = (updatedPs.childPackageNames != null)
18215                            ? updatedPs.childPackageNames.size() : 0;
18216                    for (int i = 0; i < childCount; i++) {
18217                        String childPackageName = updatedPs.childPackageNames.get(i);
18218                        if (outInfo.removedChildPackages == null
18219                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18220                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18221                            if (childPs == null) {
18222                                continue;
18223                            }
18224                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18225                            installRes.name = childPackageName;
18226                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18227                            installRes.pkg = mPackages.get(childPackageName);
18228                            installRes.uid = childPs.pkg.applicationInfo.uid;
18229                            if (outInfo.appearedChildPackages == null) {
18230                                outInfo.appearedChildPackages = new ArrayMap<>();
18231                            }
18232                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18233                        }
18234                    }
18235                }
18236            }
18237        }
18238
18239        return ret;
18240    }
18241
18242    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18243        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18244                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18245        for (int nextUserId : userIds) {
18246            if (DEBUG_REMOVE) {
18247                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18248            }
18249            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18250                    false /*installed*/,
18251                    true /*stopped*/,
18252                    true /*notLaunched*/,
18253                    false /*hidden*/,
18254                    false /*suspended*/,
18255                    false /*instantApp*/,
18256                    null /*lastDisableAppCaller*/,
18257                    null /*enabledComponents*/,
18258                    null /*disabledComponents*/,
18259                    false /*blockUninstall*/,
18260                    ps.readUserState(nextUserId).domainVerificationStatus,
18261                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18262        }
18263        mSettings.writeKernelMappingLPr(ps);
18264    }
18265
18266    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18267            PackageRemovedInfo outInfo) {
18268        final PackageParser.Package pkg;
18269        synchronized (mPackages) {
18270            pkg = mPackages.get(ps.name);
18271        }
18272
18273        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18274                : new int[] {userId};
18275        for (int nextUserId : userIds) {
18276            if (DEBUG_REMOVE) {
18277                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18278                        + nextUserId);
18279            }
18280
18281            destroyAppDataLIF(pkg, userId,
18282                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18283            destroyAppProfilesLIF(pkg, userId);
18284            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18285            schedulePackageCleaning(ps.name, nextUserId, false);
18286            synchronized (mPackages) {
18287                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18288                    scheduleWritePackageRestrictionsLocked(nextUserId);
18289                }
18290                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18291            }
18292        }
18293
18294        if (outInfo != null) {
18295            outInfo.removedPackage = ps.name;
18296            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18297            outInfo.removedAppId = ps.appId;
18298            outInfo.removedUsers = userIds;
18299        }
18300
18301        return true;
18302    }
18303
18304    private final class ClearStorageConnection implements ServiceConnection {
18305        IMediaContainerService mContainerService;
18306
18307        @Override
18308        public void onServiceConnected(ComponentName name, IBinder service) {
18309            synchronized (this) {
18310                mContainerService = IMediaContainerService.Stub
18311                        .asInterface(Binder.allowBlocking(service));
18312                notifyAll();
18313            }
18314        }
18315
18316        @Override
18317        public void onServiceDisconnected(ComponentName name) {
18318        }
18319    }
18320
18321    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18322        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18323
18324        final boolean mounted;
18325        if (Environment.isExternalStorageEmulated()) {
18326            mounted = true;
18327        } else {
18328            final String status = Environment.getExternalStorageState();
18329
18330            mounted = status.equals(Environment.MEDIA_MOUNTED)
18331                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18332        }
18333
18334        if (!mounted) {
18335            return;
18336        }
18337
18338        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18339        int[] users;
18340        if (userId == UserHandle.USER_ALL) {
18341            users = sUserManager.getUserIds();
18342        } else {
18343            users = new int[] { userId };
18344        }
18345        final ClearStorageConnection conn = new ClearStorageConnection();
18346        if (mContext.bindServiceAsUser(
18347                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18348            try {
18349                for (int curUser : users) {
18350                    long timeout = SystemClock.uptimeMillis() + 5000;
18351                    synchronized (conn) {
18352                        long now;
18353                        while (conn.mContainerService == null &&
18354                                (now = SystemClock.uptimeMillis()) < timeout) {
18355                            try {
18356                                conn.wait(timeout - now);
18357                            } catch (InterruptedException e) {
18358                            }
18359                        }
18360                    }
18361                    if (conn.mContainerService == null) {
18362                        return;
18363                    }
18364
18365                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18366                    clearDirectory(conn.mContainerService,
18367                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18368                    if (allData) {
18369                        clearDirectory(conn.mContainerService,
18370                                userEnv.buildExternalStorageAppDataDirs(packageName));
18371                        clearDirectory(conn.mContainerService,
18372                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18373                    }
18374                }
18375            } finally {
18376                mContext.unbindService(conn);
18377            }
18378        }
18379    }
18380
18381    @Override
18382    public void clearApplicationProfileData(String packageName) {
18383        enforceSystemOrRoot("Only the system can clear all profile data");
18384
18385        final PackageParser.Package pkg;
18386        synchronized (mPackages) {
18387            pkg = mPackages.get(packageName);
18388        }
18389
18390        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18391            synchronized (mInstallLock) {
18392                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18393                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18394                        true /* removeBaseMarker */);
18395            }
18396        }
18397    }
18398
18399    @Override
18400    public void clearApplicationUserData(final String packageName,
18401            final IPackageDataObserver observer, final int userId) {
18402        mContext.enforceCallingOrSelfPermission(
18403                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18404
18405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18406                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18407
18408        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18409            throw new SecurityException("Cannot clear data for a protected package: "
18410                    + packageName);
18411        }
18412        // Queue up an async operation since the package deletion may take a little while.
18413        mHandler.post(new Runnable() {
18414            public void run() {
18415                mHandler.removeCallbacks(this);
18416                final boolean succeeded;
18417                try (PackageFreezer freezer = freezePackage(packageName,
18418                        "clearApplicationUserData")) {
18419                    synchronized (mInstallLock) {
18420                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18421                    }
18422                    clearExternalStorageDataSync(packageName, userId, true);
18423                    synchronized (mPackages) {
18424                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18425                                packageName, userId);
18426                    }
18427                }
18428                if (succeeded) {
18429                    // invoke DeviceStorageMonitor's update method to clear any notifications
18430                    DeviceStorageMonitorInternal dsm = LocalServices
18431                            .getService(DeviceStorageMonitorInternal.class);
18432                    if (dsm != null) {
18433                        dsm.checkMemory();
18434                    }
18435                }
18436                if(observer != null) {
18437                    try {
18438                        observer.onRemoveCompleted(packageName, succeeded);
18439                    } catch (RemoteException e) {
18440                        Log.i(TAG, "Observer no longer exists.");
18441                    }
18442                } //end if observer
18443            } //end run
18444        });
18445    }
18446
18447    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18448        if (packageName == null) {
18449            Slog.w(TAG, "Attempt to delete null packageName.");
18450            return false;
18451        }
18452
18453        // Try finding details about the requested package
18454        PackageParser.Package pkg;
18455        synchronized (mPackages) {
18456            pkg = mPackages.get(packageName);
18457            if (pkg == null) {
18458                final PackageSetting ps = mSettings.mPackages.get(packageName);
18459                if (ps != null) {
18460                    pkg = ps.pkg;
18461                }
18462            }
18463
18464            if (pkg == null) {
18465                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18466                return false;
18467            }
18468
18469            PackageSetting ps = (PackageSetting) pkg.mExtras;
18470            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18471        }
18472
18473        clearAppDataLIF(pkg, userId,
18474                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18475
18476        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18477        removeKeystoreDataIfNeeded(userId, appId);
18478
18479        UserManagerInternal umInternal = getUserManagerInternal();
18480        final int flags;
18481        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18482            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18483        } else if (umInternal.isUserRunning(userId)) {
18484            flags = StorageManager.FLAG_STORAGE_DE;
18485        } else {
18486            flags = 0;
18487        }
18488        prepareAppDataContentsLIF(pkg, userId, flags);
18489
18490        return true;
18491    }
18492
18493    /**
18494     * Reverts user permission state changes (permissions and flags) in
18495     * all packages for a given user.
18496     *
18497     * @param userId The device user for which to do a reset.
18498     */
18499    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18500        final int packageCount = mPackages.size();
18501        for (int i = 0; i < packageCount; i++) {
18502            PackageParser.Package pkg = mPackages.valueAt(i);
18503            PackageSetting ps = (PackageSetting) pkg.mExtras;
18504            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18505        }
18506    }
18507
18508    private void resetNetworkPolicies(int userId) {
18509        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18510    }
18511
18512    /**
18513     * Reverts user permission state changes (permissions and flags).
18514     *
18515     * @param ps The package for which to reset.
18516     * @param userId The device user for which to do a reset.
18517     */
18518    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18519            final PackageSetting ps, final int userId) {
18520        if (ps.pkg == null) {
18521            return;
18522        }
18523
18524        // These are flags that can change base on user actions.
18525        final int userSettableMask = FLAG_PERMISSION_USER_SET
18526                | FLAG_PERMISSION_USER_FIXED
18527                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18528                | FLAG_PERMISSION_REVIEW_REQUIRED;
18529
18530        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18531                | FLAG_PERMISSION_POLICY_FIXED;
18532
18533        boolean writeInstallPermissions = false;
18534        boolean writeRuntimePermissions = false;
18535
18536        final int permissionCount = ps.pkg.requestedPermissions.size();
18537        for (int i = 0; i < permissionCount; i++) {
18538            String permission = ps.pkg.requestedPermissions.get(i);
18539
18540            BasePermission bp = mSettings.mPermissions.get(permission);
18541            if (bp == null) {
18542                continue;
18543            }
18544
18545            // If shared user we just reset the state to which only this app contributed.
18546            if (ps.sharedUser != null) {
18547                boolean used = false;
18548                final int packageCount = ps.sharedUser.packages.size();
18549                for (int j = 0; j < packageCount; j++) {
18550                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18551                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18552                            && pkg.pkg.requestedPermissions.contains(permission)) {
18553                        used = true;
18554                        break;
18555                    }
18556                }
18557                if (used) {
18558                    continue;
18559                }
18560            }
18561
18562            PermissionsState permissionsState = ps.getPermissionsState();
18563
18564            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18565
18566            // Always clear the user settable flags.
18567            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18568                    bp.name) != null;
18569            // If permission review is enabled and this is a legacy app, mark the
18570            // permission as requiring a review as this is the initial state.
18571            int flags = 0;
18572            if (mPermissionReviewRequired
18573                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18574                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18575            }
18576            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18577                if (hasInstallState) {
18578                    writeInstallPermissions = true;
18579                } else {
18580                    writeRuntimePermissions = true;
18581                }
18582            }
18583
18584            // Below is only runtime permission handling.
18585            if (!bp.isRuntime()) {
18586                continue;
18587            }
18588
18589            // Never clobber system or policy.
18590            if ((oldFlags & policyOrSystemFlags) != 0) {
18591                continue;
18592            }
18593
18594            // If this permission was granted by default, make sure it is.
18595            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18596                if (permissionsState.grantRuntimePermission(bp, userId)
18597                        != PERMISSION_OPERATION_FAILURE) {
18598                    writeRuntimePermissions = true;
18599                }
18600            // If permission review is enabled the permissions for a legacy apps
18601            // are represented as constantly granted runtime ones, so don't revoke.
18602            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18603                // Otherwise, reset the permission.
18604                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18605                switch (revokeResult) {
18606                    case PERMISSION_OPERATION_SUCCESS:
18607                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18608                        writeRuntimePermissions = true;
18609                        final int appId = ps.appId;
18610                        mHandler.post(new Runnable() {
18611                            @Override
18612                            public void run() {
18613                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18614                            }
18615                        });
18616                    } break;
18617                }
18618            }
18619        }
18620
18621        // Synchronously write as we are taking permissions away.
18622        if (writeRuntimePermissions) {
18623            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18624        }
18625
18626        // Synchronously write as we are taking permissions away.
18627        if (writeInstallPermissions) {
18628            mSettings.writeLPr();
18629        }
18630    }
18631
18632    /**
18633     * Remove entries from the keystore daemon. Will only remove it if the
18634     * {@code appId} is valid.
18635     */
18636    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18637        if (appId < 0) {
18638            return;
18639        }
18640
18641        final KeyStore keyStore = KeyStore.getInstance();
18642        if (keyStore != null) {
18643            if (userId == UserHandle.USER_ALL) {
18644                for (final int individual : sUserManager.getUserIds()) {
18645                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18646                }
18647            } else {
18648                keyStore.clearUid(UserHandle.getUid(userId, appId));
18649            }
18650        } else {
18651            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18652        }
18653    }
18654
18655    @Override
18656    public void deleteApplicationCacheFiles(final String packageName,
18657            final IPackageDataObserver observer) {
18658        final int userId = UserHandle.getCallingUserId();
18659        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18660    }
18661
18662    @Override
18663    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18664            final IPackageDataObserver observer) {
18665        mContext.enforceCallingOrSelfPermission(
18666                android.Manifest.permission.DELETE_CACHE_FILES, null);
18667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18668                /* requireFullPermission= */ true, /* checkShell= */ false,
18669                "delete application cache files");
18670
18671        final PackageParser.Package pkg;
18672        synchronized (mPackages) {
18673            pkg = mPackages.get(packageName);
18674        }
18675
18676        // Queue up an async operation since the package deletion may take a little while.
18677        mHandler.post(new Runnable() {
18678            public void run() {
18679                synchronized (mInstallLock) {
18680                    final int flags = StorageManager.FLAG_STORAGE_DE
18681                            | StorageManager.FLAG_STORAGE_CE;
18682                    // We're only clearing cache files, so we don't care if the
18683                    // app is unfrozen and still able to run
18684                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18685                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18686                }
18687                clearExternalStorageDataSync(packageName, userId, false);
18688                if (observer != null) {
18689                    try {
18690                        observer.onRemoveCompleted(packageName, true);
18691                    } catch (RemoteException e) {
18692                        Log.i(TAG, "Observer no longer exists.");
18693                    }
18694                }
18695            }
18696        });
18697    }
18698
18699    @Override
18700    public void getPackageSizeInfo(final String packageName, int userHandle,
18701            final IPackageStatsObserver observer) {
18702        Slog.w(TAG, "Shame on you for calling a hidden API. Shame!");
18703        try {
18704            observer.onGetStatsCompleted(null, false);
18705        } catch (Throwable ignored) {
18706        }
18707    }
18708
18709    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18710        final PackageSetting ps;
18711        synchronized (mPackages) {
18712            ps = mSettings.mPackages.get(packageName);
18713            if (ps == null) {
18714                Slog.w(TAG, "Failed to find settings for " + packageName);
18715                return false;
18716            }
18717        }
18718
18719        final String[] packageNames = { packageName };
18720        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18721        final String[] codePaths = { ps.codePathString };
18722
18723        try {
18724            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18725                    ps.appId, ceDataInodes, codePaths, stats);
18726
18727            // For now, ignore code size of packages on system partition
18728            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18729                stats.codeSize = 0;
18730            }
18731
18732            // External clients expect these to be tracked separately
18733            stats.dataSize -= stats.cacheSize;
18734
18735        } catch (InstallerException e) {
18736            Slog.w(TAG, String.valueOf(e));
18737            return false;
18738        }
18739
18740        return true;
18741    }
18742
18743    private int getUidTargetSdkVersionLockedLPr(int uid) {
18744        Object obj = mSettings.getUserIdLPr(uid);
18745        if (obj instanceof SharedUserSetting) {
18746            final SharedUserSetting sus = (SharedUserSetting) obj;
18747            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18748            final Iterator<PackageSetting> it = sus.packages.iterator();
18749            while (it.hasNext()) {
18750                final PackageSetting ps = it.next();
18751                if (ps.pkg != null) {
18752                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18753                    if (v < vers) vers = v;
18754                }
18755            }
18756            return vers;
18757        } else if (obj instanceof PackageSetting) {
18758            final PackageSetting ps = (PackageSetting) obj;
18759            if (ps.pkg != null) {
18760                return ps.pkg.applicationInfo.targetSdkVersion;
18761            }
18762        }
18763        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18764    }
18765
18766    @Override
18767    public void addPreferredActivity(IntentFilter filter, int match,
18768            ComponentName[] set, ComponentName activity, int userId) {
18769        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18770                "Adding preferred");
18771    }
18772
18773    private void addPreferredActivityInternal(IntentFilter filter, int match,
18774            ComponentName[] set, ComponentName activity, boolean always, int userId,
18775            String opname) {
18776        // writer
18777        int callingUid = Binder.getCallingUid();
18778        enforceCrossUserPermission(callingUid, userId,
18779                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18780        if (filter.countActions() == 0) {
18781            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18782            return;
18783        }
18784        synchronized (mPackages) {
18785            if (mContext.checkCallingOrSelfPermission(
18786                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18787                    != PackageManager.PERMISSION_GRANTED) {
18788                if (getUidTargetSdkVersionLockedLPr(callingUid)
18789                        < Build.VERSION_CODES.FROYO) {
18790                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18791                            + callingUid);
18792                    return;
18793                }
18794                mContext.enforceCallingOrSelfPermission(
18795                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18796            }
18797
18798            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18799            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18800                    + userId + ":");
18801            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18802            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18803            scheduleWritePackageRestrictionsLocked(userId);
18804            postPreferredActivityChangedBroadcast(userId);
18805        }
18806    }
18807
18808    private void postPreferredActivityChangedBroadcast(int userId) {
18809        mHandler.post(() -> {
18810            final IActivityManager am = ActivityManager.getService();
18811            if (am == null) {
18812                return;
18813            }
18814
18815            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18816            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18817            try {
18818                am.broadcastIntent(null, intent, null, null,
18819                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18820                        null, false, false, userId);
18821            } catch (RemoteException e) {
18822            }
18823        });
18824    }
18825
18826    @Override
18827    public void replacePreferredActivity(IntentFilter filter, int match,
18828            ComponentName[] set, ComponentName activity, int userId) {
18829        if (filter.countActions() != 1) {
18830            throw new IllegalArgumentException(
18831                    "replacePreferredActivity expects filter to have only 1 action.");
18832        }
18833        if (filter.countDataAuthorities() != 0
18834                || filter.countDataPaths() != 0
18835                || filter.countDataSchemes() > 1
18836                || filter.countDataTypes() != 0) {
18837            throw new IllegalArgumentException(
18838                    "replacePreferredActivity expects filter to have no data authorities, " +
18839                    "paths, or types; and at most one scheme.");
18840        }
18841
18842        final int callingUid = Binder.getCallingUid();
18843        enforceCrossUserPermission(callingUid, userId,
18844                true /* requireFullPermission */, false /* checkShell */,
18845                "replace preferred activity");
18846        synchronized (mPackages) {
18847            if (mContext.checkCallingOrSelfPermission(
18848                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18849                    != PackageManager.PERMISSION_GRANTED) {
18850                if (getUidTargetSdkVersionLockedLPr(callingUid)
18851                        < Build.VERSION_CODES.FROYO) {
18852                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18853                            + Binder.getCallingUid());
18854                    return;
18855                }
18856                mContext.enforceCallingOrSelfPermission(
18857                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18858            }
18859
18860            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18861            if (pir != null) {
18862                // Get all of the existing entries that exactly match this filter.
18863                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18864                if (existing != null && existing.size() == 1) {
18865                    PreferredActivity cur = existing.get(0);
18866                    if (DEBUG_PREFERRED) {
18867                        Slog.i(TAG, "Checking replace of preferred:");
18868                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18869                        if (!cur.mPref.mAlways) {
18870                            Slog.i(TAG, "  -- CUR; not mAlways!");
18871                        } else {
18872                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18873                            Slog.i(TAG, "  -- CUR: mSet="
18874                                    + Arrays.toString(cur.mPref.mSetComponents));
18875                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18876                            Slog.i(TAG, "  -- NEW: mMatch="
18877                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18878                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18879                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18880                        }
18881                    }
18882                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18883                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18884                            && cur.mPref.sameSet(set)) {
18885                        // Setting the preferred activity to what it happens to be already
18886                        if (DEBUG_PREFERRED) {
18887                            Slog.i(TAG, "Replacing with same preferred activity "
18888                                    + cur.mPref.mShortComponent + " for user "
18889                                    + userId + ":");
18890                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18891                        }
18892                        return;
18893                    }
18894                }
18895
18896                if (existing != null) {
18897                    if (DEBUG_PREFERRED) {
18898                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18899                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18900                    }
18901                    for (int i = 0; i < existing.size(); i++) {
18902                        PreferredActivity pa = existing.get(i);
18903                        if (DEBUG_PREFERRED) {
18904                            Slog.i(TAG, "Removing existing preferred activity "
18905                                    + pa.mPref.mComponent + ":");
18906                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18907                        }
18908                        pir.removeFilter(pa);
18909                    }
18910                }
18911            }
18912            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18913                    "Replacing preferred");
18914        }
18915    }
18916
18917    @Override
18918    public void clearPackagePreferredActivities(String packageName) {
18919        final int uid = Binder.getCallingUid();
18920        // writer
18921        synchronized (mPackages) {
18922            PackageParser.Package pkg = mPackages.get(packageName);
18923            if (pkg == null || pkg.applicationInfo.uid != uid) {
18924                if (mContext.checkCallingOrSelfPermission(
18925                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18926                        != PackageManager.PERMISSION_GRANTED) {
18927                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18928                            < Build.VERSION_CODES.FROYO) {
18929                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18930                                + Binder.getCallingUid());
18931                        return;
18932                    }
18933                    mContext.enforceCallingOrSelfPermission(
18934                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18935                }
18936            }
18937
18938            int user = UserHandle.getCallingUserId();
18939            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18940                scheduleWritePackageRestrictionsLocked(user);
18941            }
18942        }
18943    }
18944
18945    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18946    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18947        ArrayList<PreferredActivity> removed = null;
18948        boolean changed = false;
18949        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18950            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18951            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18952            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18953                continue;
18954            }
18955            Iterator<PreferredActivity> it = pir.filterIterator();
18956            while (it.hasNext()) {
18957                PreferredActivity pa = it.next();
18958                // Mark entry for removal only if it matches the package name
18959                // and the entry is of type "always".
18960                if (packageName == null ||
18961                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18962                                && pa.mPref.mAlways)) {
18963                    if (removed == null) {
18964                        removed = new ArrayList<PreferredActivity>();
18965                    }
18966                    removed.add(pa);
18967                }
18968            }
18969            if (removed != null) {
18970                for (int j=0; j<removed.size(); j++) {
18971                    PreferredActivity pa = removed.get(j);
18972                    pir.removeFilter(pa);
18973                }
18974                changed = true;
18975            }
18976        }
18977        if (changed) {
18978            postPreferredActivityChangedBroadcast(userId);
18979        }
18980        return changed;
18981    }
18982
18983    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18984    private void clearIntentFilterVerificationsLPw(int userId) {
18985        final int packageCount = mPackages.size();
18986        for (int i = 0; i < packageCount; i++) {
18987            PackageParser.Package pkg = mPackages.valueAt(i);
18988            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18989        }
18990    }
18991
18992    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18993    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18994        if (userId == UserHandle.USER_ALL) {
18995            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18996                    sUserManager.getUserIds())) {
18997                for (int oneUserId : sUserManager.getUserIds()) {
18998                    scheduleWritePackageRestrictionsLocked(oneUserId);
18999                }
19000            }
19001        } else {
19002            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19003                scheduleWritePackageRestrictionsLocked(userId);
19004            }
19005        }
19006    }
19007
19008    void clearDefaultBrowserIfNeeded(String packageName) {
19009        for (int oneUserId : sUserManager.getUserIds()) {
19010            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19011            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19012            if (packageName.equals(defaultBrowserPackageName)) {
19013                setDefaultBrowserPackageName(null, oneUserId);
19014            }
19015        }
19016    }
19017
19018    @Override
19019    public void resetApplicationPreferences(int userId) {
19020        mContext.enforceCallingOrSelfPermission(
19021                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19022        final long identity = Binder.clearCallingIdentity();
19023        // writer
19024        try {
19025            synchronized (mPackages) {
19026                clearPackagePreferredActivitiesLPw(null, userId);
19027                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19028                // TODO: We have to reset the default SMS and Phone. This requires
19029                // significant refactoring to keep all default apps in the package
19030                // manager (cleaner but more work) or have the services provide
19031                // callbacks to the package manager to request a default app reset.
19032                applyFactoryDefaultBrowserLPw(userId);
19033                clearIntentFilterVerificationsLPw(userId);
19034                primeDomainVerificationsLPw(userId);
19035                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19036                scheduleWritePackageRestrictionsLocked(userId);
19037            }
19038            resetNetworkPolicies(userId);
19039        } finally {
19040            Binder.restoreCallingIdentity(identity);
19041        }
19042    }
19043
19044    @Override
19045    public int getPreferredActivities(List<IntentFilter> outFilters,
19046            List<ComponentName> outActivities, String packageName) {
19047
19048        int num = 0;
19049        final int userId = UserHandle.getCallingUserId();
19050        // reader
19051        synchronized (mPackages) {
19052            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19053            if (pir != null) {
19054                final Iterator<PreferredActivity> it = pir.filterIterator();
19055                while (it.hasNext()) {
19056                    final PreferredActivity pa = it.next();
19057                    if (packageName == null
19058                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19059                                    && pa.mPref.mAlways)) {
19060                        if (outFilters != null) {
19061                            outFilters.add(new IntentFilter(pa));
19062                        }
19063                        if (outActivities != null) {
19064                            outActivities.add(pa.mPref.mComponent);
19065                        }
19066                    }
19067                }
19068            }
19069        }
19070
19071        return num;
19072    }
19073
19074    @Override
19075    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19076            int userId) {
19077        int callingUid = Binder.getCallingUid();
19078        if (callingUid != Process.SYSTEM_UID) {
19079            throw new SecurityException(
19080                    "addPersistentPreferredActivity can only be run by the system");
19081        }
19082        if (filter.countActions() == 0) {
19083            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19084            return;
19085        }
19086        synchronized (mPackages) {
19087            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19088                    ":");
19089            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19090            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19091                    new PersistentPreferredActivity(filter, activity));
19092            scheduleWritePackageRestrictionsLocked(userId);
19093            postPreferredActivityChangedBroadcast(userId);
19094        }
19095    }
19096
19097    @Override
19098    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19099        int callingUid = Binder.getCallingUid();
19100        if (callingUid != Process.SYSTEM_UID) {
19101            throw new SecurityException(
19102                    "clearPackagePersistentPreferredActivities can only be run by the system");
19103        }
19104        ArrayList<PersistentPreferredActivity> removed = null;
19105        boolean changed = false;
19106        synchronized (mPackages) {
19107            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19108                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19109                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19110                        .valueAt(i);
19111                if (userId != thisUserId) {
19112                    continue;
19113                }
19114                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19115                while (it.hasNext()) {
19116                    PersistentPreferredActivity ppa = it.next();
19117                    // Mark entry for removal only if it matches the package name.
19118                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19119                        if (removed == null) {
19120                            removed = new ArrayList<PersistentPreferredActivity>();
19121                        }
19122                        removed.add(ppa);
19123                    }
19124                }
19125                if (removed != null) {
19126                    for (int j=0; j<removed.size(); j++) {
19127                        PersistentPreferredActivity ppa = removed.get(j);
19128                        ppir.removeFilter(ppa);
19129                    }
19130                    changed = true;
19131                }
19132            }
19133
19134            if (changed) {
19135                scheduleWritePackageRestrictionsLocked(userId);
19136                postPreferredActivityChangedBroadcast(userId);
19137            }
19138        }
19139    }
19140
19141    /**
19142     * Common machinery for picking apart a restored XML blob and passing
19143     * it to a caller-supplied functor to be applied to the running system.
19144     */
19145    private void restoreFromXml(XmlPullParser parser, int userId,
19146            String expectedStartTag, BlobXmlRestorer functor)
19147            throws IOException, XmlPullParserException {
19148        int type;
19149        while ((type = parser.next()) != XmlPullParser.START_TAG
19150                && type != XmlPullParser.END_DOCUMENT) {
19151        }
19152        if (type != XmlPullParser.START_TAG) {
19153            // oops didn't find a start tag?!
19154            if (DEBUG_BACKUP) {
19155                Slog.e(TAG, "Didn't find start tag during restore");
19156            }
19157            return;
19158        }
19159Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19160        // this is supposed to be TAG_PREFERRED_BACKUP
19161        if (!expectedStartTag.equals(parser.getName())) {
19162            if (DEBUG_BACKUP) {
19163                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19164            }
19165            return;
19166        }
19167
19168        // skip interfering stuff, then we're aligned with the backing implementation
19169        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19170Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19171        functor.apply(parser, userId);
19172    }
19173
19174    private interface BlobXmlRestorer {
19175        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19176    }
19177
19178    /**
19179     * Non-Binder method, support for the backup/restore mechanism: write the
19180     * full set of preferred activities in its canonical XML format.  Returns the
19181     * XML output as a byte array, or null if there is none.
19182     */
19183    @Override
19184    public byte[] getPreferredActivityBackup(int userId) {
19185        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19186            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19187        }
19188
19189        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19190        try {
19191            final XmlSerializer serializer = new FastXmlSerializer();
19192            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19193            serializer.startDocument(null, true);
19194            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19195
19196            synchronized (mPackages) {
19197                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19198            }
19199
19200            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19201            serializer.endDocument();
19202            serializer.flush();
19203        } catch (Exception e) {
19204            if (DEBUG_BACKUP) {
19205                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19206            }
19207            return null;
19208        }
19209
19210        return dataStream.toByteArray();
19211    }
19212
19213    @Override
19214    public void restorePreferredActivities(byte[] backup, int userId) {
19215        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19216            throw new SecurityException("Only the system may call restorePreferredActivities()");
19217        }
19218
19219        try {
19220            final XmlPullParser parser = Xml.newPullParser();
19221            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19222            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19223                    new BlobXmlRestorer() {
19224                        @Override
19225                        public void apply(XmlPullParser parser, int userId)
19226                                throws XmlPullParserException, IOException {
19227                            synchronized (mPackages) {
19228                                mSettings.readPreferredActivitiesLPw(parser, userId);
19229                            }
19230                        }
19231                    } );
19232        } catch (Exception e) {
19233            if (DEBUG_BACKUP) {
19234                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19235            }
19236        }
19237    }
19238
19239    /**
19240     * Non-Binder method, support for the backup/restore mechanism: write the
19241     * default browser (etc) settings in its canonical XML format.  Returns the default
19242     * browser XML representation as a byte array, or null if there is none.
19243     */
19244    @Override
19245    public byte[] getDefaultAppsBackup(int userId) {
19246        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19247            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19248        }
19249
19250        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19251        try {
19252            final XmlSerializer serializer = new FastXmlSerializer();
19253            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19254            serializer.startDocument(null, true);
19255            serializer.startTag(null, TAG_DEFAULT_APPS);
19256
19257            synchronized (mPackages) {
19258                mSettings.writeDefaultAppsLPr(serializer, userId);
19259            }
19260
19261            serializer.endTag(null, TAG_DEFAULT_APPS);
19262            serializer.endDocument();
19263            serializer.flush();
19264        } catch (Exception e) {
19265            if (DEBUG_BACKUP) {
19266                Slog.e(TAG, "Unable to write default apps for backup", e);
19267            }
19268            return null;
19269        }
19270
19271        return dataStream.toByteArray();
19272    }
19273
19274    @Override
19275    public void restoreDefaultApps(byte[] backup, int userId) {
19276        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19277            throw new SecurityException("Only the system may call restoreDefaultApps()");
19278        }
19279
19280        try {
19281            final XmlPullParser parser = Xml.newPullParser();
19282            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19283            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19284                    new BlobXmlRestorer() {
19285                        @Override
19286                        public void apply(XmlPullParser parser, int userId)
19287                                throws XmlPullParserException, IOException {
19288                            synchronized (mPackages) {
19289                                mSettings.readDefaultAppsLPw(parser, userId);
19290                            }
19291                        }
19292                    } );
19293        } catch (Exception e) {
19294            if (DEBUG_BACKUP) {
19295                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19296            }
19297        }
19298    }
19299
19300    @Override
19301    public byte[] getIntentFilterVerificationBackup(int userId) {
19302        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19303            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19304        }
19305
19306        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19307        try {
19308            final XmlSerializer serializer = new FastXmlSerializer();
19309            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19310            serializer.startDocument(null, true);
19311            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19312
19313            synchronized (mPackages) {
19314                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19315            }
19316
19317            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19318            serializer.endDocument();
19319            serializer.flush();
19320        } catch (Exception e) {
19321            if (DEBUG_BACKUP) {
19322                Slog.e(TAG, "Unable to write default apps for backup", e);
19323            }
19324            return null;
19325        }
19326
19327        return dataStream.toByteArray();
19328    }
19329
19330    @Override
19331    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19332        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19333            throw new SecurityException("Only the system may call restorePreferredActivities()");
19334        }
19335
19336        try {
19337            final XmlPullParser parser = Xml.newPullParser();
19338            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19339            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19340                    new BlobXmlRestorer() {
19341                        @Override
19342                        public void apply(XmlPullParser parser, int userId)
19343                                throws XmlPullParserException, IOException {
19344                            synchronized (mPackages) {
19345                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19346                                mSettings.writeLPr();
19347                            }
19348                        }
19349                    } );
19350        } catch (Exception e) {
19351            if (DEBUG_BACKUP) {
19352                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19353            }
19354        }
19355    }
19356
19357    @Override
19358    public byte[] getPermissionGrantBackup(int userId) {
19359        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19360            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19361        }
19362
19363        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19364        try {
19365            final XmlSerializer serializer = new FastXmlSerializer();
19366            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19367            serializer.startDocument(null, true);
19368            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19369
19370            synchronized (mPackages) {
19371                serializeRuntimePermissionGrantsLPr(serializer, userId);
19372            }
19373
19374            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19375            serializer.endDocument();
19376            serializer.flush();
19377        } catch (Exception e) {
19378            if (DEBUG_BACKUP) {
19379                Slog.e(TAG, "Unable to write default apps for backup", e);
19380            }
19381            return null;
19382        }
19383
19384        return dataStream.toByteArray();
19385    }
19386
19387    @Override
19388    public void restorePermissionGrants(byte[] backup, int userId) {
19389        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19390            throw new SecurityException("Only the system may call restorePermissionGrants()");
19391        }
19392
19393        try {
19394            final XmlPullParser parser = Xml.newPullParser();
19395            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19396            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19397                    new BlobXmlRestorer() {
19398                        @Override
19399                        public void apply(XmlPullParser parser, int userId)
19400                                throws XmlPullParserException, IOException {
19401                            synchronized (mPackages) {
19402                                processRestoredPermissionGrantsLPr(parser, userId);
19403                            }
19404                        }
19405                    } );
19406        } catch (Exception e) {
19407            if (DEBUG_BACKUP) {
19408                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19409            }
19410        }
19411    }
19412
19413    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19414            throws IOException {
19415        serializer.startTag(null, TAG_ALL_GRANTS);
19416
19417        final int N = mSettings.mPackages.size();
19418        for (int i = 0; i < N; i++) {
19419            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19420            boolean pkgGrantsKnown = false;
19421
19422            PermissionsState packagePerms = ps.getPermissionsState();
19423
19424            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19425                final int grantFlags = state.getFlags();
19426                // only look at grants that are not system/policy fixed
19427                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19428                    final boolean isGranted = state.isGranted();
19429                    // And only back up the user-twiddled state bits
19430                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19431                        final String packageName = mSettings.mPackages.keyAt(i);
19432                        if (!pkgGrantsKnown) {
19433                            serializer.startTag(null, TAG_GRANT);
19434                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19435                            pkgGrantsKnown = true;
19436                        }
19437
19438                        final boolean userSet =
19439                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19440                        final boolean userFixed =
19441                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19442                        final boolean revoke =
19443                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19444
19445                        serializer.startTag(null, TAG_PERMISSION);
19446                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19447                        if (isGranted) {
19448                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19449                        }
19450                        if (userSet) {
19451                            serializer.attribute(null, ATTR_USER_SET, "true");
19452                        }
19453                        if (userFixed) {
19454                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19455                        }
19456                        if (revoke) {
19457                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19458                        }
19459                        serializer.endTag(null, TAG_PERMISSION);
19460                    }
19461                }
19462            }
19463
19464            if (pkgGrantsKnown) {
19465                serializer.endTag(null, TAG_GRANT);
19466            }
19467        }
19468
19469        serializer.endTag(null, TAG_ALL_GRANTS);
19470    }
19471
19472    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19473            throws XmlPullParserException, IOException {
19474        String pkgName = null;
19475        int outerDepth = parser.getDepth();
19476        int type;
19477        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19478                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19479            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19480                continue;
19481            }
19482
19483            final String tagName = parser.getName();
19484            if (tagName.equals(TAG_GRANT)) {
19485                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19486                if (DEBUG_BACKUP) {
19487                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19488                }
19489            } else if (tagName.equals(TAG_PERMISSION)) {
19490
19491                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19492                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19493
19494                int newFlagSet = 0;
19495                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19496                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19497                }
19498                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19499                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19500                }
19501                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19502                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19503                }
19504                if (DEBUG_BACKUP) {
19505                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19506                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19507                }
19508                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19509                if (ps != null) {
19510                    // Already installed so we apply the grant immediately
19511                    if (DEBUG_BACKUP) {
19512                        Slog.v(TAG, "        + already installed; applying");
19513                    }
19514                    PermissionsState perms = ps.getPermissionsState();
19515                    BasePermission bp = mSettings.mPermissions.get(permName);
19516                    if (bp != null) {
19517                        if (isGranted) {
19518                            perms.grantRuntimePermission(bp, userId);
19519                        }
19520                        if (newFlagSet != 0) {
19521                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19522                        }
19523                    }
19524                } else {
19525                    // Need to wait for post-restore install to apply the grant
19526                    if (DEBUG_BACKUP) {
19527                        Slog.v(TAG, "        - not yet installed; saving for later");
19528                    }
19529                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19530                            isGranted, newFlagSet, userId);
19531                }
19532            } else {
19533                PackageManagerService.reportSettingsProblem(Log.WARN,
19534                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19535                XmlUtils.skipCurrentTag(parser);
19536            }
19537        }
19538
19539        scheduleWriteSettingsLocked();
19540        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19541    }
19542
19543    @Override
19544    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19545            int sourceUserId, int targetUserId, int flags) {
19546        mContext.enforceCallingOrSelfPermission(
19547                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19548        int callingUid = Binder.getCallingUid();
19549        enforceOwnerRights(ownerPackage, callingUid);
19550        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19551        if (intentFilter.countActions() == 0) {
19552            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19553            return;
19554        }
19555        synchronized (mPackages) {
19556            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19557                    ownerPackage, targetUserId, flags);
19558            CrossProfileIntentResolver resolver =
19559                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19560            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19561            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19562            if (existing != null) {
19563                int size = existing.size();
19564                for (int i = 0; i < size; i++) {
19565                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19566                        return;
19567                    }
19568                }
19569            }
19570            resolver.addFilter(newFilter);
19571            scheduleWritePackageRestrictionsLocked(sourceUserId);
19572        }
19573    }
19574
19575    @Override
19576    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19577        mContext.enforceCallingOrSelfPermission(
19578                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19579        int callingUid = Binder.getCallingUid();
19580        enforceOwnerRights(ownerPackage, callingUid);
19581        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19582        synchronized (mPackages) {
19583            CrossProfileIntentResolver resolver =
19584                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19585            ArraySet<CrossProfileIntentFilter> set =
19586                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19587            for (CrossProfileIntentFilter filter : set) {
19588                if (filter.getOwnerPackage().equals(ownerPackage)) {
19589                    resolver.removeFilter(filter);
19590                }
19591            }
19592            scheduleWritePackageRestrictionsLocked(sourceUserId);
19593        }
19594    }
19595
19596    // Enforcing that callingUid is owning pkg on userId
19597    private void enforceOwnerRights(String pkg, int callingUid) {
19598        // The system owns everything.
19599        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19600            return;
19601        }
19602        int callingUserId = UserHandle.getUserId(callingUid);
19603        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19604        if (pi == null) {
19605            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19606                    + callingUserId);
19607        }
19608        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19609            throw new SecurityException("Calling uid " + callingUid
19610                    + " does not own package " + pkg);
19611        }
19612    }
19613
19614    @Override
19615    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19616        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19617    }
19618
19619    private Intent getHomeIntent() {
19620        Intent intent = new Intent(Intent.ACTION_MAIN);
19621        intent.addCategory(Intent.CATEGORY_HOME);
19622        intent.addCategory(Intent.CATEGORY_DEFAULT);
19623        return intent;
19624    }
19625
19626    private IntentFilter getHomeFilter() {
19627        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19628        filter.addCategory(Intent.CATEGORY_HOME);
19629        filter.addCategory(Intent.CATEGORY_DEFAULT);
19630        return filter;
19631    }
19632
19633    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19634            int userId) {
19635        Intent intent  = getHomeIntent();
19636        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19637                PackageManager.GET_META_DATA, userId);
19638        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19639                true, false, false, userId);
19640
19641        allHomeCandidates.clear();
19642        if (list != null) {
19643            for (ResolveInfo ri : list) {
19644                allHomeCandidates.add(ri);
19645            }
19646        }
19647        return (preferred == null || preferred.activityInfo == null)
19648                ? null
19649                : new ComponentName(preferred.activityInfo.packageName,
19650                        preferred.activityInfo.name);
19651    }
19652
19653    @Override
19654    public void setHomeActivity(ComponentName comp, int userId) {
19655        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19656        getHomeActivitiesAsUser(homeActivities, userId);
19657
19658        boolean found = false;
19659
19660        final int size = homeActivities.size();
19661        final ComponentName[] set = new ComponentName[size];
19662        for (int i = 0; i < size; i++) {
19663            final ResolveInfo candidate = homeActivities.get(i);
19664            final ActivityInfo info = candidate.activityInfo;
19665            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19666            set[i] = activityName;
19667            if (!found && activityName.equals(comp)) {
19668                found = true;
19669            }
19670        }
19671        if (!found) {
19672            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19673                    + userId);
19674        }
19675        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19676                set, comp, userId);
19677    }
19678
19679    private @Nullable String getSetupWizardPackageName() {
19680        final Intent intent = new Intent(Intent.ACTION_MAIN);
19681        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19682
19683        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19684                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19685                        | MATCH_DISABLED_COMPONENTS,
19686                UserHandle.myUserId());
19687        if (matches.size() == 1) {
19688            return matches.get(0).getComponentInfo().packageName;
19689        } else {
19690            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19691                    + ": matches=" + matches);
19692            return null;
19693        }
19694    }
19695
19696    private @Nullable String getStorageManagerPackageName() {
19697        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19698
19699        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19700                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19701                        | MATCH_DISABLED_COMPONENTS,
19702                UserHandle.myUserId());
19703        if (matches.size() == 1) {
19704            return matches.get(0).getComponentInfo().packageName;
19705        } else {
19706            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19707                    + matches.size() + ": matches=" + matches);
19708            return null;
19709        }
19710    }
19711
19712    @Override
19713    public void setApplicationEnabledSetting(String appPackageName,
19714            int newState, int flags, int userId, String callingPackage) {
19715        if (!sUserManager.exists(userId)) return;
19716        if (callingPackage == null) {
19717            callingPackage = Integer.toString(Binder.getCallingUid());
19718        }
19719        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19720    }
19721
19722    @Override
19723    public void setComponentEnabledSetting(ComponentName componentName,
19724            int newState, int flags, int userId) {
19725        if (!sUserManager.exists(userId)) return;
19726        setEnabledSetting(componentName.getPackageName(),
19727                componentName.getClassName(), newState, flags, userId, null);
19728    }
19729
19730    private void setEnabledSetting(final String packageName, String className, int newState,
19731            final int flags, int userId, String callingPackage) {
19732        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19733              || newState == COMPONENT_ENABLED_STATE_ENABLED
19734              || newState == COMPONENT_ENABLED_STATE_DISABLED
19735              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19736              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19737            throw new IllegalArgumentException("Invalid new component state: "
19738                    + newState);
19739        }
19740        PackageSetting pkgSetting;
19741        final int uid = Binder.getCallingUid();
19742        final int permission;
19743        if (uid == Process.SYSTEM_UID) {
19744            permission = PackageManager.PERMISSION_GRANTED;
19745        } else {
19746            permission = mContext.checkCallingOrSelfPermission(
19747                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19748        }
19749        enforceCrossUserPermission(uid, userId,
19750                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19751        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19752        boolean sendNow = false;
19753        boolean isApp = (className == null);
19754        String componentName = isApp ? packageName : className;
19755        int packageUid = -1;
19756        ArrayList<String> components;
19757
19758        // writer
19759        synchronized (mPackages) {
19760            pkgSetting = mSettings.mPackages.get(packageName);
19761            if (pkgSetting == null) {
19762                if (className == null) {
19763                    throw new IllegalArgumentException("Unknown package: " + packageName);
19764                }
19765                throw new IllegalArgumentException(
19766                        "Unknown component: " + packageName + "/" + className);
19767            }
19768        }
19769
19770        // Limit who can change which apps
19771        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19772            // Don't allow apps that don't have permission to modify other apps
19773            if (!allowedByPermission) {
19774                throw new SecurityException(
19775                        "Permission Denial: attempt to change component state from pid="
19776                        + Binder.getCallingPid()
19777                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19778            }
19779            // Don't allow changing protected packages.
19780            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19781                throw new SecurityException("Cannot disable a protected package: " + packageName);
19782            }
19783        }
19784
19785        synchronized (mPackages) {
19786            if (uid == Process.SHELL_UID
19787                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19788                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19789                // unless it is a test package.
19790                int oldState = pkgSetting.getEnabled(userId);
19791                if (className == null
19792                    &&
19793                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19794                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19795                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19796                    &&
19797                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19798                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19799                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19800                    // ok
19801                } else {
19802                    throw new SecurityException(
19803                            "Shell cannot change component state for " + packageName + "/"
19804                            + className + " to " + newState);
19805                }
19806            }
19807            if (className == null) {
19808                // We're dealing with an application/package level state change
19809                if (pkgSetting.getEnabled(userId) == newState) {
19810                    // Nothing to do
19811                    return;
19812                }
19813                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19814                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19815                    // Don't care about who enables an app.
19816                    callingPackage = null;
19817                }
19818                pkgSetting.setEnabled(newState, userId, callingPackage);
19819                // pkgSetting.pkg.mSetEnabled = newState;
19820            } else {
19821                // We're dealing with a component level state change
19822                // First, verify that this is a valid class name.
19823                PackageParser.Package pkg = pkgSetting.pkg;
19824                if (pkg == null || !pkg.hasComponentClassName(className)) {
19825                    if (pkg != null &&
19826                            pkg.applicationInfo.targetSdkVersion >=
19827                                    Build.VERSION_CODES.JELLY_BEAN) {
19828                        throw new IllegalArgumentException("Component class " + className
19829                                + " does not exist in " + packageName);
19830                    } else {
19831                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19832                                + className + " does not exist in " + packageName);
19833                    }
19834                }
19835                switch (newState) {
19836                case COMPONENT_ENABLED_STATE_ENABLED:
19837                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19838                        return;
19839                    }
19840                    break;
19841                case COMPONENT_ENABLED_STATE_DISABLED:
19842                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19843                        return;
19844                    }
19845                    break;
19846                case COMPONENT_ENABLED_STATE_DEFAULT:
19847                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19848                        return;
19849                    }
19850                    break;
19851                default:
19852                    Slog.e(TAG, "Invalid new component state: " + newState);
19853                    return;
19854                }
19855            }
19856            scheduleWritePackageRestrictionsLocked(userId);
19857            updateSequenceNumberLP(packageName, new int[] { userId });
19858            components = mPendingBroadcasts.get(userId, packageName);
19859            final boolean newPackage = components == null;
19860            if (newPackage) {
19861                components = new ArrayList<String>();
19862            }
19863            if (!components.contains(componentName)) {
19864                components.add(componentName);
19865            }
19866            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19867                sendNow = true;
19868                // Purge entry from pending broadcast list if another one exists already
19869                // since we are sending one right away.
19870                mPendingBroadcasts.remove(userId, packageName);
19871            } else {
19872                if (newPackage) {
19873                    mPendingBroadcasts.put(userId, packageName, components);
19874                }
19875                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19876                    // Schedule a message
19877                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19878                }
19879            }
19880        }
19881
19882        long callingId = Binder.clearCallingIdentity();
19883        try {
19884            if (sendNow) {
19885                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19886                sendPackageChangedBroadcast(packageName,
19887                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19888            }
19889        } finally {
19890            Binder.restoreCallingIdentity(callingId);
19891        }
19892    }
19893
19894    @Override
19895    public void flushPackageRestrictionsAsUser(int userId) {
19896        if (!sUserManager.exists(userId)) {
19897            return;
19898        }
19899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19900                false /* checkShell */, "flushPackageRestrictions");
19901        synchronized (mPackages) {
19902            mSettings.writePackageRestrictionsLPr(userId);
19903            mDirtyUsers.remove(userId);
19904            if (mDirtyUsers.isEmpty()) {
19905                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19906            }
19907        }
19908    }
19909
19910    private void sendPackageChangedBroadcast(String packageName,
19911            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19912        if (DEBUG_INSTALL)
19913            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19914                    + componentNames);
19915        Bundle extras = new Bundle(4);
19916        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19917        String nameList[] = new String[componentNames.size()];
19918        componentNames.toArray(nameList);
19919        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19920        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19921        extras.putInt(Intent.EXTRA_UID, packageUid);
19922        // If this is not reporting a change of the overall package, then only send it
19923        // to registered receivers.  We don't want to launch a swath of apps for every
19924        // little component state change.
19925        final int flags = !componentNames.contains(packageName)
19926                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19927        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19928                new int[] {UserHandle.getUserId(packageUid)});
19929    }
19930
19931    @Override
19932    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19933        if (!sUserManager.exists(userId)) return;
19934        final int uid = Binder.getCallingUid();
19935        final int permission = mContext.checkCallingOrSelfPermission(
19936                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19937        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19938        enforceCrossUserPermission(uid, userId,
19939                true /* requireFullPermission */, true /* checkShell */, "stop package");
19940        // writer
19941        synchronized (mPackages) {
19942            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19943                    allowedByPermission, uid, userId)) {
19944                scheduleWritePackageRestrictionsLocked(userId);
19945            }
19946        }
19947    }
19948
19949    @Override
19950    public String getInstallerPackageName(String packageName) {
19951        // reader
19952        synchronized (mPackages) {
19953            return mSettings.getInstallerPackageNameLPr(packageName);
19954        }
19955    }
19956
19957    public boolean isOrphaned(String packageName) {
19958        // reader
19959        synchronized (mPackages) {
19960            return mSettings.isOrphaned(packageName);
19961        }
19962    }
19963
19964    @Override
19965    public int getApplicationEnabledSetting(String packageName, int userId) {
19966        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19967        int uid = Binder.getCallingUid();
19968        enforceCrossUserPermission(uid, userId,
19969                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19970        // reader
19971        synchronized (mPackages) {
19972            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19973        }
19974    }
19975
19976    @Override
19977    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19978        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19979        int uid = Binder.getCallingUid();
19980        enforceCrossUserPermission(uid, userId,
19981                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19982        // reader
19983        synchronized (mPackages) {
19984            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19985        }
19986    }
19987
19988    @Override
19989    public void enterSafeMode() {
19990        enforceSystemOrRoot("Only the system can request entering safe mode");
19991
19992        if (!mSystemReady) {
19993            mSafeMode = true;
19994        }
19995    }
19996
19997    @Override
19998    public void systemReady() {
19999        mSystemReady = true;
20000
20001        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20002        // disabled after already being started.
20003        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20004                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20005
20006        // Read the compatibilty setting when the system is ready.
20007        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20008                mContext.getContentResolver(),
20009                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20010        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20011        if (DEBUG_SETTINGS) {
20012            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20013        }
20014
20015        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20016
20017        synchronized (mPackages) {
20018            // Verify that all of the preferred activity components actually
20019            // exist.  It is possible for applications to be updated and at
20020            // that point remove a previously declared activity component that
20021            // had been set as a preferred activity.  We try to clean this up
20022            // the next time we encounter that preferred activity, but it is
20023            // possible for the user flow to never be able to return to that
20024            // situation so here we do a sanity check to make sure we haven't
20025            // left any junk around.
20026            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20027            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20028                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20029                removed.clear();
20030                for (PreferredActivity pa : pir.filterSet()) {
20031                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20032                        removed.add(pa);
20033                    }
20034                }
20035                if (removed.size() > 0) {
20036                    for (int r=0; r<removed.size(); r++) {
20037                        PreferredActivity pa = removed.get(r);
20038                        Slog.w(TAG, "Removing dangling preferred activity: "
20039                                + pa.mPref.mComponent);
20040                        pir.removeFilter(pa);
20041                    }
20042                    mSettings.writePackageRestrictionsLPr(
20043                            mSettings.mPreferredActivities.keyAt(i));
20044                }
20045            }
20046
20047            for (int userId : UserManagerService.getInstance().getUserIds()) {
20048                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20049                    grantPermissionsUserIds = ArrayUtils.appendInt(
20050                            grantPermissionsUserIds, userId);
20051                }
20052            }
20053        }
20054        sUserManager.systemReady();
20055
20056        // If we upgraded grant all default permissions before kicking off.
20057        for (int userId : grantPermissionsUserIds) {
20058            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20059        }
20060
20061        // If we did not grant default permissions, we preload from this the
20062        // default permission exceptions lazily to ensure we don't hit the
20063        // disk on a new user creation.
20064        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20065            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20066        }
20067
20068        // Kick off any messages waiting for system ready
20069        if (mPostSystemReadyMessages != null) {
20070            for (Message msg : mPostSystemReadyMessages) {
20071                msg.sendToTarget();
20072            }
20073            mPostSystemReadyMessages = null;
20074        }
20075
20076        // Watch for external volumes that come and go over time
20077        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20078        storage.registerListener(mStorageListener);
20079
20080        mInstallerService.systemReady();
20081        mPackageDexOptimizer.systemReady();
20082
20083        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20084                StorageManagerInternal.class);
20085        StorageManagerInternal.addExternalStoragePolicy(
20086                new StorageManagerInternal.ExternalStorageMountPolicy() {
20087            @Override
20088            public int getMountMode(int uid, String packageName) {
20089                if (Process.isIsolated(uid)) {
20090                    return Zygote.MOUNT_EXTERNAL_NONE;
20091                }
20092                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20093                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20094                }
20095                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20096                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20097                }
20098                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20099                    return Zygote.MOUNT_EXTERNAL_READ;
20100                }
20101                return Zygote.MOUNT_EXTERNAL_WRITE;
20102            }
20103
20104            @Override
20105            public boolean hasExternalStorage(int uid, String packageName) {
20106                return true;
20107            }
20108        });
20109
20110        // Now that we're mostly running, clean up stale users and apps
20111        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20112        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20113
20114        if (mPrivappPermissionsViolations != null) {
20115            Slog.wtf(TAG,"Signature|privileged permissions not in "
20116                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20117            mPrivappPermissionsViolations = null;
20118        }
20119    }
20120
20121    public void waitForAppDataPrepared() {
20122        if (mPrepareAppDataFuture == null) {
20123            return;
20124        }
20125        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20126        mPrepareAppDataFuture = null;
20127    }
20128
20129    @Override
20130    public boolean isSafeMode() {
20131        return mSafeMode;
20132    }
20133
20134    @Override
20135    public boolean hasSystemUidErrors() {
20136        return mHasSystemUidErrors;
20137    }
20138
20139    static String arrayToString(int[] array) {
20140        StringBuffer buf = new StringBuffer(128);
20141        buf.append('[');
20142        if (array != null) {
20143            for (int i=0; i<array.length; i++) {
20144                if (i > 0) buf.append(", ");
20145                buf.append(array[i]);
20146            }
20147        }
20148        buf.append(']');
20149        return buf.toString();
20150    }
20151
20152    static class DumpState {
20153        public static final int DUMP_LIBS = 1 << 0;
20154        public static final int DUMP_FEATURES = 1 << 1;
20155        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20156        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20157        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20158        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20159        public static final int DUMP_PERMISSIONS = 1 << 6;
20160        public static final int DUMP_PACKAGES = 1 << 7;
20161        public static final int DUMP_SHARED_USERS = 1 << 8;
20162        public static final int DUMP_MESSAGES = 1 << 9;
20163        public static final int DUMP_PROVIDERS = 1 << 10;
20164        public static final int DUMP_VERIFIERS = 1 << 11;
20165        public static final int DUMP_PREFERRED = 1 << 12;
20166        public static final int DUMP_PREFERRED_XML = 1 << 13;
20167        public static final int DUMP_KEYSETS = 1 << 14;
20168        public static final int DUMP_VERSION = 1 << 15;
20169        public static final int DUMP_INSTALLS = 1 << 16;
20170        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20171        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20172        public static final int DUMP_FROZEN = 1 << 19;
20173        public static final int DUMP_DEXOPT = 1 << 20;
20174        public static final int DUMP_COMPILER_STATS = 1 << 21;
20175        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20176
20177        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20178
20179        private int mTypes;
20180
20181        private int mOptions;
20182
20183        private boolean mTitlePrinted;
20184
20185        private SharedUserSetting mSharedUser;
20186
20187        public boolean isDumping(int type) {
20188            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20189                return true;
20190            }
20191
20192            return (mTypes & type) != 0;
20193        }
20194
20195        public void setDump(int type) {
20196            mTypes |= type;
20197        }
20198
20199        public boolean isOptionEnabled(int option) {
20200            return (mOptions & option) != 0;
20201        }
20202
20203        public void setOptionEnabled(int option) {
20204            mOptions |= option;
20205        }
20206
20207        public boolean onTitlePrinted() {
20208            final boolean printed = mTitlePrinted;
20209            mTitlePrinted = true;
20210            return printed;
20211        }
20212
20213        public boolean getTitlePrinted() {
20214            return mTitlePrinted;
20215        }
20216
20217        public void setTitlePrinted(boolean enabled) {
20218            mTitlePrinted = enabled;
20219        }
20220
20221        public SharedUserSetting getSharedUser() {
20222            return mSharedUser;
20223        }
20224
20225        public void setSharedUser(SharedUserSetting user) {
20226            mSharedUser = user;
20227        }
20228    }
20229
20230    @Override
20231    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20232            FileDescriptor err, String[] args, ShellCallback callback,
20233            ResultReceiver resultReceiver) {
20234        (new PackageManagerShellCommand(this)).exec(
20235                this, in, out, err, args, callback, resultReceiver);
20236    }
20237
20238    @Override
20239    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20240        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20241                != PackageManager.PERMISSION_GRANTED) {
20242            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20243                    + Binder.getCallingPid()
20244                    + ", uid=" + Binder.getCallingUid()
20245                    + " without permission "
20246                    + android.Manifest.permission.DUMP);
20247            return;
20248        }
20249
20250        DumpState dumpState = new DumpState();
20251        boolean fullPreferred = false;
20252        boolean checkin = false;
20253
20254        String packageName = null;
20255        ArraySet<String> permissionNames = null;
20256
20257        int opti = 0;
20258        while (opti < args.length) {
20259            String opt = args[opti];
20260            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20261                break;
20262            }
20263            opti++;
20264
20265            if ("-a".equals(opt)) {
20266                // Right now we only know how to print all.
20267            } else if ("-h".equals(opt)) {
20268                pw.println("Package manager dump options:");
20269                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20270                pw.println("    --checkin: dump for a checkin");
20271                pw.println("    -f: print details of intent filters");
20272                pw.println("    -h: print this help");
20273                pw.println("  cmd may be one of:");
20274                pw.println("    l[ibraries]: list known shared libraries");
20275                pw.println("    f[eatures]: list device features");
20276                pw.println("    k[eysets]: print known keysets");
20277                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20278                pw.println("    perm[issions]: dump permissions");
20279                pw.println("    permission [name ...]: dump declaration and use of given permission");
20280                pw.println("    pref[erred]: print preferred package settings");
20281                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20282                pw.println("    prov[iders]: dump content providers");
20283                pw.println("    p[ackages]: dump installed packages");
20284                pw.println("    s[hared-users]: dump shared user IDs");
20285                pw.println("    m[essages]: print collected runtime messages");
20286                pw.println("    v[erifiers]: print package verifier info");
20287                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20288                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20289                pw.println("    version: print database version info");
20290                pw.println("    write: write current settings now");
20291                pw.println("    installs: details about install sessions");
20292                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20293                pw.println("    dexopt: dump dexopt state");
20294                pw.println("    compiler-stats: dump compiler statistics");
20295                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20296                pw.println("    <package.name>: info about given package");
20297                return;
20298            } else if ("--checkin".equals(opt)) {
20299                checkin = true;
20300            } else if ("-f".equals(opt)) {
20301                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20302            } else {
20303                pw.println("Unknown argument: " + opt + "; use -h for help");
20304            }
20305        }
20306
20307        // Is the caller requesting to dump a particular piece of data?
20308        if (opti < args.length) {
20309            String cmd = args[opti];
20310            opti++;
20311            // Is this a package name?
20312            if ("android".equals(cmd) || cmd.contains(".")) {
20313                packageName = cmd;
20314                // When dumping a single package, we always dump all of its
20315                // filter information since the amount of data will be reasonable.
20316                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20317            } else if ("check-permission".equals(cmd)) {
20318                if (opti >= args.length) {
20319                    pw.println("Error: check-permission missing permission argument");
20320                    return;
20321                }
20322                String perm = args[opti];
20323                opti++;
20324                if (opti >= args.length) {
20325                    pw.println("Error: check-permission missing package argument");
20326                    return;
20327                }
20328
20329                String pkg = args[opti];
20330                opti++;
20331                int user = UserHandle.getUserId(Binder.getCallingUid());
20332                if (opti < args.length) {
20333                    try {
20334                        user = Integer.parseInt(args[opti]);
20335                    } catch (NumberFormatException e) {
20336                        pw.println("Error: check-permission user argument is not a number: "
20337                                + args[opti]);
20338                        return;
20339                    }
20340                }
20341
20342                // Normalize package name to handle renamed packages and static libs
20343                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20344
20345                pw.println(checkPermission(perm, pkg, user));
20346                return;
20347            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_LIBS);
20349            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20350                dumpState.setDump(DumpState.DUMP_FEATURES);
20351            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20352                if (opti >= args.length) {
20353                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20354                            | DumpState.DUMP_SERVICE_RESOLVERS
20355                            | DumpState.DUMP_RECEIVER_RESOLVERS
20356                            | DumpState.DUMP_CONTENT_RESOLVERS);
20357                } else {
20358                    while (opti < args.length) {
20359                        String name = args[opti];
20360                        if ("a".equals(name) || "activity".equals(name)) {
20361                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20362                        } else if ("s".equals(name) || "service".equals(name)) {
20363                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20364                        } else if ("r".equals(name) || "receiver".equals(name)) {
20365                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20366                        } else if ("c".equals(name) || "content".equals(name)) {
20367                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20368                        } else {
20369                            pw.println("Error: unknown resolver table type: " + name);
20370                            return;
20371                        }
20372                        opti++;
20373                    }
20374                }
20375            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20376                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20377            } else if ("permission".equals(cmd)) {
20378                if (opti >= args.length) {
20379                    pw.println("Error: permission requires permission name");
20380                    return;
20381                }
20382                permissionNames = new ArraySet<>();
20383                while (opti < args.length) {
20384                    permissionNames.add(args[opti]);
20385                    opti++;
20386                }
20387                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20388                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20389            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20390                dumpState.setDump(DumpState.DUMP_PREFERRED);
20391            } else if ("preferred-xml".equals(cmd)) {
20392                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20393                if (opti < args.length && "--full".equals(args[opti])) {
20394                    fullPreferred = true;
20395                    opti++;
20396                }
20397            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20398                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20399            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20400                dumpState.setDump(DumpState.DUMP_PACKAGES);
20401            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20402                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20403            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20405            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20406                dumpState.setDump(DumpState.DUMP_MESSAGES);
20407            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20408                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20409            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20410                    || "intent-filter-verifiers".equals(cmd)) {
20411                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20412            } else if ("version".equals(cmd)) {
20413                dumpState.setDump(DumpState.DUMP_VERSION);
20414            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20415                dumpState.setDump(DumpState.DUMP_KEYSETS);
20416            } else if ("installs".equals(cmd)) {
20417                dumpState.setDump(DumpState.DUMP_INSTALLS);
20418            } else if ("frozen".equals(cmd)) {
20419                dumpState.setDump(DumpState.DUMP_FROZEN);
20420            } else if ("dexopt".equals(cmd)) {
20421                dumpState.setDump(DumpState.DUMP_DEXOPT);
20422            } else if ("compiler-stats".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20424            } else if ("enabled-overlays".equals(cmd)) {
20425                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20426            } else if ("write".equals(cmd)) {
20427                synchronized (mPackages) {
20428                    mSettings.writeLPr();
20429                    pw.println("Settings written.");
20430                    return;
20431                }
20432            }
20433        }
20434
20435        if (checkin) {
20436            pw.println("vers,1");
20437        }
20438
20439        // reader
20440        synchronized (mPackages) {
20441            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20442                if (!checkin) {
20443                    if (dumpState.onTitlePrinted())
20444                        pw.println();
20445                    pw.println("Database versions:");
20446                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20447                }
20448            }
20449
20450            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20451                if (!checkin) {
20452                    if (dumpState.onTitlePrinted())
20453                        pw.println();
20454                    pw.println("Verifiers:");
20455                    pw.print("  Required: ");
20456                    pw.print(mRequiredVerifierPackage);
20457                    pw.print(" (uid=");
20458                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20459                            UserHandle.USER_SYSTEM));
20460                    pw.println(")");
20461                } else if (mRequiredVerifierPackage != null) {
20462                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20463                    pw.print(",");
20464                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20465                            UserHandle.USER_SYSTEM));
20466                }
20467            }
20468
20469            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20470                    packageName == null) {
20471                if (mIntentFilterVerifierComponent != null) {
20472                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20473                    if (!checkin) {
20474                        if (dumpState.onTitlePrinted())
20475                            pw.println();
20476                        pw.println("Intent Filter Verifier:");
20477                        pw.print("  Using: ");
20478                        pw.print(verifierPackageName);
20479                        pw.print(" (uid=");
20480                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20481                                UserHandle.USER_SYSTEM));
20482                        pw.println(")");
20483                    } else if (verifierPackageName != null) {
20484                        pw.print("ifv,"); pw.print(verifierPackageName);
20485                        pw.print(",");
20486                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20487                                UserHandle.USER_SYSTEM));
20488                    }
20489                } else {
20490                    pw.println();
20491                    pw.println("No Intent Filter Verifier available!");
20492                }
20493            }
20494
20495            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20496                boolean printedHeader = false;
20497                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20498                while (it.hasNext()) {
20499                    String libName = it.next();
20500                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20501                    if (versionedLib == null) {
20502                        continue;
20503                    }
20504                    final int versionCount = versionedLib.size();
20505                    for (int i = 0; i < versionCount; i++) {
20506                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20507                        if (!checkin) {
20508                            if (!printedHeader) {
20509                                if (dumpState.onTitlePrinted())
20510                                    pw.println();
20511                                pw.println("Libraries:");
20512                                printedHeader = true;
20513                            }
20514                            pw.print("  ");
20515                        } else {
20516                            pw.print("lib,");
20517                        }
20518                        pw.print(libEntry.info.getName());
20519                        if (libEntry.info.isStatic()) {
20520                            pw.print(" version=" + libEntry.info.getVersion());
20521                        }
20522                        if (!checkin) {
20523                            pw.print(" -> ");
20524                        }
20525                        if (libEntry.path != null) {
20526                            pw.print(" (jar) ");
20527                            pw.print(libEntry.path);
20528                        } else {
20529                            pw.print(" (apk) ");
20530                            pw.print(libEntry.apk);
20531                        }
20532                        pw.println();
20533                    }
20534                }
20535            }
20536
20537            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20538                if (dumpState.onTitlePrinted())
20539                    pw.println();
20540                if (!checkin) {
20541                    pw.println("Features:");
20542                }
20543
20544                synchronized (mAvailableFeatures) {
20545                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20546                        if (checkin) {
20547                            pw.print("feat,");
20548                            pw.print(feat.name);
20549                            pw.print(",");
20550                            pw.println(feat.version);
20551                        } else {
20552                            pw.print("  ");
20553                            pw.print(feat.name);
20554                            if (feat.version > 0) {
20555                                pw.print(" version=");
20556                                pw.print(feat.version);
20557                            }
20558                            pw.println();
20559                        }
20560                    }
20561                }
20562            }
20563
20564            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20565                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20566                        : "Activity Resolver Table:", "  ", packageName,
20567                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20568                    dumpState.setTitlePrinted(true);
20569                }
20570            }
20571            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20572                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20573                        : "Receiver Resolver Table:", "  ", packageName,
20574                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20575                    dumpState.setTitlePrinted(true);
20576                }
20577            }
20578            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20579                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20580                        : "Service Resolver Table:", "  ", packageName,
20581                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20582                    dumpState.setTitlePrinted(true);
20583                }
20584            }
20585            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20586                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20587                        : "Provider Resolver Table:", "  ", packageName,
20588                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20589                    dumpState.setTitlePrinted(true);
20590                }
20591            }
20592
20593            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20594                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20595                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20596                    int user = mSettings.mPreferredActivities.keyAt(i);
20597                    if (pir.dump(pw,
20598                            dumpState.getTitlePrinted()
20599                                ? "\nPreferred Activities User " + user + ":"
20600                                : "Preferred Activities User " + user + ":", "  ",
20601                            packageName, true, false)) {
20602                        dumpState.setTitlePrinted(true);
20603                    }
20604                }
20605            }
20606
20607            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20608                pw.flush();
20609                FileOutputStream fout = new FileOutputStream(fd);
20610                BufferedOutputStream str = new BufferedOutputStream(fout);
20611                XmlSerializer serializer = new FastXmlSerializer();
20612                try {
20613                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20614                    serializer.startDocument(null, true);
20615                    serializer.setFeature(
20616                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20617                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20618                    serializer.endDocument();
20619                    serializer.flush();
20620                } catch (IllegalArgumentException e) {
20621                    pw.println("Failed writing: " + e);
20622                } catch (IllegalStateException e) {
20623                    pw.println("Failed writing: " + e);
20624                } catch (IOException e) {
20625                    pw.println("Failed writing: " + e);
20626                }
20627            }
20628
20629            if (!checkin
20630                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20631                    && packageName == null) {
20632                pw.println();
20633                int count = mSettings.mPackages.size();
20634                if (count == 0) {
20635                    pw.println("No applications!");
20636                    pw.println();
20637                } else {
20638                    final String prefix = "  ";
20639                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20640                    if (allPackageSettings.size() == 0) {
20641                        pw.println("No domain preferred apps!");
20642                        pw.println();
20643                    } else {
20644                        pw.println("App verification status:");
20645                        pw.println();
20646                        count = 0;
20647                        for (PackageSetting ps : allPackageSettings) {
20648                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20649                            if (ivi == null || ivi.getPackageName() == null) continue;
20650                            pw.println(prefix + "Package: " + ivi.getPackageName());
20651                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20652                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20653                            pw.println();
20654                            count++;
20655                        }
20656                        if (count == 0) {
20657                            pw.println(prefix + "No app verification established.");
20658                            pw.println();
20659                        }
20660                        for (int userId : sUserManager.getUserIds()) {
20661                            pw.println("App linkages for user " + userId + ":");
20662                            pw.println();
20663                            count = 0;
20664                            for (PackageSetting ps : allPackageSettings) {
20665                                final long status = ps.getDomainVerificationStatusForUser(userId);
20666                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20667                                        && !DEBUG_DOMAIN_VERIFICATION) {
20668                                    continue;
20669                                }
20670                                pw.println(prefix + "Package: " + ps.name);
20671                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20672                                String statusStr = IntentFilterVerificationInfo.
20673                                        getStatusStringFromValue(status);
20674                                pw.println(prefix + "Status:  " + statusStr);
20675                                pw.println();
20676                                count++;
20677                            }
20678                            if (count == 0) {
20679                                pw.println(prefix + "No configured app linkages.");
20680                                pw.println();
20681                            }
20682                        }
20683                    }
20684                }
20685            }
20686
20687            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20688                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20689                if (packageName == null && permissionNames == null) {
20690                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20691                        if (iperm == 0) {
20692                            if (dumpState.onTitlePrinted())
20693                                pw.println();
20694                            pw.println("AppOp Permissions:");
20695                        }
20696                        pw.print("  AppOp Permission ");
20697                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20698                        pw.println(":");
20699                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20700                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20701                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20702                        }
20703                    }
20704                }
20705            }
20706
20707            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20708                boolean printedSomething = false;
20709                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20710                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20711                        continue;
20712                    }
20713                    if (!printedSomething) {
20714                        if (dumpState.onTitlePrinted())
20715                            pw.println();
20716                        pw.println("Registered ContentProviders:");
20717                        printedSomething = true;
20718                    }
20719                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20720                    pw.print("    "); pw.println(p.toString());
20721                }
20722                printedSomething = false;
20723                for (Map.Entry<String, PackageParser.Provider> entry :
20724                        mProvidersByAuthority.entrySet()) {
20725                    PackageParser.Provider p = entry.getValue();
20726                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20727                        continue;
20728                    }
20729                    if (!printedSomething) {
20730                        if (dumpState.onTitlePrinted())
20731                            pw.println();
20732                        pw.println("ContentProvider Authorities:");
20733                        printedSomething = true;
20734                    }
20735                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20736                    pw.print("    "); pw.println(p.toString());
20737                    if (p.info != null && p.info.applicationInfo != null) {
20738                        final String appInfo = p.info.applicationInfo.toString();
20739                        pw.print("      applicationInfo="); pw.println(appInfo);
20740                    }
20741                }
20742            }
20743
20744            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20745                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20746            }
20747
20748            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20749                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20750            }
20751
20752            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20753                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20754            }
20755
20756            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20757                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20758            }
20759
20760            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20761                // XXX should handle packageName != null by dumping only install data that
20762                // the given package is involved with.
20763                if (dumpState.onTitlePrinted()) pw.println();
20764                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20765            }
20766
20767            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20768                // XXX should handle packageName != null by dumping only install data that
20769                // the given package is involved with.
20770                if (dumpState.onTitlePrinted()) pw.println();
20771
20772                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20773                ipw.println();
20774                ipw.println("Frozen packages:");
20775                ipw.increaseIndent();
20776                if (mFrozenPackages.size() == 0) {
20777                    ipw.println("(none)");
20778                } else {
20779                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20780                        ipw.println(mFrozenPackages.valueAt(i));
20781                    }
20782                }
20783                ipw.decreaseIndent();
20784            }
20785
20786            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20787                if (dumpState.onTitlePrinted()) pw.println();
20788                dumpDexoptStateLPr(pw, packageName);
20789            }
20790
20791            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20792                if (dumpState.onTitlePrinted()) pw.println();
20793                dumpCompilerStatsLPr(pw, packageName);
20794            }
20795
20796            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20797                if (dumpState.onTitlePrinted()) pw.println();
20798                dumpEnabledOverlaysLPr(pw);
20799            }
20800
20801            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20802                if (dumpState.onTitlePrinted()) pw.println();
20803                mSettings.dumpReadMessagesLPr(pw, dumpState);
20804
20805                pw.println();
20806                pw.println("Package warning messages:");
20807                BufferedReader in = null;
20808                String line = null;
20809                try {
20810                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20811                    while ((line = in.readLine()) != null) {
20812                        if (line.contains("ignored: updated version")) continue;
20813                        pw.println(line);
20814                    }
20815                } catch (IOException ignored) {
20816                } finally {
20817                    IoUtils.closeQuietly(in);
20818                }
20819            }
20820
20821            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20822                BufferedReader in = null;
20823                String line = null;
20824                try {
20825                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20826                    while ((line = in.readLine()) != null) {
20827                        if (line.contains("ignored: updated version")) continue;
20828                        pw.print("msg,");
20829                        pw.println(line);
20830                    }
20831                } catch (IOException ignored) {
20832                } finally {
20833                    IoUtils.closeQuietly(in);
20834                }
20835            }
20836        }
20837    }
20838
20839    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20840        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20841        ipw.println();
20842        ipw.println("Dexopt state:");
20843        ipw.increaseIndent();
20844        Collection<PackageParser.Package> packages = null;
20845        if (packageName != null) {
20846            PackageParser.Package targetPackage = mPackages.get(packageName);
20847            if (targetPackage != null) {
20848                packages = Collections.singletonList(targetPackage);
20849            } else {
20850                ipw.println("Unable to find package: " + packageName);
20851                return;
20852            }
20853        } else {
20854            packages = mPackages.values();
20855        }
20856
20857        for (PackageParser.Package pkg : packages) {
20858            ipw.println("[" + pkg.packageName + "]");
20859            ipw.increaseIndent();
20860            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20861            ipw.decreaseIndent();
20862        }
20863    }
20864
20865    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20866        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20867        ipw.println();
20868        ipw.println("Compiler stats:");
20869        ipw.increaseIndent();
20870        Collection<PackageParser.Package> packages = null;
20871        if (packageName != null) {
20872            PackageParser.Package targetPackage = mPackages.get(packageName);
20873            if (targetPackage != null) {
20874                packages = Collections.singletonList(targetPackage);
20875            } else {
20876                ipw.println("Unable to find package: " + packageName);
20877                return;
20878            }
20879        } else {
20880            packages = mPackages.values();
20881        }
20882
20883        for (PackageParser.Package pkg : packages) {
20884            ipw.println("[" + pkg.packageName + "]");
20885            ipw.increaseIndent();
20886
20887            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20888            if (stats == null) {
20889                ipw.println("(No recorded stats)");
20890            } else {
20891                stats.dump(ipw);
20892            }
20893            ipw.decreaseIndent();
20894        }
20895    }
20896
20897    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20898        pw.println("Enabled overlay paths:");
20899        final int N = mEnabledOverlayPaths.size();
20900        for (int i = 0; i < N; i++) {
20901            final int userId = mEnabledOverlayPaths.keyAt(i);
20902            pw.println(String.format("    User %d:", userId));
20903            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20904                mEnabledOverlayPaths.valueAt(i);
20905            final int M = userSpecificOverlays.size();
20906            for (int j = 0; j < M; j++) {
20907                final String targetPackageName = userSpecificOverlays.keyAt(j);
20908                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20909                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20910            }
20911        }
20912    }
20913
20914    private String dumpDomainString(String packageName) {
20915        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20916                .getList();
20917        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20918
20919        ArraySet<String> result = new ArraySet<>();
20920        if (iviList.size() > 0) {
20921            for (IntentFilterVerificationInfo ivi : iviList) {
20922                for (String host : ivi.getDomains()) {
20923                    result.add(host);
20924                }
20925            }
20926        }
20927        if (filters != null && filters.size() > 0) {
20928            for (IntentFilter filter : filters) {
20929                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20930                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20931                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20932                    result.addAll(filter.getHostsList());
20933                }
20934            }
20935        }
20936
20937        StringBuilder sb = new StringBuilder(result.size() * 16);
20938        for (String domain : result) {
20939            if (sb.length() > 0) sb.append(" ");
20940            sb.append(domain);
20941        }
20942        return sb.toString();
20943    }
20944
20945    // ------- apps on sdcard specific code -------
20946    static final boolean DEBUG_SD_INSTALL = false;
20947
20948    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20949
20950    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20951
20952    private boolean mMediaMounted = false;
20953
20954    static String getEncryptKey() {
20955        try {
20956            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20957                    SD_ENCRYPTION_KEYSTORE_NAME);
20958            if (sdEncKey == null) {
20959                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20960                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20961                if (sdEncKey == null) {
20962                    Slog.e(TAG, "Failed to create encryption keys");
20963                    return null;
20964                }
20965            }
20966            return sdEncKey;
20967        } catch (NoSuchAlgorithmException nsae) {
20968            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20969            return null;
20970        } catch (IOException ioe) {
20971            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20972            return null;
20973        }
20974    }
20975
20976    /*
20977     * Update media status on PackageManager.
20978     */
20979    @Override
20980    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20981        int callingUid = Binder.getCallingUid();
20982        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20983            throw new SecurityException("Media status can only be updated by the system");
20984        }
20985        // reader; this apparently protects mMediaMounted, but should probably
20986        // be a different lock in that case.
20987        synchronized (mPackages) {
20988            Log.i(TAG, "Updating external media status from "
20989                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20990                    + (mediaStatus ? "mounted" : "unmounted"));
20991            if (DEBUG_SD_INSTALL)
20992                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20993                        + ", mMediaMounted=" + mMediaMounted);
20994            if (mediaStatus == mMediaMounted) {
20995                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20996                        : 0, -1);
20997                mHandler.sendMessage(msg);
20998                return;
20999            }
21000            mMediaMounted = mediaStatus;
21001        }
21002        // Queue up an async operation since the package installation may take a
21003        // little while.
21004        mHandler.post(new Runnable() {
21005            public void run() {
21006                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21007            }
21008        });
21009    }
21010
21011    /**
21012     * Called by StorageManagerService when the initial ASECs to scan are available.
21013     * Should block until all the ASEC containers are finished being scanned.
21014     */
21015    public void scanAvailableAsecs() {
21016        updateExternalMediaStatusInner(true, false, false);
21017    }
21018
21019    /*
21020     * Collect information of applications on external media, map them against
21021     * existing containers and update information based on current mount status.
21022     * Please note that we always have to report status if reportStatus has been
21023     * set to true especially when unloading packages.
21024     */
21025    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21026            boolean externalStorage) {
21027        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21028        int[] uidArr = EmptyArray.INT;
21029
21030        final String[] list = PackageHelper.getSecureContainerList();
21031        if (ArrayUtils.isEmpty(list)) {
21032            Log.i(TAG, "No secure containers found");
21033        } else {
21034            // Process list of secure containers and categorize them
21035            // as active or stale based on their package internal state.
21036
21037            // reader
21038            synchronized (mPackages) {
21039                for (String cid : list) {
21040                    // Leave stages untouched for now; installer service owns them
21041                    if (PackageInstallerService.isStageName(cid)) continue;
21042
21043                    if (DEBUG_SD_INSTALL)
21044                        Log.i(TAG, "Processing container " + cid);
21045                    String pkgName = getAsecPackageName(cid);
21046                    if (pkgName == null) {
21047                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21048                        continue;
21049                    }
21050                    if (DEBUG_SD_INSTALL)
21051                        Log.i(TAG, "Looking for pkg : " + pkgName);
21052
21053                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21054                    if (ps == null) {
21055                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21056                        continue;
21057                    }
21058
21059                    /*
21060                     * Skip packages that are not external if we're unmounting
21061                     * external storage.
21062                     */
21063                    if (externalStorage && !isMounted && !isExternal(ps)) {
21064                        continue;
21065                    }
21066
21067                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21068                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21069                    // The package status is changed only if the code path
21070                    // matches between settings and the container id.
21071                    if (ps.codePathString != null
21072                            && ps.codePathString.startsWith(args.getCodePath())) {
21073                        if (DEBUG_SD_INSTALL) {
21074                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21075                                    + " at code path: " + ps.codePathString);
21076                        }
21077
21078                        // We do have a valid package installed on sdcard
21079                        processCids.put(args, ps.codePathString);
21080                        final int uid = ps.appId;
21081                        if (uid != -1) {
21082                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21083                        }
21084                    } else {
21085                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21086                                + ps.codePathString);
21087                    }
21088                }
21089            }
21090
21091            Arrays.sort(uidArr);
21092        }
21093
21094        // Process packages with valid entries.
21095        if (isMounted) {
21096            if (DEBUG_SD_INSTALL)
21097                Log.i(TAG, "Loading packages");
21098            loadMediaPackages(processCids, uidArr, externalStorage);
21099            startCleaningPackages();
21100            mInstallerService.onSecureContainersAvailable();
21101        } else {
21102            if (DEBUG_SD_INSTALL)
21103                Log.i(TAG, "Unloading packages");
21104            unloadMediaPackages(processCids, uidArr, reportStatus);
21105        }
21106    }
21107
21108    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21109            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21110        final int size = infos.size();
21111        final String[] packageNames = new String[size];
21112        final int[] packageUids = new int[size];
21113        for (int i = 0; i < size; i++) {
21114            final ApplicationInfo info = infos.get(i);
21115            packageNames[i] = info.packageName;
21116            packageUids[i] = info.uid;
21117        }
21118        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21119                finishedReceiver);
21120    }
21121
21122    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21123            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21124        sendResourcesChangedBroadcast(mediaStatus, replacing,
21125                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21126    }
21127
21128    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21129            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21130        int size = pkgList.length;
21131        if (size > 0) {
21132            // Send broadcasts here
21133            Bundle extras = new Bundle();
21134            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21135            if (uidArr != null) {
21136                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21137            }
21138            if (replacing) {
21139                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21140            }
21141            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21142                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21143            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21144        }
21145    }
21146
21147   /*
21148     * Look at potentially valid container ids from processCids If package
21149     * information doesn't match the one on record or package scanning fails,
21150     * the cid is added to list of removeCids. We currently don't delete stale
21151     * containers.
21152     */
21153    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21154            boolean externalStorage) {
21155        ArrayList<String> pkgList = new ArrayList<String>();
21156        Set<AsecInstallArgs> keys = processCids.keySet();
21157
21158        for (AsecInstallArgs args : keys) {
21159            String codePath = processCids.get(args);
21160            if (DEBUG_SD_INSTALL)
21161                Log.i(TAG, "Loading container : " + args.cid);
21162            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21163            try {
21164                // Make sure there are no container errors first.
21165                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21166                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21167                            + " when installing from sdcard");
21168                    continue;
21169                }
21170                // Check code path here.
21171                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21172                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21173                            + " does not match one in settings " + codePath);
21174                    continue;
21175                }
21176                // Parse package
21177                int parseFlags = mDefParseFlags;
21178                if (args.isExternalAsec()) {
21179                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21180                }
21181                if (args.isFwdLocked()) {
21182                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21183                }
21184
21185                synchronized (mInstallLock) {
21186                    PackageParser.Package pkg = null;
21187                    try {
21188                        // Sadly we don't know the package name yet to freeze it
21189                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21190                                SCAN_IGNORE_FROZEN, 0, null);
21191                    } catch (PackageManagerException e) {
21192                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21193                    }
21194                    // Scan the package
21195                    if (pkg != null) {
21196                        /*
21197                         * TODO why is the lock being held? doPostInstall is
21198                         * called in other places without the lock. This needs
21199                         * to be straightened out.
21200                         */
21201                        // writer
21202                        synchronized (mPackages) {
21203                            retCode = PackageManager.INSTALL_SUCCEEDED;
21204                            pkgList.add(pkg.packageName);
21205                            // Post process args
21206                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21207                                    pkg.applicationInfo.uid);
21208                        }
21209                    } else {
21210                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21211                    }
21212                }
21213
21214            } finally {
21215                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21216                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21217                }
21218            }
21219        }
21220        // writer
21221        synchronized (mPackages) {
21222            // If the platform SDK has changed since the last time we booted,
21223            // we need to re-grant app permission to catch any new ones that
21224            // appear. This is really a hack, and means that apps can in some
21225            // cases get permissions that the user didn't initially explicitly
21226            // allow... it would be nice to have some better way to handle
21227            // this situation.
21228            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21229                    : mSettings.getInternalVersion();
21230            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21231                    : StorageManager.UUID_PRIVATE_INTERNAL;
21232
21233            int updateFlags = UPDATE_PERMISSIONS_ALL;
21234            if (ver.sdkVersion != mSdkVersion) {
21235                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21236                        + mSdkVersion + "; regranting permissions for external");
21237                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21238            }
21239            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21240
21241            // Yay, everything is now upgraded
21242            ver.forceCurrent();
21243
21244            // can downgrade to reader
21245            // Persist settings
21246            mSettings.writeLPr();
21247        }
21248        // Send a broadcast to let everyone know we are done processing
21249        if (pkgList.size() > 0) {
21250            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21251        }
21252    }
21253
21254   /*
21255     * Utility method to unload a list of specified containers
21256     */
21257    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21258        // Just unmount all valid containers.
21259        for (AsecInstallArgs arg : cidArgs) {
21260            synchronized (mInstallLock) {
21261                arg.doPostDeleteLI(false);
21262           }
21263       }
21264   }
21265
21266    /*
21267     * Unload packages mounted on external media. This involves deleting package
21268     * data from internal structures, sending broadcasts about disabled packages,
21269     * gc'ing to free up references, unmounting all secure containers
21270     * corresponding to packages on external media, and posting a
21271     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21272     * that we always have to post this message if status has been requested no
21273     * matter what.
21274     */
21275    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21276            final boolean reportStatus) {
21277        if (DEBUG_SD_INSTALL)
21278            Log.i(TAG, "unloading media packages");
21279        ArrayList<String> pkgList = new ArrayList<String>();
21280        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21281        final Set<AsecInstallArgs> keys = processCids.keySet();
21282        for (AsecInstallArgs args : keys) {
21283            String pkgName = args.getPackageName();
21284            if (DEBUG_SD_INSTALL)
21285                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21286            // Delete package internally
21287            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21288            synchronized (mInstallLock) {
21289                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21290                final boolean res;
21291                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21292                        "unloadMediaPackages")) {
21293                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21294                            null);
21295                }
21296                if (res) {
21297                    pkgList.add(pkgName);
21298                } else {
21299                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21300                    failedList.add(args);
21301                }
21302            }
21303        }
21304
21305        // reader
21306        synchronized (mPackages) {
21307            // We didn't update the settings after removing each package;
21308            // write them now for all packages.
21309            mSettings.writeLPr();
21310        }
21311
21312        // We have to absolutely send UPDATED_MEDIA_STATUS only
21313        // after confirming that all the receivers processed the ordered
21314        // broadcast when packages get disabled, force a gc to clean things up.
21315        // and unload all the containers.
21316        if (pkgList.size() > 0) {
21317            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21318                    new IIntentReceiver.Stub() {
21319                public void performReceive(Intent intent, int resultCode, String data,
21320                        Bundle extras, boolean ordered, boolean sticky,
21321                        int sendingUser) throws RemoteException {
21322                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21323                            reportStatus ? 1 : 0, 1, keys);
21324                    mHandler.sendMessage(msg);
21325                }
21326            });
21327        } else {
21328            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21329                    keys);
21330            mHandler.sendMessage(msg);
21331        }
21332    }
21333
21334    private void loadPrivatePackages(final VolumeInfo vol) {
21335        mHandler.post(new Runnable() {
21336            @Override
21337            public void run() {
21338                loadPrivatePackagesInner(vol);
21339            }
21340        });
21341    }
21342
21343    private void loadPrivatePackagesInner(VolumeInfo vol) {
21344        final String volumeUuid = vol.fsUuid;
21345        if (TextUtils.isEmpty(volumeUuid)) {
21346            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21347            return;
21348        }
21349
21350        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21351        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21352        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21353
21354        final VersionInfo ver;
21355        final List<PackageSetting> packages;
21356        synchronized (mPackages) {
21357            ver = mSettings.findOrCreateVersion(volumeUuid);
21358            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21359        }
21360
21361        for (PackageSetting ps : packages) {
21362            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21363            synchronized (mInstallLock) {
21364                final PackageParser.Package pkg;
21365                try {
21366                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21367                    loaded.add(pkg.applicationInfo);
21368
21369                } catch (PackageManagerException e) {
21370                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21371                }
21372
21373                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21374                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21375                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21376                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21377                }
21378            }
21379        }
21380
21381        // Reconcile app data for all started/unlocked users
21382        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21383        final UserManager um = mContext.getSystemService(UserManager.class);
21384        UserManagerInternal umInternal = getUserManagerInternal();
21385        for (UserInfo user : um.getUsers()) {
21386            final int flags;
21387            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21388                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21389            } else if (umInternal.isUserRunning(user.id)) {
21390                flags = StorageManager.FLAG_STORAGE_DE;
21391            } else {
21392                continue;
21393            }
21394
21395            try {
21396                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21397                synchronized (mInstallLock) {
21398                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21399                }
21400            } catch (IllegalStateException e) {
21401                // Device was probably ejected, and we'll process that event momentarily
21402                Slog.w(TAG, "Failed to prepare storage: " + e);
21403            }
21404        }
21405
21406        synchronized (mPackages) {
21407            int updateFlags = UPDATE_PERMISSIONS_ALL;
21408            if (ver.sdkVersion != mSdkVersion) {
21409                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21410                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21411                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21412            }
21413            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21414
21415            // Yay, everything is now upgraded
21416            ver.forceCurrent();
21417
21418            mSettings.writeLPr();
21419        }
21420
21421        for (PackageFreezer freezer : freezers) {
21422            freezer.close();
21423        }
21424
21425        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21426        sendResourcesChangedBroadcast(true, false, loaded, null);
21427    }
21428
21429    private void unloadPrivatePackages(final VolumeInfo vol) {
21430        mHandler.post(new Runnable() {
21431            @Override
21432            public void run() {
21433                unloadPrivatePackagesInner(vol);
21434            }
21435        });
21436    }
21437
21438    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21439        final String volumeUuid = vol.fsUuid;
21440        if (TextUtils.isEmpty(volumeUuid)) {
21441            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21442            return;
21443        }
21444
21445        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21446        synchronized (mInstallLock) {
21447        synchronized (mPackages) {
21448            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21449            for (PackageSetting ps : packages) {
21450                if (ps.pkg == null) continue;
21451
21452                final ApplicationInfo info = ps.pkg.applicationInfo;
21453                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21454                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21455
21456                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21457                        "unloadPrivatePackagesInner")) {
21458                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21459                            false, null)) {
21460                        unloaded.add(info);
21461                    } else {
21462                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21463                    }
21464                }
21465
21466                // Try very hard to release any references to this package
21467                // so we don't risk the system server being killed due to
21468                // open FDs
21469                AttributeCache.instance().removePackage(ps.name);
21470            }
21471
21472            mSettings.writeLPr();
21473        }
21474        }
21475
21476        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21477        sendResourcesChangedBroadcast(false, false, unloaded, null);
21478
21479        // Try very hard to release any references to this path so we don't risk
21480        // the system server being killed due to open FDs
21481        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21482
21483        for (int i = 0; i < 3; i++) {
21484            System.gc();
21485            System.runFinalization();
21486        }
21487    }
21488
21489    private void assertPackageKnown(String volumeUuid, String packageName)
21490            throws PackageManagerException {
21491        synchronized (mPackages) {
21492            // Normalize package name to handle renamed packages
21493            packageName = normalizePackageNameLPr(packageName);
21494
21495            final PackageSetting ps = mSettings.mPackages.get(packageName);
21496            if (ps == null) {
21497                throw new PackageManagerException("Package " + packageName + " is unknown");
21498            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21499                throw new PackageManagerException(
21500                        "Package " + packageName + " found on unknown volume " + volumeUuid
21501                                + "; expected volume " + ps.volumeUuid);
21502            }
21503        }
21504    }
21505
21506    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21507            throws PackageManagerException {
21508        synchronized (mPackages) {
21509            // Normalize package name to handle renamed packages
21510            packageName = normalizePackageNameLPr(packageName);
21511
21512            final PackageSetting ps = mSettings.mPackages.get(packageName);
21513            if (ps == null) {
21514                throw new PackageManagerException("Package " + packageName + " is unknown");
21515            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21516                throw new PackageManagerException(
21517                        "Package " + packageName + " found on unknown volume " + volumeUuid
21518                                + "; expected volume " + ps.volumeUuid);
21519            } else if (!ps.getInstalled(userId)) {
21520                throw new PackageManagerException(
21521                        "Package " + packageName + " not installed for user " + userId);
21522            }
21523        }
21524    }
21525
21526    private List<String> collectAbsoluteCodePaths() {
21527        synchronized (mPackages) {
21528            List<String> codePaths = new ArrayList<>();
21529            final int packageCount = mSettings.mPackages.size();
21530            for (int i = 0; i < packageCount; i++) {
21531                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21532                codePaths.add(ps.codePath.getAbsolutePath());
21533            }
21534            return codePaths;
21535        }
21536    }
21537
21538    /**
21539     * Examine all apps present on given mounted volume, and destroy apps that
21540     * aren't expected, either due to uninstallation or reinstallation on
21541     * another volume.
21542     */
21543    private void reconcileApps(String volumeUuid) {
21544        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21545        List<File> filesToDelete = null;
21546
21547        final File[] files = FileUtils.listFilesOrEmpty(
21548                Environment.getDataAppDirectory(volumeUuid));
21549        for (File file : files) {
21550            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21551                    && !PackageInstallerService.isStageName(file.getName());
21552            if (!isPackage) {
21553                // Ignore entries which are not packages
21554                continue;
21555            }
21556
21557            String absolutePath = file.getAbsolutePath();
21558
21559            boolean pathValid = false;
21560            final int absoluteCodePathCount = absoluteCodePaths.size();
21561            for (int i = 0; i < absoluteCodePathCount; i++) {
21562                String absoluteCodePath = absoluteCodePaths.get(i);
21563                if (absolutePath.startsWith(absoluteCodePath)) {
21564                    pathValid = true;
21565                    break;
21566                }
21567            }
21568
21569            if (!pathValid) {
21570                if (filesToDelete == null) {
21571                    filesToDelete = new ArrayList<>();
21572                }
21573                filesToDelete.add(file);
21574            }
21575        }
21576
21577        if (filesToDelete != null) {
21578            final int fileToDeleteCount = filesToDelete.size();
21579            for (int i = 0; i < fileToDeleteCount; i++) {
21580                File fileToDelete = filesToDelete.get(i);
21581                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21582                synchronized (mInstallLock) {
21583                    removeCodePathLI(fileToDelete);
21584                }
21585            }
21586        }
21587    }
21588
21589    /**
21590     * Reconcile all app data for the given user.
21591     * <p>
21592     * Verifies that directories exist and that ownership and labeling is
21593     * correct for all installed apps on all mounted volumes.
21594     */
21595    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21596        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21597        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21598            final String volumeUuid = vol.getFsUuid();
21599            synchronized (mInstallLock) {
21600                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21601            }
21602        }
21603    }
21604
21605    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21606            boolean migrateAppData) {
21607        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21608    }
21609
21610    /**
21611     * Reconcile all app data on given mounted volume.
21612     * <p>
21613     * Destroys app data that isn't expected, either due to uninstallation or
21614     * reinstallation on another volume.
21615     * <p>
21616     * Verifies that directories exist and that ownership and labeling is
21617     * correct for all installed apps.
21618     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21619     */
21620    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21621            boolean migrateAppData, boolean onlyCoreApps) {
21622        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21623                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21624        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21625
21626        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21627        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21628
21629        // First look for stale data that doesn't belong, and check if things
21630        // have changed since we did our last restorecon
21631        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21632            if (StorageManager.isFileEncryptedNativeOrEmulated()
21633                    && !StorageManager.isUserKeyUnlocked(userId)) {
21634                throw new RuntimeException(
21635                        "Yikes, someone asked us to reconcile CE storage while " + userId
21636                                + " was still locked; this would have caused massive data loss!");
21637            }
21638
21639            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21640            for (File file : files) {
21641                final String packageName = file.getName();
21642                try {
21643                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21644                } catch (PackageManagerException e) {
21645                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21646                    try {
21647                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21648                                StorageManager.FLAG_STORAGE_CE, 0);
21649                    } catch (InstallerException e2) {
21650                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21651                    }
21652                }
21653            }
21654        }
21655        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21656            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21657            for (File file : files) {
21658                final String packageName = file.getName();
21659                try {
21660                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21661                } catch (PackageManagerException e) {
21662                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21663                    try {
21664                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21665                                StorageManager.FLAG_STORAGE_DE, 0);
21666                    } catch (InstallerException e2) {
21667                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21668                    }
21669                }
21670            }
21671        }
21672
21673        // Ensure that data directories are ready to roll for all packages
21674        // installed for this volume and user
21675        final List<PackageSetting> packages;
21676        synchronized (mPackages) {
21677            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21678        }
21679        int preparedCount = 0;
21680        for (PackageSetting ps : packages) {
21681            final String packageName = ps.name;
21682            if (ps.pkg == null) {
21683                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21684                // TODO: might be due to legacy ASEC apps; we should circle back
21685                // and reconcile again once they're scanned
21686                continue;
21687            }
21688            // Skip non-core apps if requested
21689            if (onlyCoreApps && !ps.pkg.coreApp) {
21690                result.add(packageName);
21691                continue;
21692            }
21693
21694            if (ps.getInstalled(userId)) {
21695                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21696                preparedCount++;
21697            }
21698        }
21699
21700        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21701        return result;
21702    }
21703
21704    /**
21705     * Prepare app data for the given app just after it was installed or
21706     * upgraded. This method carefully only touches users that it's installed
21707     * for, and it forces a restorecon to handle any seinfo changes.
21708     * <p>
21709     * Verifies that directories exist and that ownership and labeling is
21710     * correct for all installed apps. If there is an ownership mismatch, it
21711     * will try recovering system apps by wiping data; third-party app data is
21712     * left intact.
21713     * <p>
21714     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21715     */
21716    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21717        final PackageSetting ps;
21718        synchronized (mPackages) {
21719            ps = mSettings.mPackages.get(pkg.packageName);
21720            mSettings.writeKernelMappingLPr(ps);
21721        }
21722
21723        final UserManager um = mContext.getSystemService(UserManager.class);
21724        UserManagerInternal umInternal = getUserManagerInternal();
21725        for (UserInfo user : um.getUsers()) {
21726            final int flags;
21727            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21728                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21729            } else if (umInternal.isUserRunning(user.id)) {
21730                flags = StorageManager.FLAG_STORAGE_DE;
21731            } else {
21732                continue;
21733            }
21734
21735            if (ps.getInstalled(user.id)) {
21736                // TODO: when user data is locked, mark that we're still dirty
21737                prepareAppDataLIF(pkg, user.id, flags);
21738            }
21739        }
21740    }
21741
21742    /**
21743     * Prepare app data for the given app.
21744     * <p>
21745     * Verifies that directories exist and that ownership and labeling is
21746     * correct for all installed apps. If there is an ownership mismatch, this
21747     * will try recovering system apps by wiping data; third-party app data is
21748     * left intact.
21749     */
21750    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21751        if (pkg == null) {
21752            Slog.wtf(TAG, "Package was null!", new Throwable());
21753            return;
21754        }
21755        prepareAppDataLeafLIF(pkg, userId, flags);
21756        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21757        for (int i = 0; i < childCount; i++) {
21758            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21759        }
21760    }
21761
21762    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21763            boolean maybeMigrateAppData) {
21764        prepareAppDataLIF(pkg, userId, flags);
21765
21766        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21767            // We may have just shuffled around app data directories, so
21768            // prepare them one more time
21769            prepareAppDataLIF(pkg, userId, flags);
21770        }
21771    }
21772
21773    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21774        if (DEBUG_APP_DATA) {
21775            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21776                    + Integer.toHexString(flags));
21777        }
21778
21779        final String volumeUuid = pkg.volumeUuid;
21780        final String packageName = pkg.packageName;
21781        final ApplicationInfo app = pkg.applicationInfo;
21782        final int appId = UserHandle.getAppId(app.uid);
21783
21784        Preconditions.checkNotNull(app.seInfo);
21785
21786        long ceDataInode = -1;
21787        try {
21788            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21789                    appId, app.seInfo, app.targetSdkVersion);
21790        } catch (InstallerException e) {
21791            if (app.isSystemApp()) {
21792                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21793                        + ", but trying to recover: " + e);
21794                destroyAppDataLeafLIF(pkg, userId, flags);
21795                try {
21796                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21797                            appId, app.seInfo, app.targetSdkVersion);
21798                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21799                } catch (InstallerException e2) {
21800                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21801                }
21802            } else {
21803                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21804            }
21805        }
21806
21807        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21808            // TODO: mark this structure as dirty so we persist it!
21809            synchronized (mPackages) {
21810                final PackageSetting ps = mSettings.mPackages.get(packageName);
21811                if (ps != null) {
21812                    ps.setCeDataInode(ceDataInode, userId);
21813                }
21814            }
21815        }
21816
21817        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21818    }
21819
21820    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21821        if (pkg == null) {
21822            Slog.wtf(TAG, "Package was null!", new Throwable());
21823            return;
21824        }
21825        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21826        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21827        for (int i = 0; i < childCount; i++) {
21828            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21829        }
21830    }
21831
21832    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21833        final String volumeUuid = pkg.volumeUuid;
21834        final String packageName = pkg.packageName;
21835        final ApplicationInfo app = pkg.applicationInfo;
21836
21837        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21838            // Create a native library symlink only if we have native libraries
21839            // and if the native libraries are 32 bit libraries. We do not provide
21840            // this symlink for 64 bit libraries.
21841            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21842                final String nativeLibPath = app.nativeLibraryDir;
21843                try {
21844                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21845                            nativeLibPath, userId);
21846                } catch (InstallerException e) {
21847                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21848                }
21849            }
21850        }
21851    }
21852
21853    /**
21854     * For system apps on non-FBE devices, this method migrates any existing
21855     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21856     * requested by the app.
21857     */
21858    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21859        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21860                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21861            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21862                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21863            try {
21864                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21865                        storageTarget);
21866            } catch (InstallerException e) {
21867                logCriticalInfo(Log.WARN,
21868                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21869            }
21870            return true;
21871        } else {
21872            return false;
21873        }
21874    }
21875
21876    public PackageFreezer freezePackage(String packageName, String killReason) {
21877        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21878    }
21879
21880    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21881        return new PackageFreezer(packageName, userId, killReason);
21882    }
21883
21884    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21885            String killReason) {
21886        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21887    }
21888
21889    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21890            String killReason) {
21891        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21892            return new PackageFreezer();
21893        } else {
21894            return freezePackage(packageName, userId, killReason);
21895        }
21896    }
21897
21898    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21899            String killReason) {
21900        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21901    }
21902
21903    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21904            String killReason) {
21905        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21906            return new PackageFreezer();
21907        } else {
21908            return freezePackage(packageName, userId, killReason);
21909        }
21910    }
21911
21912    /**
21913     * Class that freezes and kills the given package upon creation, and
21914     * unfreezes it upon closing. This is typically used when doing surgery on
21915     * app code/data to prevent the app from running while you're working.
21916     */
21917    private class PackageFreezer implements AutoCloseable {
21918        private final String mPackageName;
21919        private final PackageFreezer[] mChildren;
21920
21921        private final boolean mWeFroze;
21922
21923        private final AtomicBoolean mClosed = new AtomicBoolean();
21924        private final CloseGuard mCloseGuard = CloseGuard.get();
21925
21926        /**
21927         * Create and return a stub freezer that doesn't actually do anything,
21928         * typically used when someone requested
21929         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21930         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21931         */
21932        public PackageFreezer() {
21933            mPackageName = null;
21934            mChildren = null;
21935            mWeFroze = false;
21936            mCloseGuard.open("close");
21937        }
21938
21939        public PackageFreezer(String packageName, int userId, String killReason) {
21940            synchronized (mPackages) {
21941                mPackageName = packageName;
21942                mWeFroze = mFrozenPackages.add(mPackageName);
21943
21944                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21945                if (ps != null) {
21946                    killApplication(ps.name, ps.appId, userId, killReason);
21947                }
21948
21949                final PackageParser.Package p = mPackages.get(packageName);
21950                if (p != null && p.childPackages != null) {
21951                    final int N = p.childPackages.size();
21952                    mChildren = new PackageFreezer[N];
21953                    for (int i = 0; i < N; i++) {
21954                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21955                                userId, killReason);
21956                    }
21957                } else {
21958                    mChildren = null;
21959                }
21960            }
21961            mCloseGuard.open("close");
21962        }
21963
21964        @Override
21965        protected void finalize() throws Throwable {
21966            try {
21967                mCloseGuard.warnIfOpen();
21968                close();
21969            } finally {
21970                super.finalize();
21971            }
21972        }
21973
21974        @Override
21975        public void close() {
21976            mCloseGuard.close();
21977            if (mClosed.compareAndSet(false, true)) {
21978                synchronized (mPackages) {
21979                    if (mWeFroze) {
21980                        mFrozenPackages.remove(mPackageName);
21981                    }
21982
21983                    if (mChildren != null) {
21984                        for (PackageFreezer freezer : mChildren) {
21985                            freezer.close();
21986                        }
21987                    }
21988                }
21989            }
21990        }
21991    }
21992
21993    /**
21994     * Verify that given package is currently frozen.
21995     */
21996    private void checkPackageFrozen(String packageName) {
21997        synchronized (mPackages) {
21998            if (!mFrozenPackages.contains(packageName)) {
21999                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22000            }
22001        }
22002    }
22003
22004    @Override
22005    public int movePackage(final String packageName, final String volumeUuid) {
22006        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22007
22008        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22009        final int moveId = mNextMoveId.getAndIncrement();
22010        mHandler.post(new Runnable() {
22011            @Override
22012            public void run() {
22013                try {
22014                    movePackageInternal(packageName, volumeUuid, moveId, user);
22015                } catch (PackageManagerException e) {
22016                    Slog.w(TAG, "Failed to move " + packageName, e);
22017                    mMoveCallbacks.notifyStatusChanged(moveId,
22018                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22019                }
22020            }
22021        });
22022        return moveId;
22023    }
22024
22025    private void movePackageInternal(final String packageName, final String volumeUuid,
22026            final int moveId, UserHandle user) throws PackageManagerException {
22027        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22028        final PackageManager pm = mContext.getPackageManager();
22029
22030        final boolean currentAsec;
22031        final String currentVolumeUuid;
22032        final File codeFile;
22033        final String installerPackageName;
22034        final String packageAbiOverride;
22035        final int appId;
22036        final String seinfo;
22037        final String label;
22038        final int targetSdkVersion;
22039        final PackageFreezer freezer;
22040        final int[] installedUserIds;
22041
22042        // reader
22043        synchronized (mPackages) {
22044            final PackageParser.Package pkg = mPackages.get(packageName);
22045            final PackageSetting ps = mSettings.mPackages.get(packageName);
22046            if (pkg == null || ps == null) {
22047                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22048            }
22049
22050            if (pkg.applicationInfo.isSystemApp()) {
22051                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22052                        "Cannot move system application");
22053            }
22054
22055            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22056            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22057                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22058            if (isInternalStorage && !allow3rdPartyOnInternal) {
22059                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22060                        "3rd party apps are not allowed on internal storage");
22061            }
22062
22063            if (pkg.applicationInfo.isExternalAsec()) {
22064                currentAsec = true;
22065                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22066            } else if (pkg.applicationInfo.isForwardLocked()) {
22067                currentAsec = true;
22068                currentVolumeUuid = "forward_locked";
22069            } else {
22070                currentAsec = false;
22071                currentVolumeUuid = ps.volumeUuid;
22072
22073                final File probe = new File(pkg.codePath);
22074                final File probeOat = new File(probe, "oat");
22075                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22076                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22077                            "Move only supported for modern cluster style installs");
22078                }
22079            }
22080
22081            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22082                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22083                        "Package already moved to " + volumeUuid);
22084            }
22085            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22086                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22087                        "Device admin cannot be moved");
22088            }
22089
22090            if (mFrozenPackages.contains(packageName)) {
22091                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22092                        "Failed to move already frozen package");
22093            }
22094
22095            codeFile = new File(pkg.codePath);
22096            installerPackageName = ps.installerPackageName;
22097            packageAbiOverride = ps.cpuAbiOverrideString;
22098            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22099            seinfo = pkg.applicationInfo.seInfo;
22100            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22101            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22102            freezer = freezePackage(packageName, "movePackageInternal");
22103            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22104        }
22105
22106        final Bundle extras = new Bundle();
22107        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22108        extras.putString(Intent.EXTRA_TITLE, label);
22109        mMoveCallbacks.notifyCreated(moveId, extras);
22110
22111        int installFlags;
22112        final boolean moveCompleteApp;
22113        final File measurePath;
22114
22115        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22116            installFlags = INSTALL_INTERNAL;
22117            moveCompleteApp = !currentAsec;
22118            measurePath = Environment.getDataAppDirectory(volumeUuid);
22119        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22120            installFlags = INSTALL_EXTERNAL;
22121            moveCompleteApp = false;
22122            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22123        } else {
22124            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22125            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22126                    || !volume.isMountedWritable()) {
22127                freezer.close();
22128                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22129                        "Move location not mounted private volume");
22130            }
22131
22132            Preconditions.checkState(!currentAsec);
22133
22134            installFlags = INSTALL_INTERNAL;
22135            moveCompleteApp = true;
22136            measurePath = Environment.getDataAppDirectory(volumeUuid);
22137        }
22138
22139        final PackageStats stats = new PackageStats(null, -1);
22140        synchronized (mInstaller) {
22141            for (int userId : installedUserIds) {
22142                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22143                    freezer.close();
22144                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22145                            "Failed to measure package size");
22146                }
22147            }
22148        }
22149
22150        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22151                + stats.dataSize);
22152
22153        final long startFreeBytes = measurePath.getFreeSpace();
22154        final long sizeBytes;
22155        if (moveCompleteApp) {
22156            sizeBytes = stats.codeSize + stats.dataSize;
22157        } else {
22158            sizeBytes = stats.codeSize;
22159        }
22160
22161        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22162            freezer.close();
22163            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22164                    "Not enough free space to move");
22165        }
22166
22167        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22168
22169        final CountDownLatch installedLatch = new CountDownLatch(1);
22170        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22171            @Override
22172            public void onUserActionRequired(Intent intent) throws RemoteException {
22173                throw new IllegalStateException();
22174            }
22175
22176            @Override
22177            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22178                    Bundle extras) throws RemoteException {
22179                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22180                        + PackageManager.installStatusToString(returnCode, msg));
22181
22182                installedLatch.countDown();
22183                freezer.close();
22184
22185                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22186                switch (status) {
22187                    case PackageInstaller.STATUS_SUCCESS:
22188                        mMoveCallbacks.notifyStatusChanged(moveId,
22189                                PackageManager.MOVE_SUCCEEDED);
22190                        break;
22191                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22192                        mMoveCallbacks.notifyStatusChanged(moveId,
22193                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22194                        break;
22195                    default:
22196                        mMoveCallbacks.notifyStatusChanged(moveId,
22197                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22198                        break;
22199                }
22200            }
22201        };
22202
22203        final MoveInfo move;
22204        if (moveCompleteApp) {
22205            // Kick off a thread to report progress estimates
22206            new Thread() {
22207                @Override
22208                public void run() {
22209                    while (true) {
22210                        try {
22211                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22212                                break;
22213                            }
22214                        } catch (InterruptedException ignored) {
22215                        }
22216
22217                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22218                        final int progress = 10 + (int) MathUtils.constrain(
22219                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22220                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22221                    }
22222                }
22223            }.start();
22224
22225            final String dataAppName = codeFile.getName();
22226            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22227                    dataAppName, appId, seinfo, targetSdkVersion);
22228        } else {
22229            move = null;
22230        }
22231
22232        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22233
22234        final Message msg = mHandler.obtainMessage(INIT_COPY);
22235        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22236        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22237                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22238                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22239                PackageManager.INSTALL_REASON_UNKNOWN);
22240        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22241        msg.obj = params;
22242
22243        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22244                System.identityHashCode(msg.obj));
22245        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22246                System.identityHashCode(msg.obj));
22247
22248        mHandler.sendMessage(msg);
22249    }
22250
22251    @Override
22252    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22253        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22254
22255        final int realMoveId = mNextMoveId.getAndIncrement();
22256        final Bundle extras = new Bundle();
22257        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22258        mMoveCallbacks.notifyCreated(realMoveId, extras);
22259
22260        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22261            @Override
22262            public void onCreated(int moveId, Bundle extras) {
22263                // Ignored
22264            }
22265
22266            @Override
22267            public void onStatusChanged(int moveId, int status, long estMillis) {
22268                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22269            }
22270        };
22271
22272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22273        storage.setPrimaryStorageUuid(volumeUuid, callback);
22274        return realMoveId;
22275    }
22276
22277    @Override
22278    public int getMoveStatus(int moveId) {
22279        mContext.enforceCallingOrSelfPermission(
22280                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22281        return mMoveCallbacks.mLastStatus.get(moveId);
22282    }
22283
22284    @Override
22285    public void registerMoveCallback(IPackageMoveObserver callback) {
22286        mContext.enforceCallingOrSelfPermission(
22287                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22288        mMoveCallbacks.register(callback);
22289    }
22290
22291    @Override
22292    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22293        mContext.enforceCallingOrSelfPermission(
22294                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22295        mMoveCallbacks.unregister(callback);
22296    }
22297
22298    @Override
22299    public boolean setInstallLocation(int loc) {
22300        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22301                null);
22302        if (getInstallLocation() == loc) {
22303            return true;
22304        }
22305        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22306                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22307            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22308                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22309            return true;
22310        }
22311        return false;
22312   }
22313
22314    @Override
22315    public int getInstallLocation() {
22316        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22317                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22318                PackageHelper.APP_INSTALL_AUTO);
22319    }
22320
22321    /** Called by UserManagerService */
22322    void cleanUpUser(UserManagerService userManager, int userHandle) {
22323        synchronized (mPackages) {
22324            mDirtyUsers.remove(userHandle);
22325            mUserNeedsBadging.delete(userHandle);
22326            mSettings.removeUserLPw(userHandle);
22327            mPendingBroadcasts.remove(userHandle);
22328            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22329            removeUnusedPackagesLPw(userManager, userHandle);
22330        }
22331    }
22332
22333    /**
22334     * We're removing userHandle and would like to remove any downloaded packages
22335     * that are no longer in use by any other user.
22336     * @param userHandle the user being removed
22337     */
22338    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22339        final boolean DEBUG_CLEAN_APKS = false;
22340        int [] users = userManager.getUserIds();
22341        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22342        while (psit.hasNext()) {
22343            PackageSetting ps = psit.next();
22344            if (ps.pkg == null) {
22345                continue;
22346            }
22347            final String packageName = ps.pkg.packageName;
22348            // Skip over if system app
22349            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22350                continue;
22351            }
22352            if (DEBUG_CLEAN_APKS) {
22353                Slog.i(TAG, "Checking package " + packageName);
22354            }
22355            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22356            if (keep) {
22357                if (DEBUG_CLEAN_APKS) {
22358                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22359                }
22360            } else {
22361                for (int i = 0; i < users.length; i++) {
22362                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22363                        keep = true;
22364                        if (DEBUG_CLEAN_APKS) {
22365                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22366                                    + users[i]);
22367                        }
22368                        break;
22369                    }
22370                }
22371            }
22372            if (!keep) {
22373                if (DEBUG_CLEAN_APKS) {
22374                    Slog.i(TAG, "  Removing package " + packageName);
22375                }
22376                mHandler.post(new Runnable() {
22377                    public void run() {
22378                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22379                                userHandle, 0);
22380                    } //end run
22381                });
22382            }
22383        }
22384    }
22385
22386    /** Called by UserManagerService */
22387    void createNewUser(int userId, String[] disallowedPackages) {
22388        synchronized (mInstallLock) {
22389            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22390        }
22391        synchronized (mPackages) {
22392            scheduleWritePackageRestrictionsLocked(userId);
22393            scheduleWritePackageListLocked(userId);
22394            applyFactoryDefaultBrowserLPw(userId);
22395            primeDomainVerificationsLPw(userId);
22396        }
22397    }
22398
22399    void onNewUserCreated(final int userId) {
22400        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22401        // If permission review for legacy apps is required, we represent
22402        // dagerous permissions for such apps as always granted runtime
22403        // permissions to keep per user flag state whether review is needed.
22404        // Hence, if a new user is added we have to propagate dangerous
22405        // permission grants for these legacy apps.
22406        if (mPermissionReviewRequired) {
22407            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22408                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22409        }
22410    }
22411
22412    @Override
22413    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22414        mContext.enforceCallingOrSelfPermission(
22415                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22416                "Only package verification agents can read the verifier device identity");
22417
22418        synchronized (mPackages) {
22419            return mSettings.getVerifierDeviceIdentityLPw();
22420        }
22421    }
22422
22423    @Override
22424    public void setPermissionEnforced(String permission, boolean enforced) {
22425        // TODO: Now that we no longer change GID for storage, this should to away.
22426        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22427                "setPermissionEnforced");
22428        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22429            synchronized (mPackages) {
22430                if (mSettings.mReadExternalStorageEnforced == null
22431                        || mSettings.mReadExternalStorageEnforced != enforced) {
22432                    mSettings.mReadExternalStorageEnforced = enforced;
22433                    mSettings.writeLPr();
22434                }
22435            }
22436            // kill any non-foreground processes so we restart them and
22437            // grant/revoke the GID.
22438            final IActivityManager am = ActivityManager.getService();
22439            if (am != null) {
22440                final long token = Binder.clearCallingIdentity();
22441                try {
22442                    am.killProcessesBelowForeground("setPermissionEnforcement");
22443                } catch (RemoteException e) {
22444                } finally {
22445                    Binder.restoreCallingIdentity(token);
22446                }
22447            }
22448        } else {
22449            throw new IllegalArgumentException("No selective enforcement for " + permission);
22450        }
22451    }
22452
22453    @Override
22454    @Deprecated
22455    public boolean isPermissionEnforced(String permission) {
22456        return true;
22457    }
22458
22459    @Override
22460    public boolean isStorageLow() {
22461        final long token = Binder.clearCallingIdentity();
22462        try {
22463            final DeviceStorageMonitorInternal
22464                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22465            if (dsm != null) {
22466                return dsm.isMemoryLow();
22467            } else {
22468                return false;
22469            }
22470        } finally {
22471            Binder.restoreCallingIdentity(token);
22472        }
22473    }
22474
22475    @Override
22476    public IPackageInstaller getPackageInstaller() {
22477        return mInstallerService;
22478    }
22479
22480    private boolean userNeedsBadging(int userId) {
22481        int index = mUserNeedsBadging.indexOfKey(userId);
22482        if (index < 0) {
22483            final UserInfo userInfo;
22484            final long token = Binder.clearCallingIdentity();
22485            try {
22486                userInfo = sUserManager.getUserInfo(userId);
22487            } finally {
22488                Binder.restoreCallingIdentity(token);
22489            }
22490            final boolean b;
22491            if (userInfo != null && userInfo.isManagedProfile()) {
22492                b = true;
22493            } else {
22494                b = false;
22495            }
22496            mUserNeedsBadging.put(userId, b);
22497            return b;
22498        }
22499        return mUserNeedsBadging.valueAt(index);
22500    }
22501
22502    @Override
22503    public KeySet getKeySetByAlias(String packageName, String alias) {
22504        if (packageName == null || alias == null) {
22505            return null;
22506        }
22507        synchronized(mPackages) {
22508            final PackageParser.Package pkg = mPackages.get(packageName);
22509            if (pkg == null) {
22510                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22511                throw new IllegalArgumentException("Unknown package: " + packageName);
22512            }
22513            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22514            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22515        }
22516    }
22517
22518    @Override
22519    public KeySet getSigningKeySet(String packageName) {
22520        if (packageName == null) {
22521            return null;
22522        }
22523        synchronized(mPackages) {
22524            final PackageParser.Package pkg = mPackages.get(packageName);
22525            if (pkg == null) {
22526                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22527                throw new IllegalArgumentException("Unknown package: " + packageName);
22528            }
22529            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22530                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22531                throw new SecurityException("May not access signing KeySet of other apps.");
22532            }
22533            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22534            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22535        }
22536    }
22537
22538    @Override
22539    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22540        if (packageName == null || ks == null) {
22541            return false;
22542        }
22543        synchronized(mPackages) {
22544            final PackageParser.Package pkg = mPackages.get(packageName);
22545            if (pkg == null) {
22546                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22547                throw new IllegalArgumentException("Unknown package: " + packageName);
22548            }
22549            IBinder ksh = ks.getToken();
22550            if (ksh instanceof KeySetHandle) {
22551                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22552                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22553            }
22554            return false;
22555        }
22556    }
22557
22558    @Override
22559    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22560        if (packageName == null || ks == null) {
22561            return false;
22562        }
22563        synchronized(mPackages) {
22564            final PackageParser.Package pkg = mPackages.get(packageName);
22565            if (pkg == null) {
22566                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22567                throw new IllegalArgumentException("Unknown package: " + packageName);
22568            }
22569            IBinder ksh = ks.getToken();
22570            if (ksh instanceof KeySetHandle) {
22571                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22572                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22573            }
22574            return false;
22575        }
22576    }
22577
22578    private void deletePackageIfUnusedLPr(final String packageName) {
22579        PackageSetting ps = mSettings.mPackages.get(packageName);
22580        if (ps == null) {
22581            return;
22582        }
22583        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22584            // TODO Implement atomic delete if package is unused
22585            // It is currently possible that the package will be deleted even if it is installed
22586            // after this method returns.
22587            mHandler.post(new Runnable() {
22588                public void run() {
22589                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22590                            0, PackageManager.DELETE_ALL_USERS);
22591                }
22592            });
22593        }
22594    }
22595
22596    /**
22597     * Check and throw if the given before/after packages would be considered a
22598     * downgrade.
22599     */
22600    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22601            throws PackageManagerException {
22602        if (after.versionCode < before.mVersionCode) {
22603            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22604                    "Update version code " + after.versionCode + " is older than current "
22605                    + before.mVersionCode);
22606        } else if (after.versionCode == before.mVersionCode) {
22607            if (after.baseRevisionCode < before.baseRevisionCode) {
22608                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22609                        "Update base revision code " + after.baseRevisionCode
22610                        + " is older than current " + before.baseRevisionCode);
22611            }
22612
22613            if (!ArrayUtils.isEmpty(after.splitNames)) {
22614                for (int i = 0; i < after.splitNames.length; i++) {
22615                    final String splitName = after.splitNames[i];
22616                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22617                    if (j != -1) {
22618                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22619                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22620                                    "Update split " + splitName + " revision code "
22621                                    + after.splitRevisionCodes[i] + " is older than current "
22622                                    + before.splitRevisionCodes[j]);
22623                        }
22624                    }
22625                }
22626            }
22627        }
22628    }
22629
22630    private static class MoveCallbacks extends Handler {
22631        private static final int MSG_CREATED = 1;
22632        private static final int MSG_STATUS_CHANGED = 2;
22633
22634        private final RemoteCallbackList<IPackageMoveObserver>
22635                mCallbacks = new RemoteCallbackList<>();
22636
22637        private final SparseIntArray mLastStatus = new SparseIntArray();
22638
22639        public MoveCallbacks(Looper looper) {
22640            super(looper);
22641        }
22642
22643        public void register(IPackageMoveObserver callback) {
22644            mCallbacks.register(callback);
22645        }
22646
22647        public void unregister(IPackageMoveObserver callback) {
22648            mCallbacks.unregister(callback);
22649        }
22650
22651        @Override
22652        public void handleMessage(Message msg) {
22653            final SomeArgs args = (SomeArgs) msg.obj;
22654            final int n = mCallbacks.beginBroadcast();
22655            for (int i = 0; i < n; i++) {
22656                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22657                try {
22658                    invokeCallback(callback, msg.what, args);
22659                } catch (RemoteException ignored) {
22660                }
22661            }
22662            mCallbacks.finishBroadcast();
22663            args.recycle();
22664        }
22665
22666        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22667                throws RemoteException {
22668            switch (what) {
22669                case MSG_CREATED: {
22670                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22671                    break;
22672                }
22673                case MSG_STATUS_CHANGED: {
22674                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22675                    break;
22676                }
22677            }
22678        }
22679
22680        private void notifyCreated(int moveId, Bundle extras) {
22681            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22682
22683            final SomeArgs args = SomeArgs.obtain();
22684            args.argi1 = moveId;
22685            args.arg2 = extras;
22686            obtainMessage(MSG_CREATED, args).sendToTarget();
22687        }
22688
22689        private void notifyStatusChanged(int moveId, int status) {
22690            notifyStatusChanged(moveId, status, -1);
22691        }
22692
22693        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22694            Slog.v(TAG, "Move " + moveId + " status " + status);
22695
22696            final SomeArgs args = SomeArgs.obtain();
22697            args.argi1 = moveId;
22698            args.argi2 = status;
22699            args.arg3 = estMillis;
22700            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22701
22702            synchronized (mLastStatus) {
22703                mLastStatus.put(moveId, status);
22704            }
22705        }
22706    }
22707
22708    private final static class OnPermissionChangeListeners extends Handler {
22709        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22710
22711        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22712                new RemoteCallbackList<>();
22713
22714        public OnPermissionChangeListeners(Looper looper) {
22715            super(looper);
22716        }
22717
22718        @Override
22719        public void handleMessage(Message msg) {
22720            switch (msg.what) {
22721                case MSG_ON_PERMISSIONS_CHANGED: {
22722                    final int uid = msg.arg1;
22723                    handleOnPermissionsChanged(uid);
22724                } break;
22725            }
22726        }
22727
22728        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22729            mPermissionListeners.register(listener);
22730
22731        }
22732
22733        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22734            mPermissionListeners.unregister(listener);
22735        }
22736
22737        public void onPermissionsChanged(int uid) {
22738            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22739                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22740            }
22741        }
22742
22743        private void handleOnPermissionsChanged(int uid) {
22744            final int count = mPermissionListeners.beginBroadcast();
22745            try {
22746                for (int i = 0; i < count; i++) {
22747                    IOnPermissionsChangeListener callback = mPermissionListeners
22748                            .getBroadcastItem(i);
22749                    try {
22750                        callback.onPermissionsChanged(uid);
22751                    } catch (RemoteException e) {
22752                        Log.e(TAG, "Permission listener is dead", e);
22753                    }
22754                }
22755            } finally {
22756                mPermissionListeners.finishBroadcast();
22757            }
22758        }
22759    }
22760
22761    private class PackageManagerInternalImpl extends PackageManagerInternal {
22762        @Override
22763        public void setLocationPackagesProvider(PackagesProvider provider) {
22764            synchronized (mPackages) {
22765                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22766            }
22767        }
22768
22769        @Override
22770        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22771            synchronized (mPackages) {
22772                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22773            }
22774        }
22775
22776        @Override
22777        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22778            synchronized (mPackages) {
22779                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22780            }
22781        }
22782
22783        @Override
22784        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22785            synchronized (mPackages) {
22786                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22787            }
22788        }
22789
22790        @Override
22791        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22792            synchronized (mPackages) {
22793                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22794            }
22795        }
22796
22797        @Override
22798        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22799            synchronized (mPackages) {
22800                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22801            }
22802        }
22803
22804        @Override
22805        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22806            synchronized (mPackages) {
22807                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22808                        packageName, userId);
22809            }
22810        }
22811
22812        @Override
22813        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22814            synchronized (mPackages) {
22815                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22816                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22817                        packageName, userId);
22818            }
22819        }
22820
22821        @Override
22822        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22823            synchronized (mPackages) {
22824                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22825                        packageName, userId);
22826            }
22827        }
22828
22829        @Override
22830        public void setKeepUninstalledPackages(final List<String> packageList) {
22831            Preconditions.checkNotNull(packageList);
22832            List<String> removedFromList = null;
22833            synchronized (mPackages) {
22834                if (mKeepUninstalledPackages != null) {
22835                    final int packagesCount = mKeepUninstalledPackages.size();
22836                    for (int i = 0; i < packagesCount; i++) {
22837                        String oldPackage = mKeepUninstalledPackages.get(i);
22838                        if (packageList != null && packageList.contains(oldPackage)) {
22839                            continue;
22840                        }
22841                        if (removedFromList == null) {
22842                            removedFromList = new ArrayList<>();
22843                        }
22844                        removedFromList.add(oldPackage);
22845                    }
22846                }
22847                mKeepUninstalledPackages = new ArrayList<>(packageList);
22848                if (removedFromList != null) {
22849                    final int removedCount = removedFromList.size();
22850                    for (int i = 0; i < removedCount; i++) {
22851                        deletePackageIfUnusedLPr(removedFromList.get(i));
22852                    }
22853                }
22854            }
22855        }
22856
22857        @Override
22858        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22859            synchronized (mPackages) {
22860                // If we do not support permission review, done.
22861                if (!mPermissionReviewRequired) {
22862                    return false;
22863                }
22864
22865                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22866                if (packageSetting == null) {
22867                    return false;
22868                }
22869
22870                // Permission review applies only to apps not supporting the new permission model.
22871                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22872                    return false;
22873                }
22874
22875                // Legacy apps have the permission and get user consent on launch.
22876                PermissionsState permissionsState = packageSetting.getPermissionsState();
22877                return permissionsState.isPermissionReviewRequired(userId);
22878            }
22879        }
22880
22881        @Override
22882        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22883            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22884        }
22885
22886        @Override
22887        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22888                int userId) {
22889            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22890        }
22891
22892        @Override
22893        public void setDeviceAndProfileOwnerPackages(
22894                int deviceOwnerUserId, String deviceOwnerPackage,
22895                SparseArray<String> profileOwnerPackages) {
22896            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22897                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22898        }
22899
22900        @Override
22901        public boolean isPackageDataProtected(int userId, String packageName) {
22902            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22903        }
22904
22905        @Override
22906        public boolean isPackageEphemeral(int userId, String packageName) {
22907            synchronized (mPackages) {
22908                final PackageSetting ps = mSettings.mPackages.get(packageName);
22909                return ps != null ? ps.getInstantApp(userId) : false;
22910            }
22911        }
22912
22913        @Override
22914        public boolean wasPackageEverLaunched(String packageName, int userId) {
22915            synchronized (mPackages) {
22916                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22917            }
22918        }
22919
22920        @Override
22921        public void grantRuntimePermission(String packageName, String name, int userId,
22922                boolean overridePolicy) {
22923            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22924                    overridePolicy);
22925        }
22926
22927        @Override
22928        public void revokeRuntimePermission(String packageName, String name, int userId,
22929                boolean overridePolicy) {
22930            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22931                    overridePolicy);
22932        }
22933
22934        @Override
22935        public String getNameForUid(int uid) {
22936            return PackageManagerService.this.getNameForUid(uid);
22937        }
22938
22939        @Override
22940        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22941                Intent origIntent, String resolvedType, String callingPackage, int userId) {
22942            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22943                    responseObj, origIntent, resolvedType, callingPackage, userId);
22944        }
22945
22946        @Override
22947        public void grantEphemeralAccess(int userId, Intent intent,
22948                int targetAppId, int ephemeralAppId) {
22949            synchronized (mPackages) {
22950                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22951                        targetAppId, ephemeralAppId);
22952            }
22953        }
22954
22955        @Override
22956        public void pruneInstantApps() {
22957            synchronized (mPackages) {
22958                mInstantAppRegistry.pruneInstantAppsLPw();
22959            }
22960        }
22961
22962        @Override
22963        public String getSetupWizardPackageName() {
22964            return mSetupWizardPackage;
22965        }
22966
22967        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22968            if (policy != null) {
22969                mExternalSourcesPolicy = policy;
22970            }
22971        }
22972
22973        @Override
22974        public boolean isPackagePersistent(String packageName) {
22975            synchronized (mPackages) {
22976                PackageParser.Package pkg = mPackages.get(packageName);
22977                return pkg != null
22978                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22979                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22980                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22981                        : false;
22982            }
22983        }
22984
22985        @Override
22986        public List<PackageInfo> getOverlayPackages(int userId) {
22987            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22988            synchronized (mPackages) {
22989                for (PackageParser.Package p : mPackages.values()) {
22990                    if (p.mOverlayTarget != null) {
22991                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22992                        if (pkg != null) {
22993                            overlayPackages.add(pkg);
22994                        }
22995                    }
22996                }
22997            }
22998            return overlayPackages;
22999        }
23000
23001        @Override
23002        public List<String> getTargetPackageNames(int userId) {
23003            List<String> targetPackages = new ArrayList<>();
23004            synchronized (mPackages) {
23005                for (PackageParser.Package p : mPackages.values()) {
23006                    if (p.mOverlayTarget == null) {
23007                        targetPackages.add(p.packageName);
23008                    }
23009                }
23010            }
23011            return targetPackages;
23012        }
23013
23014        @Override
23015        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23016                @Nullable List<String> overlayPackageNames) {
23017            synchronized (mPackages) {
23018                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23019                    Slog.e(TAG, "failed to find package " + targetPackageName);
23020                    return false;
23021                }
23022
23023                ArrayList<String> paths = null;
23024                if (overlayPackageNames != null) {
23025                    final int N = overlayPackageNames.size();
23026                    paths = new ArrayList<String>(N);
23027                    for (int i = 0; i < N; i++) {
23028                        final String packageName = overlayPackageNames.get(i);
23029                        final PackageParser.Package pkg = mPackages.get(packageName);
23030                        if (pkg == null) {
23031                            Slog.e(TAG, "failed to find package " + packageName);
23032                            return false;
23033                        }
23034                        paths.add(pkg.baseCodePath);
23035                    }
23036                }
23037
23038                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23039                    mEnabledOverlayPaths.get(userId);
23040                if (userSpecificOverlays == null) {
23041                    userSpecificOverlays = new ArrayMap<String, ArrayList<String>>();
23042                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23043                }
23044
23045                if (paths != null && paths.size() > 0) {
23046                    userSpecificOverlays.put(targetPackageName, paths);
23047                } else {
23048                    userSpecificOverlays.remove(targetPackageName);
23049                }
23050                return true;
23051            }
23052        }
23053
23054        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23055                int flags, int userId) {
23056            return resolveIntentInternal(
23057                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23058        }
23059    }
23060
23061    @Override
23062    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23063        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23064        synchronized (mPackages) {
23065            final long identity = Binder.clearCallingIdentity();
23066            try {
23067                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23068                        packageNames, userId);
23069            } finally {
23070                Binder.restoreCallingIdentity(identity);
23071            }
23072        }
23073    }
23074
23075    @Override
23076    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23077        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23078        synchronized (mPackages) {
23079            final long identity = Binder.clearCallingIdentity();
23080            try {
23081                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23082                        packageNames, userId);
23083            } finally {
23084                Binder.restoreCallingIdentity(identity);
23085            }
23086        }
23087    }
23088
23089    private static void enforceSystemOrPhoneCaller(String tag) {
23090        int callingUid = Binder.getCallingUid();
23091        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23092            throw new SecurityException(
23093                    "Cannot call " + tag + " from UID " + callingUid);
23094        }
23095    }
23096
23097    boolean isHistoricalPackageUsageAvailable() {
23098        return mPackageUsage.isHistoricalPackageUsageAvailable();
23099    }
23100
23101    /**
23102     * Return a <b>copy</b> of the collection of packages known to the package manager.
23103     * @return A copy of the values of mPackages.
23104     */
23105    Collection<PackageParser.Package> getPackages() {
23106        synchronized (mPackages) {
23107            return new ArrayList<>(mPackages.values());
23108        }
23109    }
23110
23111    /**
23112     * Logs process start information (including base APK hash) to the security log.
23113     * @hide
23114     */
23115    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23116            String apkFile, int pid) {
23117        if (!SecurityLog.isLoggingEnabled()) {
23118            return;
23119        }
23120        Bundle data = new Bundle();
23121        data.putLong("startTimestamp", System.currentTimeMillis());
23122        data.putString("processName", processName);
23123        data.putInt("uid", uid);
23124        data.putString("seinfo", seinfo);
23125        data.putString("apkFile", apkFile);
23126        data.putInt("pid", pid);
23127        Message msg = mProcessLoggingHandler.obtainMessage(
23128                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23129        msg.setData(data);
23130        mProcessLoggingHandler.sendMessage(msg);
23131    }
23132
23133    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23134        return mCompilerStats.getPackageStats(pkgName);
23135    }
23136
23137    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23138        return getOrCreateCompilerPackageStats(pkg.packageName);
23139    }
23140
23141    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23142        return mCompilerStats.getOrCreatePackageStats(pkgName);
23143    }
23144
23145    public void deleteCompilerPackageStats(String pkgName) {
23146        mCompilerStats.deletePackageStats(pkgName);
23147    }
23148
23149    @Override
23150    public int getInstallReason(String packageName, int userId) {
23151        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23152                true /* requireFullPermission */, false /* checkShell */,
23153                "get install reason");
23154        synchronized (mPackages) {
23155            final PackageSetting ps = mSettings.mPackages.get(packageName);
23156            if (ps != null) {
23157                return ps.getInstallReason(userId);
23158            }
23159        }
23160        return PackageManager.INSTALL_REASON_UNKNOWN;
23161    }
23162
23163    @Override
23164    public boolean canRequestPackageInstalls(String packageName, int userId) {
23165        int callingUid = Binder.getCallingUid();
23166        int uid = getPackageUid(packageName, 0, userId);
23167        if (callingUid != uid && callingUid != Process.ROOT_UID
23168                && callingUid != Process.SYSTEM_UID) {
23169            throw new SecurityException(
23170                    "Caller uid " + callingUid + " does not own package " + packageName);
23171        }
23172        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23173        if (info == null) {
23174            return false;
23175        }
23176        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23177            throw new UnsupportedOperationException(
23178                    "Operation only supported on apps targeting Android O or higher");
23179        }
23180        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23181        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23182        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23183            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23184        }
23185        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23186            return false;
23187        }
23188        if (mExternalSourcesPolicy != null) {
23189            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23190            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23191                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23192            }
23193        }
23194        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23195    }
23196}
23197