PackageManagerService.java revision d9fa667e2db634ceedbbb793ab3210cb7b229920
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_ANY_USER;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
76import static android.content.pm.PackageManager.PERMISSION_DENIED;
77import static android.content.pm.PackageManager.PERMISSION_GRANTED;
78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
79import static android.content.pm.PackageParser.isApkFile;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.AppOpsManager;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.ContentResolver;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralRequest;
128import android.content.pm.EphemeralResolveInfo;
129import android.content.pm.EphemeralResponse;
130import android.content.pm.FallbackCategoryProvider;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstrumentationInfo;
142import android.content.pm.IntentFilterVerificationInfo;
143import android.content.pm.KeySet;
144import android.content.pm.PackageCleanItem;
145import android.content.pm.PackageInfo;
146import android.content.pm.PackageInfoLite;
147import android.content.pm.PackageInstaller;
148import android.content.pm.PackageManager;
149import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
150import android.content.pm.PackageManagerInternal;
151import android.content.pm.PackageParser;
152import android.content.pm.PackageParser.ActivityIntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.PatternMatcher;
185import android.os.Process;
186import android.os.RemoteCallbackList;
187import android.os.RemoteException;
188import android.os.ResultReceiver;
189import android.os.SELinux;
190import android.os.ServiceManager;
191import android.os.ShellCallback;
192import android.os.SystemClock;
193import android.os.SystemProperties;
194import android.os.Trace;
195import android.os.UserHandle;
196import android.os.UserManager;
197import android.os.UserManagerInternal;
198import android.os.storage.IStorageManager;
199import android.os.storage.StorageManagerInternal;
200import android.os.storage.StorageEventListener;
201import android.os.storage.StorageManager;
202import android.os.storage.VolumeInfo;
203import android.os.storage.VolumeRecord;
204import android.provider.Settings.Global;
205import android.provider.Settings.Secure;
206import android.security.KeyStore;
207import android.security.SystemKeyStore;
208import android.system.ErrnoException;
209import android.system.Os;
210import android.text.TextUtils;
211import android.text.format.DateUtils;
212import android.util.ArrayMap;
213import android.util.ArraySet;
214import android.util.Base64;
215import android.util.DisplayMetrics;
216import android.util.EventLog;
217import android.util.ExceptionUtils;
218import android.util.Log;
219import android.util.LogPrinter;
220import android.util.MathUtils;
221import android.util.Pair;
222import android.util.PrintStreamPrinter;
223import android.util.Slog;
224import android.util.SparseArray;
225import android.util.SparseBooleanArray;
226import android.util.SparseIntArray;
227import android.util.Xml;
228import android.util.jar.StrictJarFile;
229import android.view.Display;
230
231import com.android.internal.R;
232import com.android.internal.annotations.GuardedBy;
233import com.android.internal.app.IMediaContainerService;
234import com.android.internal.app.ResolverActivity;
235import com.android.internal.content.NativeLibraryHelper;
236import com.android.internal.content.PackageHelper;
237import com.android.internal.logging.MetricsLogger;
238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
239import com.android.internal.os.IParcelFileDescriptorFactory;
240import com.android.internal.os.RoSystemProperties;
241import com.android.internal.os.SomeArgs;
242import com.android.internal.os.Zygote;
243import com.android.internal.telephony.CarrierAppUtils;
244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
246import com.android.internal.util.FastXmlSerializer;
247import com.android.internal.util.IndentingPrintWriter;
248import com.android.internal.util.Preconditions;
249import com.android.internal.util.XmlUtils;
250import com.android.server.AttributeCache;
251import com.android.server.EventLogTags;
252import com.android.server.FgThread;
253import com.android.server.IntentResolver;
254import com.android.server.LocalServices;
255import com.android.server.ServiceThread;
256import com.android.server.SystemConfig;
257import com.android.server.Watchdog;
258import com.android.server.net.NetworkPolicyManagerInternal;
259import com.android.server.pm.Installer.InstallerException;
260import com.android.server.pm.PermissionsState.PermissionState;
261import com.android.server.pm.Settings.DatabaseVersion;
262import com.android.server.pm.Settings.VersionInfo;
263import com.android.server.pm.dex.DexManager;
264import com.android.server.storage.DeviceStorageMonitorInternal;
265
266import dalvik.system.CloseGuard;
267import dalvik.system.DexFile;
268import dalvik.system.VMRuntime;
269
270import libcore.io.IoUtils;
271import libcore.util.EmptyArray;
272
273import org.xmlpull.v1.XmlPullParser;
274import org.xmlpull.v1.XmlPullParserException;
275import org.xmlpull.v1.XmlSerializer;
276
277import java.io.BufferedOutputStream;
278import java.io.BufferedReader;
279import java.io.ByteArrayInputStream;
280import java.io.ByteArrayOutputStream;
281import java.io.File;
282import java.io.FileDescriptor;
283import java.io.FileInputStream;
284import java.io.FileNotFoundException;
285import java.io.FileOutputStream;
286import java.io.FileReader;
287import java.io.FilenameFilter;
288import java.io.IOException;
289import java.io.PrintWriter;
290import java.nio.charset.StandardCharsets;
291import java.security.DigestInputStream;
292import java.security.MessageDigest;
293import java.security.NoSuchAlgorithmException;
294import java.security.PublicKey;
295import java.security.SecureRandom;
296import java.security.cert.Certificate;
297import java.security.cert.CertificateEncodingException;
298import java.security.cert.CertificateException;
299import java.text.SimpleDateFormat;
300import java.util.ArrayList;
301import java.util.Arrays;
302import java.util.Collection;
303import java.util.Collections;
304import java.util.Comparator;
305import java.util.Date;
306import java.util.HashSet;
307import java.util.HashMap;
308import java.util.Iterator;
309import java.util.List;
310import java.util.Map;
311import java.util.Objects;
312import java.util.Set;
313import java.util.concurrent.CountDownLatch;
314import java.util.concurrent.TimeUnit;
315import java.util.concurrent.atomic.AtomicBoolean;
316import java.util.concurrent.atomic.AtomicInteger;
317
318/**
319 * Keep track of all those APKs everywhere.
320 * <p>
321 * Internally there are two important locks:
322 * <ul>
323 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
324 * and other related state. It is a fine-grained lock that should only be held
325 * momentarily, as it's one of the most contended locks in the system.
326 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
327 * operations typically involve heavy lifting of application data on disk. Since
328 * {@code installd} is single-threaded, and it's operations can often be slow,
329 * this lock should never be acquired while already holding {@link #mPackages}.
330 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
331 * holding {@link #mInstallLock}.
332 * </ul>
333 * Many internal methods rely on the caller to hold the appropriate locks, and
334 * this contract is expressed through method name suffixes:
335 * <ul>
336 * <li>fooLI(): the caller must hold {@link #mInstallLock}
337 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
338 * being modified must be frozen
339 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
340 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
341 * </ul>
342 * <p>
343 * Because this class is very central to the platform's security; please run all
344 * CTS and unit tests whenever making modifications:
345 *
346 * <pre>
347 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
348 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
349 * </pre>
350 */
351public class PackageManagerService extends IPackageManager.Stub {
352    static final String TAG = "PackageManager";
353    static final boolean DEBUG_SETTINGS = false;
354    static final boolean DEBUG_PREFERRED = false;
355    static final boolean DEBUG_UPGRADE = false;
356    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
357    private static final boolean DEBUG_BACKUP = false;
358    private static final boolean DEBUG_INSTALL = false;
359    private static final boolean DEBUG_REMOVE = false;
360    private static final boolean DEBUG_BROADCASTS = false;
361    private static final boolean DEBUG_SHOW_INFO = false;
362    private static final boolean DEBUG_PACKAGE_INFO = false;
363    private static final boolean DEBUG_INTENT_MATCHING = false;
364    private static final boolean DEBUG_PACKAGE_SCANNING = false;
365    private static final boolean DEBUG_VERIFY = false;
366    private static final boolean DEBUG_FILTERS = false;
367
368    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
369    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
370    // user, but by default initialize to this.
371    static final boolean DEBUG_DEXOPT = false;
372
373    private static final boolean DEBUG_ABI_SELECTION = false;
374    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
375    private static final boolean DEBUG_TRIAGED_MISSING = false;
376    private static final boolean DEBUG_APP_DATA = false;
377
378    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
379    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
380
381    private static final boolean DISABLE_EPHEMERAL_APPS = false;
382    private static final boolean HIDE_EPHEMERAL_APIS = true;
383
384    private static final boolean ENABLE_QUOTA =
385            SystemProperties.getBoolean("persist.fw.quota", false);
386
387    private static final int RADIO_UID = Process.PHONE_UID;
388    private static final int LOG_UID = Process.LOG_UID;
389    private static final int NFC_UID = Process.NFC_UID;
390    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
391    private static final int SHELL_UID = Process.SHELL_UID;
392
393    // Cap the size of permission trees that 3rd party apps can define
394    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
395
396    // Suffix used during package installation when copying/moving
397    // package apks to install directory.
398    private static final String INSTALL_PACKAGE_SUFFIX = "-";
399
400    static final int SCAN_NO_DEX = 1<<1;
401    static final int SCAN_FORCE_DEX = 1<<2;
402    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
403    static final int SCAN_NEW_INSTALL = 1<<4;
404    static final int SCAN_UPDATE_TIME = 1<<5;
405    static final int SCAN_BOOTING = 1<<6;
406    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
407    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
408    static final int SCAN_REPLACING = 1<<9;
409    static final int SCAN_REQUIRE_KNOWN = 1<<10;
410    static final int SCAN_MOVE = 1<<11;
411    static final int SCAN_INITIAL = 1<<12;
412    static final int SCAN_CHECK_ONLY = 1<<13;
413    static final int SCAN_DONT_KILL_APP = 1<<14;
414    static final int SCAN_IGNORE_FROZEN = 1<<15;
415    static final int REMOVE_CHATTY = 1<<16;
416    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
417
418    private static final int[] EMPTY_INT_ARRAY = new int[0];
419
420    /**
421     * Timeout (in milliseconds) after which the watchdog should declare that
422     * our handler thread is wedged.  The usual default for such things is one
423     * minute but we sometimes do very lengthy I/O operations on this thread,
424     * such as installing multi-gigabyte applications, so ours needs to be longer.
425     */
426    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
427
428    /**
429     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
430     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
431     * settings entry if available, otherwise we use the hardcoded default.  If it's been
432     * more than this long since the last fstrim, we force one during the boot sequence.
433     *
434     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
435     * one gets run at the next available charging+idle time.  This final mandatory
436     * no-fstrim check kicks in only of the other scheduling criteria is never met.
437     */
438    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
439
440    /**
441     * Whether verification is enabled by default.
442     */
443    private static final boolean DEFAULT_VERIFY_ENABLE = true;
444
445    /**
446     * The default maximum time to wait for the verification agent to return in
447     * milliseconds.
448     */
449    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
450
451    /**
452     * The default response for package verification timeout.
453     *
454     * This can be either PackageManager.VERIFICATION_ALLOW or
455     * PackageManager.VERIFICATION_REJECT.
456     */
457    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
458
459    static final String PLATFORM_PACKAGE_NAME = "android";
460
461    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
462
463    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
464            DEFAULT_CONTAINER_PACKAGE,
465            "com.android.defcontainer.DefaultContainerService");
466
467    private static final String KILL_APP_REASON_GIDS_CHANGED =
468            "permission grant or revoke changed gids";
469
470    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
471            "permissions revoked";
472
473    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
474
475    private static final String PACKAGE_SCHEME = "package";
476
477    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
478    /**
479     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
480     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
481     * VENDOR_OVERLAY_DIR.
482     */
483    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
484    /**
485     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
486     * is in VENDOR_OVERLAY_THEME_PROPERTY.
487     */
488    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
489            = "persist.vendor.overlay.theme";
490
491    /** Permission grant: not grant the permission. */
492    private static final int GRANT_DENIED = 1;
493
494    /** Permission grant: grant the permission as an install permission. */
495    private static final int GRANT_INSTALL = 2;
496
497    /** Permission grant: grant the permission as a runtime one. */
498    private static final int GRANT_RUNTIME = 3;
499
500    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
501    private static final int GRANT_UPGRADE = 4;
502
503    /** Canonical intent used to identify what counts as a "web browser" app */
504    private static final Intent sBrowserIntent;
505    static {
506        sBrowserIntent = new Intent();
507        sBrowserIntent.setAction(Intent.ACTION_VIEW);
508        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
509        sBrowserIntent.setData(Uri.parse("http:"));
510    }
511
512    /**
513     * The set of all protected actions [i.e. those actions for which a high priority
514     * intent filter is disallowed].
515     */
516    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
517    static {
518        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
519        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
520        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
521        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
522    }
523
524    // Compilation reasons.
525    public static final int REASON_FIRST_BOOT = 0;
526    public static final int REASON_BOOT = 1;
527    public static final int REASON_INSTALL = 2;
528    public static final int REASON_BACKGROUND_DEXOPT = 3;
529    public static final int REASON_AB_OTA = 4;
530    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
531    public static final int REASON_SHARED_APK = 6;
532    public static final int REASON_FORCED_DEXOPT = 7;
533    public static final int REASON_CORE_APP = 8;
534
535    public static final int REASON_LAST = REASON_CORE_APP;
536
537    /** Special library name that skips shared libraries check during compilation. */
538    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
539
540    /** All dangerous permission names in the same order as the events in MetricsEvent */
541    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
542            Manifest.permission.READ_CALENDAR,
543            Manifest.permission.WRITE_CALENDAR,
544            Manifest.permission.CAMERA,
545            Manifest.permission.READ_CONTACTS,
546            Manifest.permission.WRITE_CONTACTS,
547            Manifest.permission.GET_ACCOUNTS,
548            Manifest.permission.ACCESS_FINE_LOCATION,
549            Manifest.permission.ACCESS_COARSE_LOCATION,
550            Manifest.permission.RECORD_AUDIO,
551            Manifest.permission.READ_PHONE_STATE,
552            Manifest.permission.CALL_PHONE,
553            Manifest.permission.READ_CALL_LOG,
554            Manifest.permission.WRITE_CALL_LOG,
555            Manifest.permission.ADD_VOICEMAIL,
556            Manifest.permission.USE_SIP,
557            Manifest.permission.PROCESS_OUTGOING_CALLS,
558            Manifest.permission.READ_CELL_BROADCASTS,
559            Manifest.permission.BODY_SENSORS,
560            Manifest.permission.SEND_SMS,
561            Manifest.permission.RECEIVE_SMS,
562            Manifest.permission.READ_SMS,
563            Manifest.permission.RECEIVE_WAP_PUSH,
564            Manifest.permission.RECEIVE_MMS,
565            Manifest.permission.READ_EXTERNAL_STORAGE,
566            Manifest.permission.WRITE_EXTERNAL_STORAGE,
567            Manifest.permission.READ_PHONE_NUMBER);
568
569
570    /**
571     * Version number for the package parser cache. Increment this whenever the format or
572     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
573     */
574    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
575
576    /**
577     * Whether the package parser cache is enabled.
578     */
579    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
580
581    final ServiceThread mHandlerThread;
582
583    final PackageHandler mHandler;
584
585    private final ProcessLoggingHandler mProcessLoggingHandler;
586
587    /**
588     * Messages for {@link #mHandler} that need to wait for system ready before
589     * being dispatched.
590     */
591    private ArrayList<Message> mPostSystemReadyMessages;
592
593    final int mSdkVersion = Build.VERSION.SDK_INT;
594
595    final Context mContext;
596    final boolean mFactoryTest;
597    final boolean mOnlyCore;
598    final DisplayMetrics mMetrics;
599    final int mDefParseFlags;
600    final String[] mSeparateProcesses;
601    final boolean mIsUpgrade;
602    final boolean mIsPreNUpgrade;
603    final boolean mIsPreNMR1Upgrade;
604
605    @GuardedBy("mPackages")
606    private boolean mDexOptDialogShown;
607
608    /** The location for ASEC container files on internal storage. */
609    final String mAsecInternalPath;
610
611    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
612    // LOCK HELD.  Can be called with mInstallLock held.
613    @GuardedBy("mInstallLock")
614    final Installer mInstaller;
615
616    /** Directory where installed third-party apps stored */
617    final File mAppInstallDir;
618    final File mEphemeralInstallDir;
619
620    /**
621     * Directory to which applications installed internally have their
622     * 32 bit native libraries copied.
623     */
624    private File mAppLib32InstallDir;
625
626    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
627    // apps.
628    final File mDrmAppPrivateInstallDir;
629
630    // ----------------------------------------------------------------
631
632    // Lock for state used when installing and doing other long running
633    // operations.  Methods that must be called with this lock held have
634    // the suffix "LI".
635    final Object mInstallLock = new Object();
636
637    // ----------------------------------------------------------------
638
639    // Keys are String (package name), values are Package.  This also serves
640    // as the lock for the global state.  Methods that must be called with
641    // this lock held have the prefix "LP".
642    @GuardedBy("mPackages")
643    final ArrayMap<String, PackageParser.Package> mPackages =
644            new ArrayMap<String, PackageParser.Package>();
645
646    final ArrayMap<String, Set<String>> mKnownCodebase =
647            new ArrayMap<String, Set<String>>();
648
649    // Tracks available target package names -> overlay package paths.
650    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
651        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
652
653    /**
654     * Tracks new system packages [received in an OTA] that we expect to
655     * find updated user-installed versions. Keys are package name, values
656     * are package location.
657     */
658    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
659    /**
660     * Tracks high priority intent filters for protected actions. During boot, certain
661     * filter actions are protected and should never be allowed to have a high priority
662     * intent filter for them. However, there is one, and only one exception -- the
663     * setup wizard. It must be able to define a high priority intent filter for these
664     * actions to ensure there are no escapes from the wizard. We need to delay processing
665     * of these during boot as we need to look at all of the system packages in order
666     * to know which component is the setup wizard.
667     */
668    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
669    /**
670     * Whether or not processing protected filters should be deferred.
671     */
672    private boolean mDeferProtectedFilters = true;
673
674    /**
675     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
676     */
677    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
678    /**
679     * Whether or not system app permissions should be promoted from install to runtime.
680     */
681    boolean mPromoteSystemApps;
682
683    @GuardedBy("mPackages")
684    final Settings mSettings;
685
686    /**
687     * Set of package names that are currently "frozen", which means active
688     * surgery is being done on the code/data for that package. The platform
689     * will refuse to launch frozen packages to avoid race conditions.
690     *
691     * @see PackageFreezer
692     */
693    @GuardedBy("mPackages")
694    final ArraySet<String> mFrozenPackages = new ArraySet<>();
695
696    final ProtectedPackages mProtectedPackages;
697
698    boolean mFirstBoot;
699
700    // System configuration read by SystemConfig.
701    final int[] mGlobalGids;
702    final SparseArray<ArraySet<String>> mSystemPermissions;
703    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
704
705    // If mac_permissions.xml was found for seinfo labeling.
706    boolean mFoundPolicyFile;
707
708    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
709
710    public static final class SharedLibraryEntry {
711        public final String path;
712        public final String apk;
713
714        SharedLibraryEntry(String _path, String _apk) {
715            path = _path;
716            apk = _apk;
717        }
718    }
719
720    // Currently known shared libraries.
721    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
722            new ArrayMap<String, SharedLibraryEntry>();
723
724    // All available activities, for your resolving pleasure.
725    final ActivityIntentResolver mActivities =
726            new ActivityIntentResolver();
727
728    // All available receivers, for your resolving pleasure.
729    final ActivityIntentResolver mReceivers =
730            new ActivityIntentResolver();
731
732    // All available services, for your resolving pleasure.
733    final ServiceIntentResolver mServices = new ServiceIntentResolver();
734
735    // All available providers, for your resolving pleasure.
736    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
737
738    // Mapping from provider base names (first directory in content URI codePath)
739    // to the provider information.
740    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
741            new ArrayMap<String, PackageParser.Provider>();
742
743    // Mapping from instrumentation class names to info about them.
744    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
745            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
746
747    // Mapping from permission names to info about them.
748    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
749            new ArrayMap<String, PackageParser.PermissionGroup>();
750
751    // Packages whose data we have transfered into another package, thus
752    // should no longer exist.
753    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
754
755    // Broadcast actions that are only available to the system.
756    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
757
758    /** List of packages waiting for verification. */
759    final SparseArray<PackageVerificationState> mPendingVerification
760            = new SparseArray<PackageVerificationState>();
761
762    /** Set of packages associated with each app op permission. */
763    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
764
765    final PackageInstallerService mInstallerService;
766
767    private final PackageDexOptimizer mPackageDexOptimizer;
768    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
769    // is used by other apps).
770    private final DexManager mDexManager;
771
772    private AtomicInteger mNextMoveId = new AtomicInteger();
773    private final MoveCallbacks mMoveCallbacks;
774
775    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
776
777    // Cache of users who need badging.
778    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
779
780    /** Token for keys in mPendingVerification. */
781    private int mPendingVerificationToken = 0;
782
783    volatile boolean mSystemReady;
784    volatile boolean mSafeMode;
785    volatile boolean mHasSystemUidErrors;
786
787    ApplicationInfo mAndroidApplication;
788    final ActivityInfo mResolveActivity = new ActivityInfo();
789    final ResolveInfo mResolveInfo = new ResolveInfo();
790    ComponentName mResolveComponentName;
791    PackageParser.Package mPlatformPackage;
792    ComponentName mCustomResolverComponentName;
793
794    boolean mResolverReplaced = false;
795
796    private final @Nullable ComponentName mIntentFilterVerifierComponent;
797    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
798
799    private int mIntentFilterVerificationToken = 0;
800
801    /** The service connection to the ephemeral resolver */
802    final EphemeralResolverConnection mEphemeralResolverConnection;
803
804    /** Component used to install ephemeral applications */
805    ComponentName mEphemeralInstallerComponent;
806    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
807    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
808
809    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
810            = new SparseArray<IntentFilterVerificationState>();
811
812    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
813
814    // List of packages names to keep cached, even if they are uninstalled for all users
815    private List<String> mKeepUninstalledPackages;
816
817    private UserManagerInternal mUserManagerInternal;
818
819    private File mCacheDir;
820
821    private static class IFVerificationParams {
822        PackageParser.Package pkg;
823        boolean replacing;
824        int userId;
825        int verifierUid;
826
827        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
828                int _userId, int _verifierUid) {
829            pkg = _pkg;
830            replacing = _replacing;
831            userId = _userId;
832            replacing = _replacing;
833            verifierUid = _verifierUid;
834        }
835    }
836
837    private interface IntentFilterVerifier<T extends IntentFilter> {
838        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
839                                               T filter, String packageName);
840        void startVerifications(int userId);
841        void receiveVerificationResponse(int verificationId);
842    }
843
844    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
845        private Context mContext;
846        private ComponentName mIntentFilterVerifierComponent;
847        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
848
849        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
850            mContext = context;
851            mIntentFilterVerifierComponent = verifierComponent;
852        }
853
854        private String getDefaultScheme() {
855            return IntentFilter.SCHEME_HTTPS;
856        }
857
858        @Override
859        public void startVerifications(int userId) {
860            // Launch verifications requests
861            int count = mCurrentIntentFilterVerifications.size();
862            for (int n=0; n<count; n++) {
863                int verificationId = mCurrentIntentFilterVerifications.get(n);
864                final IntentFilterVerificationState ivs =
865                        mIntentFilterVerificationStates.get(verificationId);
866
867                String packageName = ivs.getPackageName();
868
869                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
870                final int filterCount = filters.size();
871                ArraySet<String> domainsSet = new ArraySet<>();
872                for (int m=0; m<filterCount; m++) {
873                    PackageParser.ActivityIntentInfo filter = filters.get(m);
874                    domainsSet.addAll(filter.getHostsList());
875                }
876                synchronized (mPackages) {
877                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
878                            packageName, domainsSet) != null) {
879                        scheduleWriteSettingsLocked();
880                    }
881                }
882                sendVerificationRequest(userId, verificationId, ivs);
883            }
884            mCurrentIntentFilterVerifications.clear();
885        }
886
887        private void sendVerificationRequest(int userId, int verificationId,
888                IntentFilterVerificationState ivs) {
889
890            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
891            verificationIntent.putExtra(
892                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
893                    verificationId);
894            verificationIntent.putExtra(
895                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
896                    getDefaultScheme());
897            verificationIntent.putExtra(
898                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
899                    ivs.getHostsString());
900            verificationIntent.putExtra(
901                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
902                    ivs.getPackageName());
903            verificationIntent.setComponent(mIntentFilterVerifierComponent);
904            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
905
906            UserHandle user = new UserHandle(userId);
907            mContext.sendBroadcastAsUser(verificationIntent, user);
908            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
909                    "Sending IntentFilter verification broadcast");
910        }
911
912        public void receiveVerificationResponse(int verificationId) {
913            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
914
915            final boolean verified = ivs.isVerified();
916
917            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
918            final int count = filters.size();
919            if (DEBUG_DOMAIN_VERIFICATION) {
920                Slog.i(TAG, "Received verification response " + verificationId
921                        + " for " + count + " filters, verified=" + verified);
922            }
923            for (int n=0; n<count; n++) {
924                PackageParser.ActivityIntentInfo filter = filters.get(n);
925                filter.setVerified(verified);
926
927                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
928                        + " verified with result:" + verified + " and hosts:"
929                        + ivs.getHostsString());
930            }
931
932            mIntentFilterVerificationStates.remove(verificationId);
933
934            final String packageName = ivs.getPackageName();
935            IntentFilterVerificationInfo ivi = null;
936
937            synchronized (mPackages) {
938                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
939            }
940            if (ivi == null) {
941                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
942                        + verificationId + " packageName:" + packageName);
943                return;
944            }
945            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
946                    "Updating IntentFilterVerificationInfo for package " + packageName
947                            +" verificationId:" + verificationId);
948
949            synchronized (mPackages) {
950                if (verified) {
951                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
952                } else {
953                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
954                }
955                scheduleWriteSettingsLocked();
956
957                final int userId = ivs.getUserId();
958                if (userId != UserHandle.USER_ALL) {
959                    final int userStatus =
960                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
961
962                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
963                    boolean needUpdate = false;
964
965                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
966                    // already been set by the User thru the Disambiguation dialog
967                    switch (userStatus) {
968                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
969                            if (verified) {
970                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
971                            } else {
972                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
973                            }
974                            needUpdate = true;
975                            break;
976
977                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
978                            if (verified) {
979                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
980                                needUpdate = true;
981                            }
982                            break;
983
984                        default:
985                            // Nothing to do
986                    }
987
988                    if (needUpdate) {
989                        mSettings.updateIntentFilterVerificationStatusLPw(
990                                packageName, updatedStatus, userId);
991                        scheduleWritePackageRestrictionsLocked(userId);
992                    }
993                }
994            }
995        }
996
997        @Override
998        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
999                    ActivityIntentInfo filter, String packageName) {
1000            if (!hasValidDomains(filter)) {
1001                return false;
1002            }
1003            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1004            if (ivs == null) {
1005                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1006                        packageName);
1007            }
1008            if (DEBUG_DOMAIN_VERIFICATION) {
1009                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1010            }
1011            ivs.addFilter(filter);
1012            return true;
1013        }
1014
1015        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1016                int userId, int verificationId, String packageName) {
1017            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1018                    verifierUid, userId, packageName);
1019            ivs.setPendingState();
1020            synchronized (mPackages) {
1021                mIntentFilterVerificationStates.append(verificationId, ivs);
1022                mCurrentIntentFilterVerifications.add(verificationId);
1023            }
1024            return ivs;
1025        }
1026    }
1027
1028    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1029        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1030                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1031                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1032    }
1033
1034    // Set of pending broadcasts for aggregating enable/disable of components.
1035    static class PendingPackageBroadcasts {
1036        // for each user id, a map of <package name -> components within that package>
1037        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1038
1039        public PendingPackageBroadcasts() {
1040            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1041        }
1042
1043        public ArrayList<String> get(int userId, String packageName) {
1044            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1045            return packages.get(packageName);
1046        }
1047
1048        public void put(int userId, String packageName, ArrayList<String> components) {
1049            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1050            packages.put(packageName, components);
1051        }
1052
1053        public void remove(int userId, String packageName) {
1054            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1055            if (packages != null) {
1056                packages.remove(packageName);
1057            }
1058        }
1059
1060        public void remove(int userId) {
1061            mUidMap.remove(userId);
1062        }
1063
1064        public int userIdCount() {
1065            return mUidMap.size();
1066        }
1067
1068        public int userIdAt(int n) {
1069            return mUidMap.keyAt(n);
1070        }
1071
1072        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1073            return mUidMap.get(userId);
1074        }
1075
1076        public int size() {
1077            // total number of pending broadcast entries across all userIds
1078            int num = 0;
1079            for (int i = 0; i< mUidMap.size(); i++) {
1080                num += mUidMap.valueAt(i).size();
1081            }
1082            return num;
1083        }
1084
1085        public void clear() {
1086            mUidMap.clear();
1087        }
1088
1089        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1090            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1091            if (map == null) {
1092                map = new ArrayMap<String, ArrayList<String>>();
1093                mUidMap.put(userId, map);
1094            }
1095            return map;
1096        }
1097    }
1098    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1099
1100    // Service Connection to remote media container service to copy
1101    // package uri's from external media onto secure containers
1102    // or internal storage.
1103    private IMediaContainerService mContainerService = null;
1104
1105    static final int SEND_PENDING_BROADCAST = 1;
1106    static final int MCS_BOUND = 3;
1107    static final int END_COPY = 4;
1108    static final int INIT_COPY = 5;
1109    static final int MCS_UNBIND = 6;
1110    static final int START_CLEANING_PACKAGE = 7;
1111    static final int FIND_INSTALL_LOC = 8;
1112    static final int POST_INSTALL = 9;
1113    static final int MCS_RECONNECT = 10;
1114    static final int MCS_GIVE_UP = 11;
1115    static final int UPDATED_MEDIA_STATUS = 12;
1116    static final int WRITE_SETTINGS = 13;
1117    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1118    static final int PACKAGE_VERIFIED = 15;
1119    static final int CHECK_PENDING_VERIFICATION = 16;
1120    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1121    static final int INTENT_FILTER_VERIFIED = 18;
1122    static final int WRITE_PACKAGE_LIST = 19;
1123    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1124
1125    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1126
1127    // Delay time in millisecs
1128    static final int BROADCAST_DELAY = 10 * 1000;
1129
1130    static UserManagerService sUserManager;
1131
1132    // Stores a list of users whose package restrictions file needs to be updated
1133    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1134
1135    final private DefaultContainerConnection mDefContainerConn =
1136            new DefaultContainerConnection();
1137    class DefaultContainerConnection implements ServiceConnection {
1138        public void onServiceConnected(ComponentName name, IBinder service) {
1139            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1140            final IMediaContainerService imcs = IMediaContainerService.Stub
1141                    .asInterface(Binder.allowBlocking(service));
1142            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1143        }
1144
1145        public void onServiceDisconnected(ComponentName name) {
1146            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1147        }
1148    }
1149
1150    // Recordkeeping of restore-after-install operations that are currently in flight
1151    // between the Package Manager and the Backup Manager
1152    static class PostInstallData {
1153        public InstallArgs args;
1154        public PackageInstalledInfo res;
1155
1156        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1157            args = _a;
1158            res = _r;
1159        }
1160    }
1161
1162    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1163    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1164
1165    // XML tags for backup/restore of various bits of state
1166    private static final String TAG_PREFERRED_BACKUP = "pa";
1167    private static final String TAG_DEFAULT_APPS = "da";
1168    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1169
1170    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1171    private static final String TAG_ALL_GRANTS = "rt-grants";
1172    private static final String TAG_GRANT = "grant";
1173    private static final String ATTR_PACKAGE_NAME = "pkg";
1174
1175    private static final String TAG_PERMISSION = "perm";
1176    private static final String ATTR_PERMISSION_NAME = "name";
1177    private static final String ATTR_IS_GRANTED = "g";
1178    private static final String ATTR_USER_SET = "set";
1179    private static final String ATTR_USER_FIXED = "fixed";
1180    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1181
1182    // System/policy permission grants are not backed up
1183    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1184            FLAG_PERMISSION_POLICY_FIXED
1185            | FLAG_PERMISSION_SYSTEM_FIXED
1186            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1187
1188    // And we back up these user-adjusted states
1189    private static final int USER_RUNTIME_GRANT_MASK =
1190            FLAG_PERMISSION_USER_SET
1191            | FLAG_PERMISSION_USER_FIXED
1192            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1193
1194    final @Nullable String mRequiredVerifierPackage;
1195    final @NonNull String mRequiredInstallerPackage;
1196    final @NonNull String mRequiredUninstallerPackage;
1197    final @Nullable String mSetupWizardPackage;
1198    final @Nullable String mStorageManagerPackage;
1199    final @NonNull String mServicesSystemSharedLibraryPackageName;
1200    final @NonNull String mSharedSystemSharedLibraryPackageName;
1201
1202    final boolean mPermissionReviewRequired;
1203
1204    private final PackageUsage mPackageUsage = new PackageUsage();
1205    private final CompilerStats mCompilerStats = new CompilerStats();
1206
1207    class PackageHandler extends Handler {
1208        private boolean mBound = false;
1209        final ArrayList<HandlerParams> mPendingInstalls =
1210            new ArrayList<HandlerParams>();
1211
1212        private boolean connectToService() {
1213            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1214                    " DefaultContainerService");
1215            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1216            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1217            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1218                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1219                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1220                mBound = true;
1221                return true;
1222            }
1223            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1224            return false;
1225        }
1226
1227        private void disconnectService() {
1228            mContainerService = null;
1229            mBound = false;
1230            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1231            mContext.unbindService(mDefContainerConn);
1232            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1233        }
1234
1235        PackageHandler(Looper looper) {
1236            super(looper);
1237        }
1238
1239        public void handleMessage(Message msg) {
1240            try {
1241                doHandleMessage(msg);
1242            } finally {
1243                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1244            }
1245        }
1246
1247        void doHandleMessage(Message msg) {
1248            switch (msg.what) {
1249                case INIT_COPY: {
1250                    HandlerParams params = (HandlerParams) msg.obj;
1251                    int idx = mPendingInstalls.size();
1252                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1253                    // If a bind was already initiated we dont really
1254                    // need to do anything. The pending install
1255                    // will be processed later on.
1256                    if (!mBound) {
1257                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1258                                System.identityHashCode(mHandler));
1259                        // If this is the only one pending we might
1260                        // have to bind to the service again.
1261                        if (!connectToService()) {
1262                            Slog.e(TAG, "Failed to bind to media container service");
1263                            params.serviceError();
1264                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1265                                    System.identityHashCode(mHandler));
1266                            if (params.traceMethod != null) {
1267                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1268                                        params.traceCookie);
1269                            }
1270                            return;
1271                        } else {
1272                            // Once we bind to the service, the first
1273                            // pending request will be processed.
1274                            mPendingInstalls.add(idx, params);
1275                        }
1276                    } else {
1277                        mPendingInstalls.add(idx, params);
1278                        // Already bound to the service. Just make
1279                        // sure we trigger off processing the first request.
1280                        if (idx == 0) {
1281                            mHandler.sendEmptyMessage(MCS_BOUND);
1282                        }
1283                    }
1284                    break;
1285                }
1286                case MCS_BOUND: {
1287                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1288                    if (msg.obj != null) {
1289                        mContainerService = (IMediaContainerService) msg.obj;
1290                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1291                                System.identityHashCode(mHandler));
1292                    }
1293                    if (mContainerService == null) {
1294                        if (!mBound) {
1295                            // Something seriously wrong since we are not bound and we are not
1296                            // waiting for connection. Bail out.
1297                            Slog.e(TAG, "Cannot bind to media container service");
1298                            for (HandlerParams params : mPendingInstalls) {
1299                                // Indicate service bind error
1300                                params.serviceError();
1301                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1302                                        System.identityHashCode(params));
1303                                if (params.traceMethod != null) {
1304                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1305                                            params.traceMethod, params.traceCookie);
1306                                }
1307                                return;
1308                            }
1309                            mPendingInstalls.clear();
1310                        } else {
1311                            Slog.w(TAG, "Waiting to connect to media container service");
1312                        }
1313                    } else if (mPendingInstalls.size() > 0) {
1314                        HandlerParams params = mPendingInstalls.get(0);
1315                        if (params != null) {
1316                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1317                                    System.identityHashCode(params));
1318                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1319                            if (params.startCopy()) {
1320                                // We are done...  look for more work or to
1321                                // go idle.
1322                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1323                                        "Checking for more work or unbind...");
1324                                // Delete pending install
1325                                if (mPendingInstalls.size() > 0) {
1326                                    mPendingInstalls.remove(0);
1327                                }
1328                                if (mPendingInstalls.size() == 0) {
1329                                    if (mBound) {
1330                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1331                                                "Posting delayed MCS_UNBIND");
1332                                        removeMessages(MCS_UNBIND);
1333                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1334                                        // Unbind after a little delay, to avoid
1335                                        // continual thrashing.
1336                                        sendMessageDelayed(ubmsg, 10000);
1337                                    }
1338                                } else {
1339                                    // There are more pending requests in queue.
1340                                    // Just post MCS_BOUND message to trigger processing
1341                                    // of next pending install.
1342                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1343                                            "Posting MCS_BOUND for next work");
1344                                    mHandler.sendEmptyMessage(MCS_BOUND);
1345                                }
1346                            }
1347                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1348                        }
1349                    } else {
1350                        // Should never happen ideally.
1351                        Slog.w(TAG, "Empty queue");
1352                    }
1353                    break;
1354                }
1355                case MCS_RECONNECT: {
1356                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1357                    if (mPendingInstalls.size() > 0) {
1358                        if (mBound) {
1359                            disconnectService();
1360                        }
1361                        if (!connectToService()) {
1362                            Slog.e(TAG, "Failed to bind to media container service");
1363                            for (HandlerParams params : mPendingInstalls) {
1364                                // Indicate service bind error
1365                                params.serviceError();
1366                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1367                                        System.identityHashCode(params));
1368                            }
1369                            mPendingInstalls.clear();
1370                        }
1371                    }
1372                    break;
1373                }
1374                case MCS_UNBIND: {
1375                    // If there is no actual work left, then time to unbind.
1376                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1377
1378                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1379                        if (mBound) {
1380                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1381
1382                            disconnectService();
1383                        }
1384                    } else if (mPendingInstalls.size() > 0) {
1385                        // There are more pending requests in queue.
1386                        // Just post MCS_BOUND message to trigger processing
1387                        // of next pending install.
1388                        mHandler.sendEmptyMessage(MCS_BOUND);
1389                    }
1390
1391                    break;
1392                }
1393                case MCS_GIVE_UP: {
1394                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1395                    HandlerParams params = mPendingInstalls.remove(0);
1396                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1397                            System.identityHashCode(params));
1398                    break;
1399                }
1400                case SEND_PENDING_BROADCAST: {
1401                    String packages[];
1402                    ArrayList<String> components[];
1403                    int size = 0;
1404                    int uids[];
1405                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406                    synchronized (mPackages) {
1407                        if (mPendingBroadcasts == null) {
1408                            return;
1409                        }
1410                        size = mPendingBroadcasts.size();
1411                        if (size <= 0) {
1412                            // Nothing to be done. Just return
1413                            return;
1414                        }
1415                        packages = new String[size];
1416                        components = new ArrayList[size];
1417                        uids = new int[size];
1418                        int i = 0;  // filling out the above arrays
1419
1420                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1421                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1422                            Iterator<Map.Entry<String, ArrayList<String>>> it
1423                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1424                                            .entrySet().iterator();
1425                            while (it.hasNext() && i < size) {
1426                                Map.Entry<String, ArrayList<String>> ent = it.next();
1427                                packages[i] = ent.getKey();
1428                                components[i] = ent.getValue();
1429                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1430                                uids[i] = (ps != null)
1431                                        ? UserHandle.getUid(packageUserId, ps.appId)
1432                                        : -1;
1433                                i++;
1434                            }
1435                        }
1436                        size = i;
1437                        mPendingBroadcasts.clear();
1438                    }
1439                    // Send broadcasts
1440                    for (int i = 0; i < size; i++) {
1441                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1442                    }
1443                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1444                    break;
1445                }
1446                case START_CLEANING_PACKAGE: {
1447                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1448                    final String packageName = (String)msg.obj;
1449                    final int userId = msg.arg1;
1450                    final boolean andCode = msg.arg2 != 0;
1451                    synchronized (mPackages) {
1452                        if (userId == UserHandle.USER_ALL) {
1453                            int[] users = sUserManager.getUserIds();
1454                            for (int user : users) {
1455                                mSettings.addPackageToCleanLPw(
1456                                        new PackageCleanItem(user, packageName, andCode));
1457                            }
1458                        } else {
1459                            mSettings.addPackageToCleanLPw(
1460                                    new PackageCleanItem(userId, packageName, andCode));
1461                        }
1462                    }
1463                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1464                    startCleaningPackages();
1465                } break;
1466                case POST_INSTALL: {
1467                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1468
1469                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1470                    final boolean didRestore = (msg.arg2 != 0);
1471                    mRunningInstalls.delete(msg.arg1);
1472
1473                    if (data != null) {
1474                        InstallArgs args = data.args;
1475                        PackageInstalledInfo parentRes = data.res;
1476
1477                        final boolean grantPermissions = (args.installFlags
1478                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1479                        final boolean killApp = (args.installFlags
1480                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1481                        final String[] grantedPermissions = args.installGrantPermissions;
1482
1483                        // Handle the parent package
1484                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1485                                grantedPermissions, didRestore, args.installerPackageName,
1486                                args.observer);
1487
1488                        // Handle the child packages
1489                        final int childCount = (parentRes.addedChildPackages != null)
1490                                ? parentRes.addedChildPackages.size() : 0;
1491                        for (int i = 0; i < childCount; i++) {
1492                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1493                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1494                                    grantedPermissions, false, args.installerPackageName,
1495                                    args.observer);
1496                        }
1497
1498                        // Log tracing if needed
1499                        if (args.traceMethod != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1501                                    args.traceCookie);
1502                        }
1503                    } else {
1504                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1505                    }
1506
1507                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1508                } break;
1509                case UPDATED_MEDIA_STATUS: {
1510                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1511                    boolean reportStatus = msg.arg1 == 1;
1512                    boolean doGc = msg.arg2 == 1;
1513                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1514                    if (doGc) {
1515                        // Force a gc to clear up stale containers.
1516                        Runtime.getRuntime().gc();
1517                    }
1518                    if (msg.obj != null) {
1519                        @SuppressWarnings("unchecked")
1520                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1521                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1522                        // Unload containers
1523                        unloadAllContainers(args);
1524                    }
1525                    if (reportStatus) {
1526                        try {
1527                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                    "Invoking StorageManagerService call back");
1529                            PackageHelper.getStorageManager().finishMediaUpdate();
1530                        } catch (RemoteException e) {
1531                            Log.e(TAG, "StorageManagerService not running?");
1532                        }
1533                    }
1534                } break;
1535                case WRITE_SETTINGS: {
1536                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1537                    synchronized (mPackages) {
1538                        removeMessages(WRITE_SETTINGS);
1539                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1540                        mSettings.writeLPr();
1541                        mDirtyUsers.clear();
1542                    }
1543                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1544                } break;
1545                case WRITE_PACKAGE_RESTRICTIONS: {
1546                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1547                    synchronized (mPackages) {
1548                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1549                        for (int userId : mDirtyUsers) {
1550                            mSettings.writePackageRestrictionsLPr(userId);
1551                        }
1552                        mDirtyUsers.clear();
1553                    }
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1555                } break;
1556                case WRITE_PACKAGE_LIST: {
1557                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1558                    synchronized (mPackages) {
1559                        removeMessages(WRITE_PACKAGE_LIST);
1560                        mSettings.writePackageListLPr(msg.arg1);
1561                    }
1562                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1563                } break;
1564                case CHECK_PENDING_VERIFICATION: {
1565                    final int verificationId = msg.arg1;
1566                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1567
1568                    if ((state != null) && !state.timeoutExtended()) {
1569                        final InstallArgs args = state.getInstallArgs();
1570                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1571
1572                        Slog.i(TAG, "Verification timed out for " + originUri);
1573                        mPendingVerification.remove(verificationId);
1574
1575                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1576
1577                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1578                            Slog.i(TAG, "Continuing with installation of " + originUri);
1579                            state.setVerifierResponse(Binder.getCallingUid(),
1580                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1581                            broadcastPackageVerified(verificationId, originUri,
1582                                    PackageManager.VERIFICATION_ALLOW,
1583                                    state.getInstallArgs().getUser());
1584                            try {
1585                                ret = args.copyApk(mContainerService, true);
1586                            } catch (RemoteException e) {
1587                                Slog.e(TAG, "Could not contact the ContainerService");
1588                            }
1589                        } else {
1590                            broadcastPackageVerified(verificationId, originUri,
1591                                    PackageManager.VERIFICATION_REJECT,
1592                                    state.getInstallArgs().getUser());
1593                        }
1594
1595                        Trace.asyncTraceEnd(
1596                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1597
1598                        processPendingInstall(args, ret);
1599                        mHandler.sendEmptyMessage(MCS_UNBIND);
1600                    }
1601                    break;
1602                }
1603                case PACKAGE_VERIFIED: {
1604                    final int verificationId = msg.arg1;
1605
1606                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1607                    if (state == null) {
1608                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1609                        break;
1610                    }
1611
1612                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1613
1614                    state.setVerifierResponse(response.callerUid, response.code);
1615
1616                    if (state.isVerificationComplete()) {
1617                        mPendingVerification.remove(verificationId);
1618
1619                        final InstallArgs args = state.getInstallArgs();
1620                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1621
1622                        int ret;
1623                        if (state.isInstallAllowed()) {
1624                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1625                            broadcastPackageVerified(verificationId, originUri,
1626                                    response.code, state.getInstallArgs().getUser());
1627                            try {
1628                                ret = args.copyApk(mContainerService, true);
1629                            } catch (RemoteException e) {
1630                                Slog.e(TAG, "Could not contact the ContainerService");
1631                            }
1632                        } else {
1633                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1634                        }
1635
1636                        Trace.asyncTraceEnd(
1637                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1638
1639                        processPendingInstall(args, ret);
1640                        mHandler.sendEmptyMessage(MCS_UNBIND);
1641                    }
1642
1643                    break;
1644                }
1645                case START_INTENT_FILTER_VERIFICATIONS: {
1646                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1647                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1648                            params.replacing, params.pkg);
1649                    break;
1650                }
1651                case INTENT_FILTER_VERIFIED: {
1652                    final int verificationId = msg.arg1;
1653
1654                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1655                            verificationId);
1656                    if (state == null) {
1657                        Slog.w(TAG, "Invalid IntentFilter verification token "
1658                                + verificationId + " received");
1659                        break;
1660                    }
1661
1662                    final int userId = state.getUserId();
1663
1664                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1665                            "Processing IntentFilter verification with token:"
1666                            + verificationId + " and userId:" + userId);
1667
1668                    final IntentFilterVerificationResponse response =
1669                            (IntentFilterVerificationResponse) msg.obj;
1670
1671                    state.setVerifierResponse(response.callerUid, response.code);
1672
1673                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1674                            "IntentFilter verification with token:" + verificationId
1675                            + " and userId:" + userId
1676                            + " is settings verifier response with response code:"
1677                            + response.code);
1678
1679                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1680                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1681                                + response.getFailedDomainsString());
1682                    }
1683
1684                    if (state.isVerificationComplete()) {
1685                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1686                    } else {
1687                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1688                                "IntentFilter verification with token:" + verificationId
1689                                + " was not said to be complete");
1690                    }
1691
1692                    break;
1693                }
1694                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1695                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1696                            mEphemeralResolverConnection,
1697                            (EphemeralRequest) msg.obj,
1698                            mEphemeralInstallerActivity,
1699                            mHandler);
1700                }
1701            }
1702        }
1703    }
1704
1705    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1706            boolean killApp, String[] grantedPermissions,
1707            boolean launchedForRestore, String installerPackage,
1708            IPackageInstallObserver2 installObserver) {
1709        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1710            // Send the removed broadcasts
1711            if (res.removedInfo != null) {
1712                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1713            }
1714
1715            // Now that we successfully installed the package, grant runtime
1716            // permissions if requested before broadcasting the install. Also
1717            // for legacy apps in permission review mode we clear the permission
1718            // review flag which is used to emulate runtime permissions for
1719            // legacy apps.
1720            if (grantPermissions) {
1721                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1722            }
1723
1724            final boolean update = res.removedInfo != null
1725                    && res.removedInfo.removedPackage != null;
1726
1727            // If this is the first time we have child packages for a disabled privileged
1728            // app that had no children, we grant requested runtime permissions to the new
1729            // children if the parent on the system image had them already granted.
1730            if (res.pkg.parentPackage != null) {
1731                synchronized (mPackages) {
1732                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1733                }
1734            }
1735
1736            synchronized (mPackages) {
1737                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1738            }
1739
1740            final String packageName = res.pkg.applicationInfo.packageName;
1741
1742            // Determine the set of users who are adding this package for
1743            // the first time vs. those who are seeing an update.
1744            int[] firstUsers = EMPTY_INT_ARRAY;
1745            int[] updateUsers = EMPTY_INT_ARRAY;
1746            if (res.origUsers == null || res.origUsers.length == 0) {
1747                firstUsers = res.newUsers;
1748            } else {
1749                for (int newUser : res.newUsers) {
1750                    boolean isNew = true;
1751                    for (int origUser : res.origUsers) {
1752                        if (origUser == newUser) {
1753                            isNew = false;
1754                            break;
1755                        }
1756                    }
1757                    if (isNew) {
1758                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1759                    } else {
1760                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1761                    }
1762                }
1763            }
1764
1765            // Send installed broadcasts if the install/update is not ephemeral
1766            if (!isEphemeral(res.pkg)) {
1767                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1768
1769                // Send added for users that see the package for the first time
1770                // sendPackageAddedForNewUsers also deals with system apps
1771                int appId = UserHandle.getAppId(res.uid);
1772                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1773                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1774
1775                // Send added for users that don't see the package for the first time
1776                Bundle extras = new Bundle(1);
1777                extras.putInt(Intent.EXTRA_UID, res.uid);
1778                if (update) {
1779                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1780                }
1781                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1782                        extras, 0 /*flags*/, null /*targetPackage*/,
1783                        null /*finishedReceiver*/, updateUsers);
1784
1785                // Send replaced for users that don't see the package for the first time
1786                if (update) {
1787                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1788                            packageName, extras, 0 /*flags*/,
1789                            null /*targetPackage*/, null /*finishedReceiver*/,
1790                            updateUsers);
1791                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1792                            null /*package*/, null /*extras*/, 0 /*flags*/,
1793                            packageName /*targetPackage*/,
1794                            null /*finishedReceiver*/, updateUsers);
1795                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1796                    // First-install and we did a restore, so we're responsible for the
1797                    // first-launch broadcast.
1798                    if (DEBUG_BACKUP) {
1799                        Slog.i(TAG, "Post-restore of " + packageName
1800                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1801                    }
1802                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1803                }
1804
1805                // Send broadcast package appeared if forward locked/external for all users
1806                // treat asec-hosted packages like removable media on upgrade
1807                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1808                    if (DEBUG_INSTALL) {
1809                        Slog.i(TAG, "upgrading pkg " + res.pkg
1810                                + " is ASEC-hosted -> AVAILABLE");
1811                    }
1812                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1813                    ArrayList<String> pkgList = new ArrayList<>(1);
1814                    pkgList.add(packageName);
1815                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1816                }
1817            }
1818
1819            // Work that needs to happen on first install within each user
1820            if (firstUsers != null && firstUsers.length > 0) {
1821                synchronized (mPackages) {
1822                    for (int userId : firstUsers) {
1823                        // If this app is a browser and it's newly-installed for some
1824                        // users, clear any default-browser state in those users. The
1825                        // app's nature doesn't depend on the user, so we can just check
1826                        // its browser nature in any user and generalize.
1827                        if (packageIsBrowser(packageName, userId)) {
1828                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1829                        }
1830
1831                        // We may also need to apply pending (restored) runtime
1832                        // permission grants within these users.
1833                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1834                    }
1835                }
1836            }
1837
1838            // Log current value of "unknown sources" setting
1839            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1840                    getUnknownSourcesSettings());
1841
1842            // Force a gc to clear up things
1843            Runtime.getRuntime().gc();
1844
1845            // Remove the replaced package's older resources safely now
1846            // We delete after a gc for applications  on sdcard.
1847            if (res.removedInfo != null && res.removedInfo.args != null) {
1848                synchronized (mInstallLock) {
1849                    res.removedInfo.args.doPostDeleteLI(true);
1850                }
1851            }
1852        }
1853
1854        // If someone is watching installs - notify them
1855        if (installObserver != null) {
1856            try {
1857                Bundle extras = extrasForInstallResult(res);
1858                installObserver.onPackageInstalled(res.name, res.returnCode,
1859                        res.returnMsg, extras);
1860            } catch (RemoteException e) {
1861                Slog.i(TAG, "Observer no longer exists.");
1862            }
1863        }
1864    }
1865
1866    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1867            PackageParser.Package pkg) {
1868        if (pkg.parentPackage == null) {
1869            return;
1870        }
1871        if (pkg.requestedPermissions == null) {
1872            return;
1873        }
1874        final PackageSetting disabledSysParentPs = mSettings
1875                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1876        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1877                || !disabledSysParentPs.isPrivileged()
1878                || (disabledSysParentPs.childPackageNames != null
1879                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1880            return;
1881        }
1882        final int[] allUserIds = sUserManager.getUserIds();
1883        final int permCount = pkg.requestedPermissions.size();
1884        for (int i = 0; i < permCount; i++) {
1885            String permission = pkg.requestedPermissions.get(i);
1886            BasePermission bp = mSettings.mPermissions.get(permission);
1887            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1888                continue;
1889            }
1890            for (int userId : allUserIds) {
1891                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1892                        permission, userId)) {
1893                    grantRuntimePermission(pkg.packageName, permission, userId);
1894                }
1895            }
1896        }
1897    }
1898
1899    private StorageEventListener mStorageListener = new StorageEventListener() {
1900        @Override
1901        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1902            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1903                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1904                    final String volumeUuid = vol.getFsUuid();
1905
1906                    // Clean up any users or apps that were removed or recreated
1907                    // while this volume was missing
1908                    reconcileUsers(volumeUuid);
1909                    reconcileApps(volumeUuid);
1910
1911                    // Clean up any install sessions that expired or were
1912                    // cancelled while this volume was missing
1913                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1914
1915                    loadPrivatePackages(vol);
1916
1917                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1918                    unloadPrivatePackages(vol);
1919                }
1920            }
1921
1922            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1923                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1924                    updateExternalMediaStatus(true, false);
1925                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1926                    updateExternalMediaStatus(false, false);
1927                }
1928            }
1929        }
1930
1931        @Override
1932        public void onVolumeForgotten(String fsUuid) {
1933            if (TextUtils.isEmpty(fsUuid)) {
1934                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1935                return;
1936            }
1937
1938            // Remove any apps installed on the forgotten volume
1939            synchronized (mPackages) {
1940                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1941                for (PackageSetting ps : packages) {
1942                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1943                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1944                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1945
1946                    // Try very hard to release any references to this package
1947                    // so we don't risk the system server being killed due to
1948                    // open FDs
1949                    AttributeCache.instance().removePackage(ps.name);
1950                }
1951
1952                mSettings.onVolumeForgotten(fsUuid);
1953                mSettings.writeLPr();
1954            }
1955        }
1956    };
1957
1958    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1959            String[] grantedPermissions) {
1960        for (int userId : userIds) {
1961            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1962        }
1963    }
1964
1965    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1966            String[] grantedPermissions) {
1967        SettingBase sb = (SettingBase) pkg.mExtras;
1968        if (sb == null) {
1969            return;
1970        }
1971
1972        PermissionsState permissionsState = sb.getPermissionsState();
1973
1974        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1975                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1976
1977        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1978                >= Build.VERSION_CODES.M;
1979
1980        for (String permission : pkg.requestedPermissions) {
1981            final BasePermission bp;
1982            synchronized (mPackages) {
1983                bp = mSettings.mPermissions.get(permission);
1984            }
1985            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1986                    && (grantedPermissions == null
1987                           || ArrayUtils.contains(grantedPermissions, permission))) {
1988                final int flags = permissionsState.getPermissionFlags(permission, userId);
1989                if (supportsRuntimePermissions) {
1990                    // Installer cannot change immutable permissions.
1991                    if ((flags & immutableFlags) == 0) {
1992                        grantRuntimePermission(pkg.packageName, permission, userId);
1993                    }
1994                } else if (mPermissionReviewRequired) {
1995                    // In permission review mode we clear the review flag when we
1996                    // are asked to install the app with all permissions granted.
1997                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
1998                        updatePermissionFlags(permission, pkg.packageName,
1999                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2000                    }
2001                }
2002            }
2003        }
2004    }
2005
2006    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2007        Bundle extras = null;
2008        switch (res.returnCode) {
2009            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2010                extras = new Bundle();
2011                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2012                        res.origPermission);
2013                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2014                        res.origPackage);
2015                break;
2016            }
2017            case PackageManager.INSTALL_SUCCEEDED: {
2018                extras = new Bundle();
2019                extras.putBoolean(Intent.EXTRA_REPLACING,
2020                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2021                break;
2022            }
2023        }
2024        return extras;
2025    }
2026
2027    void scheduleWriteSettingsLocked() {
2028        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2029            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2030        }
2031    }
2032
2033    void scheduleWritePackageListLocked(int userId) {
2034        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2035            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2036            msg.arg1 = userId;
2037            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2038        }
2039    }
2040
2041    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2042        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2043        scheduleWritePackageRestrictionsLocked(userId);
2044    }
2045
2046    void scheduleWritePackageRestrictionsLocked(int userId) {
2047        final int[] userIds = (userId == UserHandle.USER_ALL)
2048                ? sUserManager.getUserIds() : new int[]{userId};
2049        for (int nextUserId : userIds) {
2050            if (!sUserManager.exists(nextUserId)) return;
2051            mDirtyUsers.add(nextUserId);
2052            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2053                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2054            }
2055        }
2056    }
2057
2058    public static PackageManagerService main(Context context, Installer installer,
2059            boolean factoryTest, boolean onlyCore) {
2060        // Self-check for initial settings.
2061        PackageManagerServiceCompilerMapping.checkProperties();
2062
2063        PackageManagerService m = new PackageManagerService(context, installer,
2064                factoryTest, onlyCore);
2065        m.enableSystemUserPackages();
2066        ServiceManager.addService("package", m);
2067        return m;
2068    }
2069
2070    private void enableSystemUserPackages() {
2071        if (!UserManager.isSplitSystemUser()) {
2072            return;
2073        }
2074        // For system user, enable apps based on the following conditions:
2075        // - app is whitelisted or belong to one of these groups:
2076        //   -- system app which has no launcher icons
2077        //   -- system app which has INTERACT_ACROSS_USERS permission
2078        //   -- system IME app
2079        // - app is not in the blacklist
2080        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2081        Set<String> enableApps = new ArraySet<>();
2082        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2083                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2084                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2085        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2086        enableApps.addAll(wlApps);
2087        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2088                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2089        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2090        enableApps.removeAll(blApps);
2091        Log.i(TAG, "Applications installed for system user: " + enableApps);
2092        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2093                UserHandle.SYSTEM);
2094        final int allAppsSize = allAps.size();
2095        synchronized (mPackages) {
2096            for (int i = 0; i < allAppsSize; i++) {
2097                String pName = allAps.get(i);
2098                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2099                // Should not happen, but we shouldn't be failing if it does
2100                if (pkgSetting == null) {
2101                    continue;
2102                }
2103                boolean install = enableApps.contains(pName);
2104                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2105                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2106                            + " for system user");
2107                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2108                }
2109            }
2110        }
2111    }
2112
2113    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2114        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2115                Context.DISPLAY_SERVICE);
2116        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2117    }
2118
2119    /**
2120     * Requests that files preopted on a secondary system partition be copied to the data partition
2121     * if possible.  Note that the actual copying of the files is accomplished by init for security
2122     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2123     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2124     */
2125    private static void requestCopyPreoptedFiles() {
2126        final int WAIT_TIME_MS = 100;
2127        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2128        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2129            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2130            // We will wait for up to 100 seconds.
2131            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2132            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2133                try {
2134                    Thread.sleep(WAIT_TIME_MS);
2135                } catch (InterruptedException e) {
2136                    // Do nothing
2137                }
2138                if (SystemClock.uptimeMillis() > timeEnd) {
2139                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2140                    Slog.wtf(TAG, "cppreopt did not finish!");
2141                    break;
2142                }
2143            }
2144        }
2145    }
2146
2147    public PackageManagerService(Context context, Installer installer,
2148            boolean factoryTest, boolean onlyCore) {
2149        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2150        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2151                SystemClock.uptimeMillis());
2152
2153        if (mSdkVersion <= 0) {
2154            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2155        }
2156
2157        mContext = context;
2158
2159        mPermissionReviewRequired = context.getResources().getBoolean(
2160                R.bool.config_permissionReviewRequired);
2161
2162        mFactoryTest = factoryTest;
2163        mOnlyCore = onlyCore;
2164        mMetrics = new DisplayMetrics();
2165        mSettings = new Settings(mPackages);
2166        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2167                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2168        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2169                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2170        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2171                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2172        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2173                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2174        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2175                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2176        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2177                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2178
2179        String separateProcesses = SystemProperties.get("debug.separate_processes");
2180        if (separateProcesses != null && separateProcesses.length() > 0) {
2181            if ("*".equals(separateProcesses)) {
2182                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2183                mSeparateProcesses = null;
2184                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2185            } else {
2186                mDefParseFlags = 0;
2187                mSeparateProcesses = separateProcesses.split(",");
2188                Slog.w(TAG, "Running with debug.separate_processes: "
2189                        + separateProcesses);
2190            }
2191        } else {
2192            mDefParseFlags = 0;
2193            mSeparateProcesses = null;
2194        }
2195
2196        mInstaller = installer;
2197        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2198                "*dexopt*");
2199        mDexManager = new DexManager();
2200        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2201
2202        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2203                FgThread.get().getLooper());
2204
2205        getDefaultDisplayMetrics(context, mMetrics);
2206
2207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2208        SystemConfig systemConfig = SystemConfig.getInstance();
2209        mGlobalGids = systemConfig.getGlobalGids();
2210        mSystemPermissions = systemConfig.getSystemPermissions();
2211        mAvailableFeatures = systemConfig.getAvailableFeatures();
2212        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2213
2214        mProtectedPackages = new ProtectedPackages(mContext);
2215
2216        synchronized (mInstallLock) {
2217        // writer
2218        synchronized (mPackages) {
2219            mHandlerThread = new ServiceThread(TAG,
2220                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2221            mHandlerThread.start();
2222            mHandler = new PackageHandler(mHandlerThread.getLooper());
2223            mProcessLoggingHandler = new ProcessLoggingHandler();
2224            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2225
2226            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2227
2228            File dataDir = Environment.getDataDirectory();
2229            mAppInstallDir = new File(dataDir, "app");
2230            mAppLib32InstallDir = new File(dataDir, "app-lib");
2231            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2232            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2233            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2234
2235            sUserManager = new UserManagerService(context, this, mPackages);
2236
2237            // Propagate permission configuration in to package manager.
2238            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2239                    = systemConfig.getPermissions();
2240            for (int i=0; i<permConfig.size(); i++) {
2241                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2242                BasePermission bp = mSettings.mPermissions.get(perm.name);
2243                if (bp == null) {
2244                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2245                    mSettings.mPermissions.put(perm.name, bp);
2246                }
2247                if (perm.gids != null) {
2248                    bp.setGids(perm.gids, perm.perUser);
2249                }
2250            }
2251
2252            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2253            for (int i=0; i<libConfig.size(); i++) {
2254                mSharedLibraries.put(libConfig.keyAt(i),
2255                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2256            }
2257
2258            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2259
2260            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2261            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2262            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2263
2264            // Clean up orphaned packages for which the code path doesn't exist
2265            // and they are an update to a system app - caused by bug/32321269
2266            final int packageSettingCount = mSettings.mPackages.size();
2267            for (int i = packageSettingCount - 1; i >= 0; i--) {
2268                PackageSetting ps = mSettings.mPackages.valueAt(i);
2269                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2270                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2271                    mSettings.mPackages.removeAt(i);
2272                    mSettings.enableSystemPackageLPw(ps.name);
2273                }
2274            }
2275
2276            if (mFirstBoot) {
2277                requestCopyPreoptedFiles();
2278            }
2279
2280            String customResolverActivity = Resources.getSystem().getString(
2281                    R.string.config_customResolverActivity);
2282            if (TextUtils.isEmpty(customResolverActivity)) {
2283                customResolverActivity = null;
2284            } else {
2285                mCustomResolverComponentName = ComponentName.unflattenFromString(
2286                        customResolverActivity);
2287            }
2288
2289            long startTime = SystemClock.uptimeMillis();
2290
2291            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2292                    startTime);
2293
2294            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2295            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2296
2297            if (bootClassPath == null) {
2298                Slog.w(TAG, "No BOOTCLASSPATH found!");
2299            }
2300
2301            if (systemServerClassPath == null) {
2302                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2303            }
2304
2305            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2306            final String[] dexCodeInstructionSets =
2307                    getDexCodeInstructionSets(
2308                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2309
2310            /**
2311             * Ensure all external libraries have had dexopt run on them.
2312             */
2313            if (mSharedLibraries.size() > 0) {
2314                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2315                // NOTE: For now, we're compiling these system "shared libraries"
2316                // (and framework jars) into all available architectures. It's possible
2317                // to compile them only when we come across an app that uses them (there's
2318                // already logic for that in scanPackageLI) but that adds some complexity.
2319                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2320                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2321                        final String lib = libEntry.path;
2322                        if (lib == null) {
2323                            continue;
2324                        }
2325
2326                        try {
2327                            // Shared libraries do not have profiles so we perform a full
2328                            // AOT compilation (if needed).
2329                            int dexoptNeeded = DexFile.getDexOptNeeded(
2330                                    lib, dexCodeInstructionSet,
2331                                    getCompilerFilterForReason(REASON_SHARED_APK),
2332                                    false /* newProfile */);
2333                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2334                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2335                                        dexCodeInstructionSet, dexoptNeeded, null,
2336                                        DEXOPT_PUBLIC,
2337                                        getCompilerFilterForReason(REASON_SHARED_APK),
2338                                        StorageManager.UUID_PRIVATE_INTERNAL,
2339                                        SKIP_SHARED_LIBRARY_CHECK);
2340                            }
2341                        } catch (FileNotFoundException e) {
2342                            Slog.w(TAG, "Library not found: " + lib);
2343                        } catch (IOException | InstallerException e) {
2344                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2345                                    + e.getMessage());
2346                        }
2347                    }
2348                }
2349                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2350            }
2351
2352            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2353
2354            final VersionInfo ver = mSettings.getInternalVersion();
2355            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2356
2357            // when upgrading from pre-M, promote system app permissions from install to runtime
2358            mPromoteSystemApps =
2359                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2360
2361            // When upgrading from pre-N, we need to handle package extraction like first boot,
2362            // as there is no profiling data available.
2363            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2364
2365            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2366
2367            // save off the names of pre-existing system packages prior to scanning; we don't
2368            // want to automatically grant runtime permissions for new system apps
2369            if (mPromoteSystemApps) {
2370                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2371                while (pkgSettingIter.hasNext()) {
2372                    PackageSetting ps = pkgSettingIter.next();
2373                    if (isSystemApp(ps)) {
2374                        mExistingSystemPackages.add(ps.name);
2375                    }
2376                }
2377            }
2378
2379            mCacheDir = preparePackageParserCache(mIsUpgrade);
2380
2381            // Set flag to monitor and not change apk file paths when
2382            // scanning install directories.
2383            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2384
2385            if (mIsUpgrade || mFirstBoot) {
2386                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2387            }
2388
2389            // Collect vendor overlay packages. (Do this before scanning any apps.)
2390            // For security and version matching reason, only consider
2391            // overlay packages if they reside in the right directory.
2392            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2393            if (overlayThemeDir.isEmpty()) {
2394                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2395            }
2396            if (!overlayThemeDir.isEmpty()) {
2397                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2398                        | PackageParser.PARSE_IS_SYSTEM
2399                        | PackageParser.PARSE_IS_SYSTEM_DIR
2400                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2401            }
2402            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2403                    | PackageParser.PARSE_IS_SYSTEM
2404                    | PackageParser.PARSE_IS_SYSTEM_DIR
2405                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2406
2407            // Find base frameworks (resource packages without code).
2408            scanDirTracedLI(frameworkDir, mDefParseFlags
2409                    | PackageParser.PARSE_IS_SYSTEM
2410                    | PackageParser.PARSE_IS_SYSTEM_DIR
2411                    | PackageParser.PARSE_IS_PRIVILEGED,
2412                    scanFlags | SCAN_NO_DEX, 0);
2413
2414            // Collected privileged system packages.
2415            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2416            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2417                    | PackageParser.PARSE_IS_SYSTEM
2418                    | PackageParser.PARSE_IS_SYSTEM_DIR
2419                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2420
2421            // Collect ordinary system packages.
2422            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2423            scanDirTracedLI(systemAppDir, mDefParseFlags
2424                    | PackageParser.PARSE_IS_SYSTEM
2425                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2426
2427            // Collect all vendor packages.
2428            File vendorAppDir = new File("/vendor/app");
2429            try {
2430                vendorAppDir = vendorAppDir.getCanonicalFile();
2431            } catch (IOException e) {
2432                // failed to look up canonical path, continue with original one
2433            }
2434            scanDirTracedLI(vendorAppDir, mDefParseFlags
2435                    | PackageParser.PARSE_IS_SYSTEM
2436                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2437
2438            // Collect all OEM packages.
2439            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2440            scanDirTracedLI(oemAppDir, mDefParseFlags
2441                    | PackageParser.PARSE_IS_SYSTEM
2442                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2443
2444            // Prune any system packages that no longer exist.
2445            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2446            if (!mOnlyCore) {
2447                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2448                while (psit.hasNext()) {
2449                    PackageSetting ps = psit.next();
2450
2451                    /*
2452                     * If this is not a system app, it can't be a
2453                     * disable system app.
2454                     */
2455                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2456                        continue;
2457                    }
2458
2459                    /*
2460                     * If the package is scanned, it's not erased.
2461                     */
2462                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2463                    if (scannedPkg != null) {
2464                        /*
2465                         * If the system app is both scanned and in the
2466                         * disabled packages list, then it must have been
2467                         * added via OTA. Remove it from the currently
2468                         * scanned package so the previously user-installed
2469                         * application can be scanned.
2470                         */
2471                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2472                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2473                                    + ps.name + "; removing system app.  Last known codePath="
2474                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2475                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2476                                    + scannedPkg.mVersionCode);
2477                            removePackageLI(scannedPkg, true);
2478                            mExpectingBetter.put(ps.name, ps.codePath);
2479                        }
2480
2481                        continue;
2482                    }
2483
2484                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2485                        psit.remove();
2486                        logCriticalInfo(Log.WARN, "System package " + ps.name
2487                                + " no longer exists; it's data will be wiped");
2488                        // Actual deletion of code and data will be handled by later
2489                        // reconciliation step
2490                    } else {
2491                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2492                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2493                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2494                        }
2495                    }
2496                }
2497            }
2498
2499            //look for any incomplete package installations
2500            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2501            for (int i = 0; i < deletePkgsList.size(); i++) {
2502                // Actual deletion of code and data will be handled by later
2503                // reconciliation step
2504                final String packageName = deletePkgsList.get(i).name;
2505                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2506                synchronized (mPackages) {
2507                    mSettings.removePackageLPw(packageName);
2508                }
2509            }
2510
2511            //delete tmp files
2512            deleteTempPackageFiles();
2513
2514            // Remove any shared userIDs that have no associated packages
2515            mSettings.pruneSharedUsersLPw();
2516
2517            if (!mOnlyCore) {
2518                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2519                        SystemClock.uptimeMillis());
2520                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2521
2522                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2523                        | PackageParser.PARSE_FORWARD_LOCK,
2524                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2525
2526                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2527                        | PackageParser.PARSE_IS_EPHEMERAL,
2528                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2529
2530                /**
2531                 * Remove disable package settings for any updated system
2532                 * apps that were removed via an OTA. If they're not a
2533                 * previously-updated app, remove them completely.
2534                 * Otherwise, just revoke their system-level permissions.
2535                 */
2536                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2537                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2538                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2539
2540                    String msg;
2541                    if (deletedPkg == null) {
2542                        msg = "Updated system package " + deletedAppName
2543                                + " no longer exists; it's data will be wiped";
2544                        // Actual deletion of code and data will be handled by later
2545                        // reconciliation step
2546                    } else {
2547                        msg = "Updated system app + " + deletedAppName
2548                                + " no longer present; removing system privileges for "
2549                                + deletedAppName;
2550
2551                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2552
2553                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2554                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2555                    }
2556                    logCriticalInfo(Log.WARN, msg);
2557                }
2558
2559                /**
2560                 * Make sure all system apps that we expected to appear on
2561                 * the userdata partition actually showed up. If they never
2562                 * appeared, crawl back and revive the system version.
2563                 */
2564                for (int i = 0; i < mExpectingBetter.size(); i++) {
2565                    final String packageName = mExpectingBetter.keyAt(i);
2566                    if (!mPackages.containsKey(packageName)) {
2567                        final File scanFile = mExpectingBetter.valueAt(i);
2568
2569                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2570                                + " but never showed up; reverting to system");
2571
2572                        int reparseFlags = mDefParseFlags;
2573                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2574                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2575                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2576                                    | PackageParser.PARSE_IS_PRIVILEGED;
2577                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2578                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2579                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2580                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2581                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2582                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2583                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2584                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2585                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2586                        } else {
2587                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2588                            continue;
2589                        }
2590
2591                        mSettings.enableSystemPackageLPw(packageName);
2592
2593                        try {
2594                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2595                        } catch (PackageManagerException e) {
2596                            Slog.e(TAG, "Failed to parse original system package: "
2597                                    + e.getMessage());
2598                        }
2599                    }
2600                }
2601            }
2602            mExpectingBetter.clear();
2603
2604            // Resolve the storage manager.
2605            mStorageManagerPackage = getStorageManagerPackageName();
2606
2607            // Resolve protected action filters. Only the setup wizard is allowed to
2608            // have a high priority filter for these actions.
2609            mSetupWizardPackage = getSetupWizardPackageName();
2610            if (mProtectedFilters.size() > 0) {
2611                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2612                    Slog.i(TAG, "No setup wizard;"
2613                        + " All protected intents capped to priority 0");
2614                }
2615                for (ActivityIntentInfo filter : mProtectedFilters) {
2616                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2617                        if (DEBUG_FILTERS) {
2618                            Slog.i(TAG, "Found setup wizard;"
2619                                + " allow priority " + filter.getPriority() + ";"
2620                                + " package: " + filter.activity.info.packageName
2621                                + " activity: " + filter.activity.className
2622                                + " priority: " + filter.getPriority());
2623                        }
2624                        // skip setup wizard; allow it to keep the high priority filter
2625                        continue;
2626                    }
2627                    Slog.w(TAG, "Protected action; cap priority to 0;"
2628                            + " package: " + filter.activity.info.packageName
2629                            + " activity: " + filter.activity.className
2630                            + " origPrio: " + filter.getPriority());
2631                    filter.setPriority(0);
2632                }
2633            }
2634            mDeferProtectedFilters = false;
2635            mProtectedFilters.clear();
2636
2637            // Now that we know all of the shared libraries, update all clients to have
2638            // the correct library paths.
2639            updateAllSharedLibrariesLPw();
2640
2641            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2642                // NOTE: We ignore potential failures here during a system scan (like
2643                // the rest of the commands above) because there's precious little we
2644                // can do about it. A settings error is reported, though.
2645                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2646            }
2647
2648            // Now that we know all the packages we are keeping,
2649            // read and update their last usage times.
2650            mPackageUsage.read(mPackages);
2651            mCompilerStats.read();
2652
2653            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2654                    SystemClock.uptimeMillis());
2655            Slog.i(TAG, "Time to scan packages: "
2656                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2657                    + " seconds");
2658
2659            // If the platform SDK has changed since the last time we booted,
2660            // we need to re-grant app permission to catch any new ones that
2661            // appear.  This is really a hack, and means that apps can in some
2662            // cases get permissions that the user didn't initially explicitly
2663            // allow...  it would be nice to have some better way to handle
2664            // this situation.
2665            int updateFlags = UPDATE_PERMISSIONS_ALL;
2666            if (ver.sdkVersion != mSdkVersion) {
2667                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2668                        + mSdkVersion + "; regranting permissions for internal storage");
2669                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2670            }
2671            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2672            ver.sdkVersion = mSdkVersion;
2673
2674            // If this is the first boot or an update from pre-M, and it is a normal
2675            // boot, then we need to initialize the default preferred apps across
2676            // all defined users.
2677            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2678                for (UserInfo user : sUserManager.getUsers(true)) {
2679                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2680                    applyFactoryDefaultBrowserLPw(user.id);
2681                    primeDomainVerificationsLPw(user.id);
2682                }
2683            }
2684
2685            // Prepare storage for system user really early during boot,
2686            // since core system apps like SettingsProvider and SystemUI
2687            // can't wait for user to start
2688            final int storageFlags;
2689            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2690                storageFlags = StorageManager.FLAG_STORAGE_DE;
2691            } else {
2692                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2693            }
2694            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2695                    storageFlags, true /* migrateAppData */);
2696
2697            // If this is first boot after an OTA, and a normal boot, then
2698            // we need to clear code cache directories.
2699            // Note that we do *not* clear the application profiles. These remain valid
2700            // across OTAs and are used to drive profile verification (post OTA) and
2701            // profile compilation (without waiting to collect a fresh set of profiles).
2702            if (mIsUpgrade && !onlyCore) {
2703                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2704                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2705                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2706                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2707                        // No apps are running this early, so no need to freeze
2708                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2709                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2710                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2711                    }
2712                }
2713                ver.fingerprint = Build.FINGERPRINT;
2714            }
2715
2716            checkDefaultBrowser();
2717
2718            // clear only after permissions and other defaults have been updated
2719            mExistingSystemPackages.clear();
2720            mPromoteSystemApps = false;
2721
2722            // All the changes are done during package scanning.
2723            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2724
2725            // can downgrade to reader
2726            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2727            mSettings.writeLPr();
2728            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2729
2730            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2731            // early on (before the package manager declares itself as early) because other
2732            // components in the system server might ask for package contexts for these apps.
2733            //
2734            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2735            // (i.e, that the data partition is unavailable).
2736            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2737                long start = System.nanoTime();
2738                List<PackageParser.Package> coreApps = new ArrayList<>();
2739                for (PackageParser.Package pkg : mPackages.values()) {
2740                    if (pkg.coreApp) {
2741                        coreApps.add(pkg);
2742                    }
2743                }
2744
2745                int[] stats = performDexOptUpgrade(coreApps, false,
2746                        getCompilerFilterForReason(REASON_CORE_APP));
2747
2748                final int elapsedTimeSeconds =
2749                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2750                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2751
2752                if (DEBUG_DEXOPT) {
2753                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2754                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2755                }
2756
2757
2758                // TODO: Should we log these stats to tron too ?
2759                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2760                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2761                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2762                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2763            }
2764
2765            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2766                    SystemClock.uptimeMillis());
2767
2768            if (!mOnlyCore) {
2769                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2770                mRequiredInstallerPackage = getRequiredInstallerLPr();
2771                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2772                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2773                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2774                        mIntentFilterVerifierComponent);
2775                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2776                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2777                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2778                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2779            } else {
2780                mRequiredVerifierPackage = null;
2781                mRequiredInstallerPackage = null;
2782                mRequiredUninstallerPackage = null;
2783                mIntentFilterVerifierComponent = null;
2784                mIntentFilterVerifier = null;
2785                mServicesSystemSharedLibraryPackageName = null;
2786                mSharedSystemSharedLibraryPackageName = null;
2787            }
2788
2789            mInstallerService = new PackageInstallerService(context, this);
2790
2791            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2792            if (ephemeralResolverComponent != null) {
2793                if (DEBUG_EPHEMERAL) {
2794                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2795                }
2796                mEphemeralResolverConnection =
2797                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2798            } else {
2799                mEphemeralResolverConnection = null;
2800            }
2801            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2802            if (mEphemeralInstallerComponent != null) {
2803                if (DEBUG_EPHEMERAL) {
2804                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2805                }
2806                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2807            }
2808
2809            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2810
2811            // Read and update the usage of dex files.
2812            // Do this at the end of PM init so that all the packages have their
2813            // data directory reconciled.
2814            // At this point we know the code paths of the packages, so we can validate
2815            // the disk file and build the internal cache.
2816            // The usage file is expected to be small so loading and verifying it
2817            // should take a fairly small time compare to the other activities (e.g. package
2818            // scanning).
2819            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2820            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2821            for (int userId : currentUserIds) {
2822                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2823            }
2824            mDexManager.load(userPackages);
2825        } // synchronized (mPackages)
2826        } // synchronized (mInstallLock)
2827
2828        // Now after opening every single application zip, make sure they
2829        // are all flushed.  Not really needed, but keeps things nice and
2830        // tidy.
2831        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2832        Runtime.getRuntime().gc();
2833        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2834
2835        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2836        FallbackCategoryProvider.loadFallbacks();
2837        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2838
2839        // The initial scanning above does many calls into installd while
2840        // holding the mPackages lock, but we're mostly interested in yelling
2841        // once we have a booted system.
2842        mInstaller.setWarnIfHeld(mPackages);
2843
2844        // Expose private service for system components to use.
2845        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2846        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2847    }
2848
2849    private static File preparePackageParserCache(boolean isUpgrade) {
2850        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2851            return null;
2852        }
2853
2854        // Disable package parsing on eng builds to allow for faster incremental development.
2855        if ("eng".equals(Build.TYPE)) {
2856            return null;
2857        }
2858
2859        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2860            Slog.i(TAG, "Disabling package parser cache due to system property.");
2861            return null;
2862        }
2863
2864        // The base directory for the package parser cache lives under /data/system/.
2865        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2866                "package_cache");
2867        if (cacheBaseDir == null) {
2868            return null;
2869        }
2870
2871        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2872        // This also serves to "GC" unused entries when the package cache version changes (which
2873        // can only happen during upgrades).
2874        if (isUpgrade) {
2875            FileUtils.deleteContents(cacheBaseDir);
2876        }
2877
2878
2879        // Return the versioned package cache directory. This is something like
2880        // "/data/system/package_cache/1"
2881        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2882
2883        // The following is a workaround to aid development on non-numbered userdebug
2884        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2885        // the system partition is newer.
2886        //
2887        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2888        // that starts with "eng." to signify that this is an engineering build and not
2889        // destined for release.
2890        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2891            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2892
2893            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2894            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2895            // in general and should not be used for production changes. In this specific case,
2896            // we know that they will work.
2897            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2898            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2899                FileUtils.deleteContents(cacheBaseDir);
2900                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2901            }
2902        }
2903
2904        return cacheDir;
2905    }
2906
2907    @Override
2908    public boolean isFirstBoot() {
2909        return mFirstBoot;
2910    }
2911
2912    @Override
2913    public boolean isOnlyCoreApps() {
2914        return mOnlyCore;
2915    }
2916
2917    @Override
2918    public boolean isUpgrade() {
2919        return mIsUpgrade;
2920    }
2921
2922    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2923        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2924
2925        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2926                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2927                UserHandle.USER_SYSTEM);
2928        if (matches.size() == 1) {
2929            return matches.get(0).getComponentInfo().packageName;
2930        } else if (matches.size() == 0) {
2931            Log.e(TAG, "There should probably be a verifier, but, none were found");
2932            return null;
2933        }
2934        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2935    }
2936
2937    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2938        synchronized (mPackages) {
2939            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2940            if (libraryEntry == null) {
2941                throw new IllegalStateException("Missing required shared library:" + libraryName);
2942            }
2943            return libraryEntry.apk;
2944        }
2945    }
2946
2947    private @NonNull String getRequiredInstallerLPr() {
2948        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2949        intent.addCategory(Intent.CATEGORY_DEFAULT);
2950        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2951
2952        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2953                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2954                UserHandle.USER_SYSTEM);
2955        if (matches.size() == 1) {
2956            ResolveInfo resolveInfo = matches.get(0);
2957            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2958                throw new RuntimeException("The installer must be a privileged app");
2959            }
2960            return matches.get(0).getComponentInfo().packageName;
2961        } else {
2962            throw new RuntimeException("There must be exactly one installer; found " + matches);
2963        }
2964    }
2965
2966    private @NonNull String getRequiredUninstallerLPr() {
2967        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2968        intent.addCategory(Intent.CATEGORY_DEFAULT);
2969        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2970
2971        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2972                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2973                UserHandle.USER_SYSTEM);
2974        if (resolveInfo == null ||
2975                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2976            throw new RuntimeException("There must be exactly one uninstaller; found "
2977                    + resolveInfo);
2978        }
2979        return resolveInfo.getComponentInfo().packageName;
2980    }
2981
2982    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2983        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2984
2985        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2986                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2987                UserHandle.USER_SYSTEM);
2988        ResolveInfo best = null;
2989        final int N = matches.size();
2990        for (int i = 0; i < N; i++) {
2991            final ResolveInfo cur = matches.get(i);
2992            final String packageName = cur.getComponentInfo().packageName;
2993            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2994                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2995                continue;
2996            }
2997
2998            if (best == null || cur.priority > best.priority) {
2999                best = cur;
3000            }
3001        }
3002
3003        if (best != null) {
3004            return best.getComponentInfo().getComponentName();
3005        } else {
3006            throw new RuntimeException("There must be at least one intent filter verifier");
3007        }
3008    }
3009
3010    private @Nullable ComponentName getEphemeralResolverLPr() {
3011        final String[] packageArray =
3012                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3013        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3014            if (DEBUG_EPHEMERAL) {
3015                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3016            }
3017            return null;
3018        }
3019
3020        final int resolveFlags =
3021                MATCH_DIRECT_BOOT_AWARE
3022                | MATCH_DIRECT_BOOT_UNAWARE
3023                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3024        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3025        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3026                resolveFlags, UserHandle.USER_SYSTEM);
3027
3028        final int N = resolvers.size();
3029        if (N == 0) {
3030            if (DEBUG_EPHEMERAL) {
3031                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3032            }
3033            return null;
3034        }
3035
3036        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3037        for (int i = 0; i < N; i++) {
3038            final ResolveInfo info = resolvers.get(i);
3039
3040            if (info.serviceInfo == null) {
3041                continue;
3042            }
3043
3044            final String packageName = info.serviceInfo.packageName;
3045            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3046                if (DEBUG_EPHEMERAL) {
3047                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3048                            + " pkg: " + packageName + ", info:" + info);
3049                }
3050                continue;
3051            }
3052
3053            if (DEBUG_EPHEMERAL) {
3054                Slog.v(TAG, "Ephemeral resolver found;"
3055                        + " pkg: " + packageName + ", info:" + info);
3056            }
3057            return new ComponentName(packageName, info.serviceInfo.name);
3058        }
3059        if (DEBUG_EPHEMERAL) {
3060            Slog.v(TAG, "Ephemeral resolver NOT found");
3061        }
3062        return null;
3063    }
3064
3065    private @Nullable ComponentName getEphemeralInstallerLPr() {
3066        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3067        intent.addCategory(Intent.CATEGORY_DEFAULT);
3068        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3069
3070        final int resolveFlags =
3071                MATCH_DIRECT_BOOT_AWARE
3072                | MATCH_DIRECT_BOOT_UNAWARE
3073                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3074        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3075                resolveFlags, UserHandle.USER_SYSTEM);
3076        Iterator<ResolveInfo> iter = matches.iterator();
3077        while (iter.hasNext()) {
3078            final ResolveInfo rInfo = iter.next();
3079            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3080            if (ps != null) {
3081                final PermissionsState permissionsState = ps.getPermissionsState();
3082                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3083                    continue;
3084                }
3085            }
3086            iter.remove();
3087        }
3088        if (matches.size() == 0) {
3089            return null;
3090        } else if (matches.size() == 1) {
3091            return matches.get(0).getComponentInfo().getComponentName();
3092        } else {
3093            throw new RuntimeException(
3094                    "There must be at most one ephemeral installer; found " + matches);
3095        }
3096    }
3097
3098    private void primeDomainVerificationsLPw(int userId) {
3099        if (DEBUG_DOMAIN_VERIFICATION) {
3100            Slog.d(TAG, "Priming domain verifications in user " + userId);
3101        }
3102
3103        SystemConfig systemConfig = SystemConfig.getInstance();
3104        ArraySet<String> packages = systemConfig.getLinkedApps();
3105
3106        for (String packageName : packages) {
3107            PackageParser.Package pkg = mPackages.get(packageName);
3108            if (pkg != null) {
3109                if (!pkg.isSystemApp()) {
3110                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3111                    continue;
3112                }
3113
3114                ArraySet<String> domains = null;
3115                for (PackageParser.Activity a : pkg.activities) {
3116                    for (ActivityIntentInfo filter : a.intents) {
3117                        if (hasValidDomains(filter)) {
3118                            if (domains == null) {
3119                                domains = new ArraySet<String>();
3120                            }
3121                            domains.addAll(filter.getHostsList());
3122                        }
3123                    }
3124                }
3125
3126                if (domains != null && domains.size() > 0) {
3127                    if (DEBUG_DOMAIN_VERIFICATION) {
3128                        Slog.v(TAG, "      + " + packageName);
3129                    }
3130                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3131                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3132                    // and then 'always' in the per-user state actually used for intent resolution.
3133                    final IntentFilterVerificationInfo ivi;
3134                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3135                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3136                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3137                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3138                } else {
3139                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3140                            + "' does not handle web links");
3141                }
3142            } else {
3143                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3144            }
3145        }
3146
3147        scheduleWritePackageRestrictionsLocked(userId);
3148        scheduleWriteSettingsLocked();
3149    }
3150
3151    private void applyFactoryDefaultBrowserLPw(int userId) {
3152        // The default browser app's package name is stored in a string resource,
3153        // with a product-specific overlay used for vendor customization.
3154        String browserPkg = mContext.getResources().getString(
3155                com.android.internal.R.string.default_browser);
3156        if (!TextUtils.isEmpty(browserPkg)) {
3157            // non-empty string => required to be a known package
3158            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3159            if (ps == null) {
3160                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3161                browserPkg = null;
3162            } else {
3163                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3164            }
3165        }
3166
3167        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3168        // default.  If there's more than one, just leave everything alone.
3169        if (browserPkg == null) {
3170            calculateDefaultBrowserLPw(userId);
3171        }
3172    }
3173
3174    private void calculateDefaultBrowserLPw(int userId) {
3175        List<String> allBrowsers = resolveAllBrowserApps(userId);
3176        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3177        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3178    }
3179
3180    private List<String> resolveAllBrowserApps(int userId) {
3181        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3182        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3183                PackageManager.MATCH_ALL, userId);
3184
3185        final int count = list.size();
3186        List<String> result = new ArrayList<String>(count);
3187        for (int i=0; i<count; i++) {
3188            ResolveInfo info = list.get(i);
3189            if (info.activityInfo == null
3190                    || !info.handleAllWebDataURI
3191                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3192                    || result.contains(info.activityInfo.packageName)) {
3193                continue;
3194            }
3195            result.add(info.activityInfo.packageName);
3196        }
3197
3198        return result;
3199    }
3200
3201    private boolean packageIsBrowser(String packageName, int userId) {
3202        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3203                PackageManager.MATCH_ALL, userId);
3204        final int N = list.size();
3205        for (int i = 0; i < N; i++) {
3206            ResolveInfo info = list.get(i);
3207            if (packageName.equals(info.activityInfo.packageName)) {
3208                return true;
3209            }
3210        }
3211        return false;
3212    }
3213
3214    private void checkDefaultBrowser() {
3215        final int myUserId = UserHandle.myUserId();
3216        final String packageName = getDefaultBrowserPackageName(myUserId);
3217        if (packageName != null) {
3218            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3219            if (info == null) {
3220                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3221                synchronized (mPackages) {
3222                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3223                }
3224            }
3225        }
3226    }
3227
3228    @Override
3229    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3230            throws RemoteException {
3231        try {
3232            return super.onTransact(code, data, reply, flags);
3233        } catch (RuntimeException e) {
3234            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3235                Slog.wtf(TAG, "Package Manager Crash", e);
3236            }
3237            throw e;
3238        }
3239    }
3240
3241    static int[] appendInts(int[] cur, int[] add) {
3242        if (add == null) return cur;
3243        if (cur == null) return add;
3244        final int N = add.length;
3245        for (int i=0; i<N; i++) {
3246            cur = appendInt(cur, add[i]);
3247        }
3248        return cur;
3249    }
3250
3251    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3252        if (!sUserManager.exists(userId)) return null;
3253        if (ps == null) {
3254            return null;
3255        }
3256        final PackageParser.Package p = ps.pkg;
3257        if (p == null) {
3258            return null;
3259        }
3260
3261        final PermissionsState permissionsState = ps.getPermissionsState();
3262
3263        // Compute GIDs only if requested
3264        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3265                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3266        // Compute granted permissions only if package has requested permissions
3267        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3268                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3269        final PackageUserState state = ps.readUserState(userId);
3270
3271        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3272                && ps.isSystem()) {
3273            flags |= MATCH_ANY_USER;
3274        }
3275
3276        return PackageParser.generatePackageInfo(p, gids, flags,
3277                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3278    }
3279
3280    @Override
3281    public void checkPackageStartable(String packageName, int userId) {
3282        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3283
3284        synchronized (mPackages) {
3285            final PackageSetting ps = mSettings.mPackages.get(packageName);
3286            if (ps == null) {
3287                throw new SecurityException("Package " + packageName + " was not found!");
3288            }
3289
3290            if (!ps.getInstalled(userId)) {
3291                throw new SecurityException(
3292                        "Package " + packageName + " was not installed for user " + userId + "!");
3293            }
3294
3295            if (mSafeMode && !ps.isSystem()) {
3296                throw new SecurityException("Package " + packageName + " not a system app!");
3297            }
3298
3299            if (mFrozenPackages.contains(packageName)) {
3300                throw new SecurityException("Package " + packageName + " is currently frozen!");
3301            }
3302
3303            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3304                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3305                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3306            }
3307        }
3308    }
3309
3310    @Override
3311    public boolean isPackageAvailable(String packageName, int userId) {
3312        if (!sUserManager.exists(userId)) return false;
3313        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3314                false /* requireFullPermission */, false /* checkShell */, "is package available");
3315        synchronized (mPackages) {
3316            PackageParser.Package p = mPackages.get(packageName);
3317            if (p != null) {
3318                final PackageSetting ps = (PackageSetting) p.mExtras;
3319                if (ps != null) {
3320                    final PackageUserState state = ps.readUserState(userId);
3321                    if (state != null) {
3322                        return PackageParser.isAvailable(state);
3323                    }
3324                }
3325            }
3326        }
3327        return false;
3328    }
3329
3330    @Override
3331    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3332        if (!sUserManager.exists(userId)) return null;
3333        flags = updateFlagsForPackage(flags, userId, packageName);
3334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3335                false /* requireFullPermission */, false /* checkShell */, "get package info");
3336
3337        // reader
3338        synchronized (mPackages) {
3339            // Normalize package name to hanlde renamed packages
3340            packageName = normalizePackageNameLPr(packageName);
3341
3342            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3343            PackageParser.Package p = null;
3344            if (matchFactoryOnly) {
3345                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3346                if (ps != null) {
3347                    return generatePackageInfo(ps, flags, userId);
3348                }
3349            }
3350            if (p == null) {
3351                p = mPackages.get(packageName);
3352                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3353                    return null;
3354                }
3355            }
3356            if (DEBUG_PACKAGE_INFO)
3357                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3358            if (p != null) {
3359                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3360            }
3361            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3362                final PackageSetting ps = mSettings.mPackages.get(packageName);
3363                return generatePackageInfo(ps, flags, userId);
3364            }
3365        }
3366        return null;
3367    }
3368
3369    @Override
3370    public String[] currentToCanonicalPackageNames(String[] names) {
3371        String[] out = new String[names.length];
3372        // reader
3373        synchronized (mPackages) {
3374            for (int i=names.length-1; i>=0; i--) {
3375                PackageSetting ps = mSettings.mPackages.get(names[i]);
3376                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3377            }
3378        }
3379        return out;
3380    }
3381
3382    @Override
3383    public String[] canonicalToCurrentPackageNames(String[] names) {
3384        String[] out = new String[names.length];
3385        // reader
3386        synchronized (mPackages) {
3387            for (int i=names.length-1; i>=0; i--) {
3388                String cur = mSettings.getRenamedPackageLPr(names[i]);
3389                out[i] = cur != null ? cur : names[i];
3390            }
3391        }
3392        return out;
3393    }
3394
3395    @Override
3396    public int getPackageUid(String packageName, int flags, int userId) {
3397        if (!sUserManager.exists(userId)) return -1;
3398        flags = updateFlagsForPackage(flags, userId, packageName);
3399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3400                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3401
3402        // reader
3403        synchronized (mPackages) {
3404            final PackageParser.Package p = mPackages.get(packageName);
3405            if (p != null && p.isMatch(flags)) {
3406                return UserHandle.getUid(userId, p.applicationInfo.uid);
3407            }
3408            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3409                final PackageSetting ps = mSettings.mPackages.get(packageName);
3410                if (ps != null && ps.isMatch(flags)) {
3411                    return UserHandle.getUid(userId, ps.appId);
3412                }
3413            }
3414        }
3415
3416        return -1;
3417    }
3418
3419    @Override
3420    public int[] getPackageGids(String packageName, int flags, int userId) {
3421        if (!sUserManager.exists(userId)) return null;
3422        flags = updateFlagsForPackage(flags, userId, packageName);
3423        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3424                false /* requireFullPermission */, false /* checkShell */,
3425                "getPackageGids");
3426
3427        // reader
3428        synchronized (mPackages) {
3429            final PackageParser.Package p = mPackages.get(packageName);
3430            if (p != null && p.isMatch(flags)) {
3431                PackageSetting ps = (PackageSetting) p.mExtras;
3432                // TODO: Shouldn't this be checking for package installed state for userId and
3433                // return null?
3434                return ps.getPermissionsState().computeGids(userId);
3435            }
3436            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3437                final PackageSetting ps = mSettings.mPackages.get(packageName);
3438                if (ps != null && ps.isMatch(flags)) {
3439                    return ps.getPermissionsState().computeGids(userId);
3440                }
3441            }
3442        }
3443
3444        return null;
3445    }
3446
3447    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3448        if (bp.perm != null) {
3449            return PackageParser.generatePermissionInfo(bp.perm, flags);
3450        }
3451        PermissionInfo pi = new PermissionInfo();
3452        pi.name = bp.name;
3453        pi.packageName = bp.sourcePackage;
3454        pi.nonLocalizedLabel = bp.name;
3455        pi.protectionLevel = bp.protectionLevel;
3456        return pi;
3457    }
3458
3459    @Override
3460    public PermissionInfo getPermissionInfo(String name, int flags) {
3461        // reader
3462        synchronized (mPackages) {
3463            final BasePermission p = mSettings.mPermissions.get(name);
3464            if (p != null) {
3465                return generatePermissionInfo(p, flags);
3466            }
3467            return null;
3468        }
3469    }
3470
3471    @Override
3472    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3473            int flags) {
3474        // reader
3475        synchronized (mPackages) {
3476            if (group != null && !mPermissionGroups.containsKey(group)) {
3477                // This is thrown as NameNotFoundException
3478                return null;
3479            }
3480
3481            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3482            for (BasePermission p : mSettings.mPermissions.values()) {
3483                if (group == null) {
3484                    if (p.perm == null || p.perm.info.group == null) {
3485                        out.add(generatePermissionInfo(p, flags));
3486                    }
3487                } else {
3488                    if (p.perm != null && group.equals(p.perm.info.group)) {
3489                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3490                    }
3491                }
3492            }
3493            return new ParceledListSlice<>(out);
3494        }
3495    }
3496
3497    @Override
3498    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3499        // reader
3500        synchronized (mPackages) {
3501            return PackageParser.generatePermissionGroupInfo(
3502                    mPermissionGroups.get(name), flags);
3503        }
3504    }
3505
3506    @Override
3507    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3508        // reader
3509        synchronized (mPackages) {
3510            final int N = mPermissionGroups.size();
3511            ArrayList<PermissionGroupInfo> out
3512                    = new ArrayList<PermissionGroupInfo>(N);
3513            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3514                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3515            }
3516            return new ParceledListSlice<>(out);
3517        }
3518    }
3519
3520    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3521            int userId) {
3522        if (!sUserManager.exists(userId)) return null;
3523        PackageSetting ps = mSettings.mPackages.get(packageName);
3524        if (ps != null) {
3525            if (ps.pkg == null) {
3526                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3527                if (pInfo != null) {
3528                    return pInfo.applicationInfo;
3529                }
3530                return null;
3531            }
3532            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3533                    ps.readUserState(userId), userId);
3534        }
3535        return null;
3536    }
3537
3538    @Override
3539    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3540        if (!sUserManager.exists(userId)) return null;
3541        flags = updateFlagsForApplication(flags, userId, packageName);
3542        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3543                false /* requireFullPermission */, false /* checkShell */, "get application info");
3544
3545        // writer
3546        synchronized (mPackages) {
3547            // Normalize package name to hanlde renamed packages
3548            packageName = normalizePackageNameLPr(packageName);
3549
3550            PackageParser.Package p = mPackages.get(packageName);
3551            if (DEBUG_PACKAGE_INFO) Log.v(
3552                    TAG, "getApplicationInfo " + packageName
3553                    + ": " + p);
3554            if (p != null) {
3555                PackageSetting ps = mSettings.mPackages.get(packageName);
3556                if (ps == null) return null;
3557                // Note: isEnabledLP() does not apply here - always return info
3558                return PackageParser.generateApplicationInfo(
3559                        p, flags, ps.readUserState(userId), userId);
3560            }
3561            if ("android".equals(packageName)||"system".equals(packageName)) {
3562                return mAndroidApplication;
3563            }
3564            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3565                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3566            }
3567        }
3568        return null;
3569    }
3570
3571    private String normalizePackageNameLPr(String packageName) {
3572        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3573        return normalizedPackageName != null ? normalizedPackageName : packageName;
3574    }
3575
3576    @Override
3577    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3578            final IPackageDataObserver observer) {
3579        mContext.enforceCallingOrSelfPermission(
3580                android.Manifest.permission.CLEAR_APP_CACHE, null);
3581        // Queue up an async operation since clearing cache may take a little while.
3582        mHandler.post(new Runnable() {
3583            public void run() {
3584                mHandler.removeCallbacks(this);
3585                boolean success = true;
3586                synchronized (mInstallLock) {
3587                    try {
3588                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3589                    } catch (InstallerException e) {
3590                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3591                        success = false;
3592                    }
3593                }
3594                if (observer != null) {
3595                    try {
3596                        observer.onRemoveCompleted(null, success);
3597                    } catch (RemoteException e) {
3598                        Slog.w(TAG, "RemoveException when invoking call back");
3599                    }
3600                }
3601            }
3602        });
3603    }
3604
3605    @Override
3606    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3607            final IntentSender pi) {
3608        mContext.enforceCallingOrSelfPermission(
3609                android.Manifest.permission.CLEAR_APP_CACHE, null);
3610        // Queue up an async operation since clearing cache may take a little while.
3611        mHandler.post(new Runnable() {
3612            public void run() {
3613                mHandler.removeCallbacks(this);
3614                boolean success = true;
3615                synchronized (mInstallLock) {
3616                    try {
3617                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3618                    } catch (InstallerException e) {
3619                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3620                        success = false;
3621                    }
3622                }
3623                if(pi != null) {
3624                    try {
3625                        // Callback via pending intent
3626                        int code = success ? 1 : 0;
3627                        pi.sendIntent(null, code, null,
3628                                null, null);
3629                    } catch (SendIntentException e1) {
3630                        Slog.i(TAG, "Failed to send pending intent");
3631                    }
3632                }
3633            }
3634        });
3635    }
3636
3637    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3638        synchronized (mInstallLock) {
3639            try {
3640                mInstaller.freeCache(volumeUuid, freeStorageSize);
3641            } catch (InstallerException e) {
3642                throw new IOException("Failed to free enough space", e);
3643            }
3644        }
3645    }
3646
3647    /**
3648     * Update given flags based on encryption status of current user.
3649     */
3650    private int updateFlags(int flags, int userId) {
3651        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3652                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3653            // Caller expressed an explicit opinion about what encryption
3654            // aware/unaware components they want to see, so fall through and
3655            // give them what they want
3656        } else {
3657            // Caller expressed no opinion, so match based on user state
3658            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3659                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3660            } else {
3661                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3662            }
3663        }
3664        return flags;
3665    }
3666
3667    private UserManagerInternal getUserManagerInternal() {
3668        if (mUserManagerInternal == null) {
3669            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3670        }
3671        return mUserManagerInternal;
3672    }
3673
3674    /**
3675     * Update given flags when being used to request {@link PackageInfo}.
3676     */
3677    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3678        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3679        boolean triaged = true;
3680        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3681                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3682            // Caller is asking for component details, so they'd better be
3683            // asking for specific encryption matching behavior, or be triaged
3684            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3685                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3686                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3687                triaged = false;
3688            }
3689        }
3690        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3691                | PackageManager.MATCH_SYSTEM_ONLY
3692                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3693            triaged = false;
3694        }
3695        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3696            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3697                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3698                    + Debug.getCallers(5));
3699        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3700                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3701            // If the caller wants all packages and has a restricted profile associated with it,
3702            // then match all users. This is to make sure that launchers that need to access work
3703            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3704            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3705            flags |= PackageManager.MATCH_ANY_USER;
3706        }
3707        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3708            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3709                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3710        }
3711        return updateFlags(flags, userId);
3712    }
3713
3714    /**
3715     * Update given flags when being used to request {@link ApplicationInfo}.
3716     */
3717    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3718        return updateFlagsForPackage(flags, userId, cookie);
3719    }
3720
3721    /**
3722     * Update given flags when being used to request {@link ComponentInfo}.
3723     */
3724    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3725        if (cookie instanceof Intent) {
3726            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3727                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3728            }
3729        }
3730
3731        boolean triaged = true;
3732        // Caller is asking for component details, so they'd better be
3733        // asking for specific encryption matching behavior, or be triaged
3734        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3735                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3736                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3737            triaged = false;
3738        }
3739        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3740            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3741                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3742        }
3743
3744        return updateFlags(flags, userId);
3745    }
3746
3747    /**
3748     * Update given intent when being used to request {@link ResolveInfo}.
3749     */
3750    private Intent updateIntentForResolve(Intent intent) {
3751        if (intent.getSelector() != null) {
3752            intent = intent.getSelector();
3753        }
3754        if (DEBUG_PREFERRED) {
3755            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3756        }
3757        return intent;
3758    }
3759
3760    /**
3761     * Update given flags when being used to request {@link ResolveInfo}.
3762     */
3763    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3764        // Safe mode means we shouldn't match any third-party components
3765        if (mSafeMode) {
3766            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3767        }
3768        final int callingUid = Binder.getCallingUid();
3769        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3770            // The system sees all components
3771            flags |= PackageManager.MATCH_EPHEMERAL;
3772        } else if (getEphemeralPackageName(callingUid) != null) {
3773            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3774            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3775            flags |= PackageManager.MATCH_EPHEMERAL;
3776        } else {
3777            // Otherwise, prevent leaking ephemeral components
3778            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3779            flags &= ~PackageManager.MATCH_EPHEMERAL;
3780        }
3781        return updateFlagsForComponent(flags, userId, cookie);
3782    }
3783
3784    @Override
3785    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3786        if (!sUserManager.exists(userId)) return null;
3787        flags = updateFlagsForComponent(flags, userId, component);
3788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3789                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3790        synchronized (mPackages) {
3791            PackageParser.Activity a = mActivities.mActivities.get(component);
3792
3793            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3794            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3795                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3796                if (ps == null) return null;
3797                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3798                        userId);
3799            }
3800            if (mResolveComponentName.equals(component)) {
3801                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3802                        new PackageUserState(), userId);
3803            }
3804        }
3805        return null;
3806    }
3807
3808    @Override
3809    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3810            String resolvedType) {
3811        synchronized (mPackages) {
3812            if (component.equals(mResolveComponentName)) {
3813                // The resolver supports EVERYTHING!
3814                return true;
3815            }
3816            PackageParser.Activity a = mActivities.mActivities.get(component);
3817            if (a == null) {
3818                return false;
3819            }
3820            for (int i=0; i<a.intents.size(); i++) {
3821                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3822                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3823                    return true;
3824                }
3825            }
3826            return false;
3827        }
3828    }
3829
3830    @Override
3831    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3832        if (!sUserManager.exists(userId)) return null;
3833        flags = updateFlagsForComponent(flags, userId, component);
3834        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3835                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3836        synchronized (mPackages) {
3837            PackageParser.Activity a = mReceivers.mActivities.get(component);
3838            if (DEBUG_PACKAGE_INFO) Log.v(
3839                TAG, "getReceiverInfo " + component + ": " + a);
3840            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3841                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3842                if (ps == null) return null;
3843                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3844                        userId);
3845            }
3846        }
3847        return null;
3848    }
3849
3850    @Override
3851    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3852        if (!sUserManager.exists(userId)) return null;
3853        flags = updateFlagsForComponent(flags, userId, component);
3854        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3855                false /* requireFullPermission */, false /* checkShell */, "get service info");
3856        synchronized (mPackages) {
3857            PackageParser.Service s = mServices.mServices.get(component);
3858            if (DEBUG_PACKAGE_INFO) Log.v(
3859                TAG, "getServiceInfo " + component + ": " + s);
3860            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3861                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3862                if (ps == null) return null;
3863                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3864                        userId);
3865            }
3866        }
3867        return null;
3868    }
3869
3870    @Override
3871    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        flags = updateFlagsForComponent(flags, userId, component);
3874        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3875                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3876        synchronized (mPackages) {
3877            PackageParser.Provider p = mProviders.mProviders.get(component);
3878            if (DEBUG_PACKAGE_INFO) Log.v(
3879                TAG, "getProviderInfo " + component + ": " + p);
3880            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3881                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3882                if (ps == null) return null;
3883                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3884                        userId);
3885            }
3886        }
3887        return null;
3888    }
3889
3890    @Override
3891    public String[] getSystemSharedLibraryNames() {
3892        Set<String> libSet;
3893        synchronized (mPackages) {
3894            libSet = mSharedLibraries.keySet();
3895            int size = libSet.size();
3896            if (size > 0) {
3897                String[] libs = new String[size];
3898                libSet.toArray(libs);
3899                return libs;
3900            }
3901        }
3902        return null;
3903    }
3904
3905    @Override
3906    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3907        synchronized (mPackages) {
3908            return mServicesSystemSharedLibraryPackageName;
3909        }
3910    }
3911
3912    @Override
3913    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3914        synchronized (mPackages) {
3915            return mSharedSystemSharedLibraryPackageName;
3916        }
3917    }
3918
3919    @Override
3920    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3921        synchronized (mPackages) {
3922            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3923
3924            final FeatureInfo fi = new FeatureInfo();
3925            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3926                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3927            res.add(fi);
3928
3929            return new ParceledListSlice<>(res);
3930        }
3931    }
3932
3933    @Override
3934    public boolean hasSystemFeature(String name, int version) {
3935        synchronized (mPackages) {
3936            final FeatureInfo feat = mAvailableFeatures.get(name);
3937            if (feat == null) {
3938                return false;
3939            } else {
3940                return feat.version >= version;
3941            }
3942        }
3943    }
3944
3945    @Override
3946    public int checkPermission(String permName, String pkgName, int userId) {
3947        if (!sUserManager.exists(userId)) {
3948            return PackageManager.PERMISSION_DENIED;
3949        }
3950
3951        synchronized (mPackages) {
3952            final PackageParser.Package p = mPackages.get(pkgName);
3953            if (p != null && p.mExtras != null) {
3954                final PackageSetting ps = (PackageSetting) p.mExtras;
3955                final PermissionsState permissionsState = ps.getPermissionsState();
3956                if (permissionsState.hasPermission(permName, userId)) {
3957                    return PackageManager.PERMISSION_GRANTED;
3958                }
3959                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3960                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3961                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3962                    return PackageManager.PERMISSION_GRANTED;
3963                }
3964            }
3965        }
3966
3967        return PackageManager.PERMISSION_DENIED;
3968    }
3969
3970    @Override
3971    public int checkUidPermission(String permName, int uid) {
3972        final int userId = UserHandle.getUserId(uid);
3973
3974        if (!sUserManager.exists(userId)) {
3975            return PackageManager.PERMISSION_DENIED;
3976        }
3977
3978        synchronized (mPackages) {
3979            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3980            if (obj != null) {
3981                final SettingBase ps = (SettingBase) obj;
3982                final PermissionsState permissionsState = ps.getPermissionsState();
3983                if (permissionsState.hasPermission(permName, userId)) {
3984                    return PackageManager.PERMISSION_GRANTED;
3985                }
3986                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3987                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3988                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3989                    return PackageManager.PERMISSION_GRANTED;
3990                }
3991            } else {
3992                ArraySet<String> perms = mSystemPermissions.get(uid);
3993                if (perms != null) {
3994                    if (perms.contains(permName)) {
3995                        return PackageManager.PERMISSION_GRANTED;
3996                    }
3997                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3998                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3999                        return PackageManager.PERMISSION_GRANTED;
4000                    }
4001                }
4002            }
4003        }
4004
4005        return PackageManager.PERMISSION_DENIED;
4006    }
4007
4008    @Override
4009    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4010        if (UserHandle.getCallingUserId() != userId) {
4011            mContext.enforceCallingPermission(
4012                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4013                    "isPermissionRevokedByPolicy for user " + userId);
4014        }
4015
4016        if (checkPermission(permission, packageName, userId)
4017                == PackageManager.PERMISSION_GRANTED) {
4018            return false;
4019        }
4020
4021        final long identity = Binder.clearCallingIdentity();
4022        try {
4023            final int flags = getPermissionFlags(permission, packageName, userId);
4024            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4025        } finally {
4026            Binder.restoreCallingIdentity(identity);
4027        }
4028    }
4029
4030    @Override
4031    public String getPermissionControllerPackageName() {
4032        synchronized (mPackages) {
4033            return mRequiredInstallerPackage;
4034        }
4035    }
4036
4037    /**
4038     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4039     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4040     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4041     * @param message the message to log on security exception
4042     */
4043    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4044            boolean checkShell, String message) {
4045        if (userId < 0) {
4046            throw new IllegalArgumentException("Invalid userId " + userId);
4047        }
4048        if (checkShell) {
4049            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4050        }
4051        if (userId == UserHandle.getUserId(callingUid)) return;
4052        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4053            if (requireFullPermission) {
4054                mContext.enforceCallingOrSelfPermission(
4055                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4056            } else {
4057                try {
4058                    mContext.enforceCallingOrSelfPermission(
4059                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4060                } catch (SecurityException se) {
4061                    mContext.enforceCallingOrSelfPermission(
4062                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4063                }
4064            }
4065        }
4066    }
4067
4068    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4069        if (callingUid == Process.SHELL_UID) {
4070            if (userHandle >= 0
4071                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4072                throw new SecurityException("Shell does not have permission to access user "
4073                        + userHandle);
4074            } else if (userHandle < 0) {
4075                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4076                        + Debug.getCallers(3));
4077            }
4078        }
4079    }
4080
4081    private BasePermission findPermissionTreeLP(String permName) {
4082        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4083            if (permName.startsWith(bp.name) &&
4084                    permName.length() > bp.name.length() &&
4085                    permName.charAt(bp.name.length()) == '.') {
4086                return bp;
4087            }
4088        }
4089        return null;
4090    }
4091
4092    private BasePermission checkPermissionTreeLP(String permName) {
4093        if (permName != null) {
4094            BasePermission bp = findPermissionTreeLP(permName);
4095            if (bp != null) {
4096                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4097                    return bp;
4098                }
4099                throw new SecurityException("Calling uid "
4100                        + Binder.getCallingUid()
4101                        + " is not allowed to add to permission tree "
4102                        + bp.name + " owned by uid " + bp.uid);
4103            }
4104        }
4105        throw new SecurityException("No permission tree found for " + permName);
4106    }
4107
4108    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4109        if (s1 == null) {
4110            return s2 == null;
4111        }
4112        if (s2 == null) {
4113            return false;
4114        }
4115        if (s1.getClass() != s2.getClass()) {
4116            return false;
4117        }
4118        return s1.equals(s2);
4119    }
4120
4121    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4122        if (pi1.icon != pi2.icon) return false;
4123        if (pi1.logo != pi2.logo) return false;
4124        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4125        if (!compareStrings(pi1.name, pi2.name)) return false;
4126        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4127        // We'll take care of setting this one.
4128        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4129        // These are not currently stored in settings.
4130        //if (!compareStrings(pi1.group, pi2.group)) return false;
4131        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4132        //if (pi1.labelRes != pi2.labelRes) return false;
4133        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4134        return true;
4135    }
4136
4137    int permissionInfoFootprint(PermissionInfo info) {
4138        int size = info.name.length();
4139        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4140        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4141        return size;
4142    }
4143
4144    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4145        int size = 0;
4146        for (BasePermission perm : mSettings.mPermissions.values()) {
4147            if (perm.uid == tree.uid) {
4148                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4149            }
4150        }
4151        return size;
4152    }
4153
4154    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4155        // We calculate the max size of permissions defined by this uid and throw
4156        // if that plus the size of 'info' would exceed our stated maximum.
4157        if (tree.uid != Process.SYSTEM_UID) {
4158            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4159            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4160                throw new SecurityException("Permission tree size cap exceeded");
4161            }
4162        }
4163    }
4164
4165    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4166        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4167            throw new SecurityException("Label must be specified in permission");
4168        }
4169        BasePermission tree = checkPermissionTreeLP(info.name);
4170        BasePermission bp = mSettings.mPermissions.get(info.name);
4171        boolean added = bp == null;
4172        boolean changed = true;
4173        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4174        if (added) {
4175            enforcePermissionCapLocked(info, tree);
4176            bp = new BasePermission(info.name, tree.sourcePackage,
4177                    BasePermission.TYPE_DYNAMIC);
4178        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4179            throw new SecurityException(
4180                    "Not allowed to modify non-dynamic permission "
4181                    + info.name);
4182        } else {
4183            if (bp.protectionLevel == fixedLevel
4184                    && bp.perm.owner.equals(tree.perm.owner)
4185                    && bp.uid == tree.uid
4186                    && comparePermissionInfos(bp.perm.info, info)) {
4187                changed = false;
4188            }
4189        }
4190        bp.protectionLevel = fixedLevel;
4191        info = new PermissionInfo(info);
4192        info.protectionLevel = fixedLevel;
4193        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4194        bp.perm.info.packageName = tree.perm.info.packageName;
4195        bp.uid = tree.uid;
4196        if (added) {
4197            mSettings.mPermissions.put(info.name, bp);
4198        }
4199        if (changed) {
4200            if (!async) {
4201                mSettings.writeLPr();
4202            } else {
4203                scheduleWriteSettingsLocked();
4204            }
4205        }
4206        return added;
4207    }
4208
4209    @Override
4210    public boolean addPermission(PermissionInfo info) {
4211        synchronized (mPackages) {
4212            return addPermissionLocked(info, false);
4213        }
4214    }
4215
4216    @Override
4217    public boolean addPermissionAsync(PermissionInfo info) {
4218        synchronized (mPackages) {
4219            return addPermissionLocked(info, true);
4220        }
4221    }
4222
4223    @Override
4224    public void removePermission(String name) {
4225        synchronized (mPackages) {
4226            checkPermissionTreeLP(name);
4227            BasePermission bp = mSettings.mPermissions.get(name);
4228            if (bp != null) {
4229                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4230                    throw new SecurityException(
4231                            "Not allowed to modify non-dynamic permission "
4232                            + name);
4233                }
4234                mSettings.mPermissions.remove(name);
4235                mSettings.writeLPr();
4236            }
4237        }
4238    }
4239
4240    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4241            BasePermission bp) {
4242        int index = pkg.requestedPermissions.indexOf(bp.name);
4243        if (index == -1) {
4244            throw new SecurityException("Package " + pkg.packageName
4245                    + " has not requested permission " + bp.name);
4246        }
4247        if (!bp.isRuntime() && !bp.isDevelopment()) {
4248            throw new SecurityException("Permission " + bp.name
4249                    + " is not a changeable permission type");
4250        }
4251    }
4252
4253    @Override
4254    public void grantRuntimePermission(String packageName, String name, final int userId) {
4255        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4256    }
4257
4258    private void grantRuntimePermission(String packageName, String name, final int userId,
4259            boolean overridePolicy) {
4260        if (!sUserManager.exists(userId)) {
4261            Log.e(TAG, "No such user:" + userId);
4262            return;
4263        }
4264
4265        mContext.enforceCallingOrSelfPermission(
4266                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4267                "grantRuntimePermission");
4268
4269        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4270                true /* requireFullPermission */, true /* checkShell */,
4271                "grantRuntimePermission");
4272
4273        final int uid;
4274        final SettingBase sb;
4275
4276        synchronized (mPackages) {
4277            final PackageParser.Package pkg = mPackages.get(packageName);
4278            if (pkg == null) {
4279                throw new IllegalArgumentException("Unknown package: " + packageName);
4280            }
4281
4282            final BasePermission bp = mSettings.mPermissions.get(name);
4283            if (bp == null) {
4284                throw new IllegalArgumentException("Unknown permission: " + name);
4285            }
4286
4287            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4288
4289            // If a permission review is required for legacy apps we represent
4290            // their permissions as always granted runtime ones since we need
4291            // to keep the review required permission flag per user while an
4292            // install permission's state is shared across all users.
4293            if (mPermissionReviewRequired
4294                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4295                    && bp.isRuntime()) {
4296                return;
4297            }
4298
4299            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4300            sb = (SettingBase) pkg.mExtras;
4301            if (sb == null) {
4302                throw new IllegalArgumentException("Unknown package: " + packageName);
4303            }
4304
4305            final PermissionsState permissionsState = sb.getPermissionsState();
4306
4307            final int flags = permissionsState.getPermissionFlags(name, userId);
4308            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4309                throw new SecurityException("Cannot grant system fixed permission "
4310                        + name + " for package " + packageName);
4311            }
4312            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4313                throw new SecurityException("Cannot grant policy fixed permission "
4314                        + name + " for package " + packageName);
4315            }
4316
4317            if (bp.isDevelopment()) {
4318                // Development permissions must be handled specially, since they are not
4319                // normal runtime permissions.  For now they apply to all users.
4320                if (permissionsState.grantInstallPermission(bp) !=
4321                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4322                    scheduleWriteSettingsLocked();
4323                }
4324                return;
4325            }
4326
4327            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4328                throw new SecurityException("Cannot grant non-ephemeral permission"
4329                        + name + " for package " + packageName);
4330            }
4331
4332            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4333                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4334                return;
4335            }
4336
4337            final int result = permissionsState.grantRuntimePermission(bp, userId);
4338            switch (result) {
4339                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4340                    return;
4341                }
4342
4343                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4344                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4345                    mHandler.post(new Runnable() {
4346                        @Override
4347                        public void run() {
4348                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4349                        }
4350                    });
4351                }
4352                break;
4353            }
4354
4355            if (bp.isRuntime()) {
4356                logPermissionGranted(mContext, name, packageName);
4357            }
4358
4359            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4360
4361            // Not critical if that is lost - app has to request again.
4362            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4363        }
4364
4365        // Only need to do this if user is initialized. Otherwise it's a new user
4366        // and there are no processes running as the user yet and there's no need
4367        // to make an expensive call to remount processes for the changed permissions.
4368        if (READ_EXTERNAL_STORAGE.equals(name)
4369                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4370            final long token = Binder.clearCallingIdentity();
4371            try {
4372                if (sUserManager.isInitialized(userId)) {
4373                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4374                            StorageManagerInternal.class);
4375                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4376                }
4377            } finally {
4378                Binder.restoreCallingIdentity(token);
4379            }
4380        }
4381    }
4382
4383    @Override
4384    public void revokeRuntimePermission(String packageName, String name, int userId) {
4385        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4386    }
4387
4388    private void revokeRuntimePermission(String packageName, String name, int userId,
4389            boolean overridePolicy) {
4390        if (!sUserManager.exists(userId)) {
4391            Log.e(TAG, "No such user:" + userId);
4392            return;
4393        }
4394
4395        mContext.enforceCallingOrSelfPermission(
4396                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4397                "revokeRuntimePermission");
4398
4399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4400                true /* requireFullPermission */, true /* checkShell */,
4401                "revokeRuntimePermission");
4402
4403        final int appId;
4404
4405        synchronized (mPackages) {
4406            final PackageParser.Package pkg = mPackages.get(packageName);
4407            if (pkg == null) {
4408                throw new IllegalArgumentException("Unknown package: " + packageName);
4409            }
4410
4411            final BasePermission bp = mSettings.mPermissions.get(name);
4412            if (bp == null) {
4413                throw new IllegalArgumentException("Unknown permission: " + name);
4414            }
4415
4416            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4417
4418            // If a permission review is required for legacy apps we represent
4419            // their permissions as always granted runtime ones since we need
4420            // to keep the review required permission flag per user while an
4421            // install permission's state is shared across all users.
4422            if (mPermissionReviewRequired
4423                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4424                    && bp.isRuntime()) {
4425                return;
4426            }
4427
4428            SettingBase sb = (SettingBase) pkg.mExtras;
4429            if (sb == null) {
4430                throw new IllegalArgumentException("Unknown package: " + packageName);
4431            }
4432
4433            final PermissionsState permissionsState = sb.getPermissionsState();
4434
4435            final int flags = permissionsState.getPermissionFlags(name, userId);
4436            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4437                throw new SecurityException("Cannot revoke system fixed permission "
4438                        + name + " for package " + packageName);
4439            }
4440            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4441                throw new SecurityException("Cannot revoke policy fixed permission "
4442                        + name + " for package " + packageName);
4443            }
4444
4445            if (bp.isDevelopment()) {
4446                // Development permissions must be handled specially, since they are not
4447                // normal runtime permissions.  For now they apply to all users.
4448                if (permissionsState.revokeInstallPermission(bp) !=
4449                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4450                    scheduleWriteSettingsLocked();
4451                }
4452                return;
4453            }
4454
4455            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4456                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4457                return;
4458            }
4459
4460            if (bp.isRuntime()) {
4461                logPermissionRevoked(mContext, name, packageName);
4462            }
4463
4464            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4465
4466            // Critical, after this call app should never have the permission.
4467            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4468
4469            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4470        }
4471
4472        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4473    }
4474
4475    /**
4476     * Get the first event id for the permission.
4477     *
4478     * <p>There are four events for each permission: <ul>
4479     *     <li>Request permission: first id + 0</li>
4480     *     <li>Grant permission: first id + 1</li>
4481     *     <li>Request for permission denied: first id + 2</li>
4482     *     <li>Revoke permission: first id + 3</li>
4483     * </ul></p>
4484     *
4485     * @param name name of the permission
4486     *
4487     * @return The first event id for the permission
4488     */
4489    private static int getBaseEventId(@NonNull String name) {
4490        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4491
4492        if (eventIdIndex == -1) {
4493            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4494                    || "user".equals(Build.TYPE)) {
4495                Log.i(TAG, "Unknown permission " + name);
4496
4497                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4498            } else {
4499                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4500                //
4501                // Also update
4502                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4503                // - metrics_constants.proto
4504                throw new IllegalStateException("Unknown permission " + name);
4505            }
4506        }
4507
4508        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4509    }
4510
4511    /**
4512     * Log that a permission was revoked.
4513     *
4514     * @param context Context of the caller
4515     * @param name name of the permission
4516     * @param packageName package permission if for
4517     */
4518    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4519            @NonNull String packageName) {
4520        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4521    }
4522
4523    /**
4524     * Log that a permission request was granted.
4525     *
4526     * @param context Context of the caller
4527     * @param name name of the permission
4528     * @param packageName package permission if for
4529     */
4530    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4531            @NonNull String packageName) {
4532        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4533    }
4534
4535    @Override
4536    public void resetRuntimePermissions() {
4537        mContext.enforceCallingOrSelfPermission(
4538                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4539                "revokeRuntimePermission");
4540
4541        int callingUid = Binder.getCallingUid();
4542        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4543            mContext.enforceCallingOrSelfPermission(
4544                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4545                    "resetRuntimePermissions");
4546        }
4547
4548        synchronized (mPackages) {
4549            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4550            for (int userId : UserManagerService.getInstance().getUserIds()) {
4551                final int packageCount = mPackages.size();
4552                for (int i = 0; i < packageCount; i++) {
4553                    PackageParser.Package pkg = mPackages.valueAt(i);
4554                    if (!(pkg.mExtras instanceof PackageSetting)) {
4555                        continue;
4556                    }
4557                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4558                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4559                }
4560            }
4561        }
4562    }
4563
4564    @Override
4565    public int getPermissionFlags(String name, String packageName, int userId) {
4566        if (!sUserManager.exists(userId)) {
4567            return 0;
4568        }
4569
4570        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4571
4572        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4573                true /* requireFullPermission */, false /* checkShell */,
4574                "getPermissionFlags");
4575
4576        synchronized (mPackages) {
4577            final PackageParser.Package pkg = mPackages.get(packageName);
4578            if (pkg == null) {
4579                return 0;
4580            }
4581
4582            final BasePermission bp = mSettings.mPermissions.get(name);
4583            if (bp == null) {
4584                return 0;
4585            }
4586
4587            SettingBase sb = (SettingBase) pkg.mExtras;
4588            if (sb == null) {
4589                return 0;
4590            }
4591
4592            PermissionsState permissionsState = sb.getPermissionsState();
4593            return permissionsState.getPermissionFlags(name, userId);
4594        }
4595    }
4596
4597    @Override
4598    public void updatePermissionFlags(String name, String packageName, int flagMask,
4599            int flagValues, int userId) {
4600        if (!sUserManager.exists(userId)) {
4601            return;
4602        }
4603
4604        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4605
4606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4607                true /* requireFullPermission */, true /* checkShell */,
4608                "updatePermissionFlags");
4609
4610        // Only the system can change these flags and nothing else.
4611        if (getCallingUid() != Process.SYSTEM_UID) {
4612            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4613            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4614            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4615            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4616            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4617        }
4618
4619        synchronized (mPackages) {
4620            final PackageParser.Package pkg = mPackages.get(packageName);
4621            if (pkg == null) {
4622                throw new IllegalArgumentException("Unknown package: " + packageName);
4623            }
4624
4625            final BasePermission bp = mSettings.mPermissions.get(name);
4626            if (bp == null) {
4627                throw new IllegalArgumentException("Unknown permission: " + name);
4628            }
4629
4630            SettingBase sb = (SettingBase) pkg.mExtras;
4631            if (sb == null) {
4632                throw new IllegalArgumentException("Unknown package: " + packageName);
4633            }
4634
4635            PermissionsState permissionsState = sb.getPermissionsState();
4636
4637            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4638
4639            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4640                // Install and runtime permissions are stored in different places,
4641                // so figure out what permission changed and persist the change.
4642                if (permissionsState.getInstallPermissionState(name) != null) {
4643                    scheduleWriteSettingsLocked();
4644                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4645                        || hadState) {
4646                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4647                }
4648            }
4649        }
4650    }
4651
4652    /**
4653     * Update the permission flags for all packages and runtime permissions of a user in order
4654     * to allow device or profile owner to remove POLICY_FIXED.
4655     */
4656    @Override
4657    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4658        if (!sUserManager.exists(userId)) {
4659            return;
4660        }
4661
4662        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4663
4664        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4665                true /* requireFullPermission */, true /* checkShell */,
4666                "updatePermissionFlagsForAllApps");
4667
4668        // Only the system can change system fixed flags.
4669        if (getCallingUid() != Process.SYSTEM_UID) {
4670            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4671            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4672        }
4673
4674        synchronized (mPackages) {
4675            boolean changed = false;
4676            final int packageCount = mPackages.size();
4677            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4678                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4679                SettingBase sb = (SettingBase) pkg.mExtras;
4680                if (sb == null) {
4681                    continue;
4682                }
4683                PermissionsState permissionsState = sb.getPermissionsState();
4684                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4685                        userId, flagMask, flagValues);
4686            }
4687            if (changed) {
4688                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4689            }
4690        }
4691    }
4692
4693    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4694        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4695                != PackageManager.PERMISSION_GRANTED
4696            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4697                != PackageManager.PERMISSION_GRANTED) {
4698            throw new SecurityException(message + " requires "
4699                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4700                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4701        }
4702    }
4703
4704    @Override
4705    public boolean shouldShowRequestPermissionRationale(String permissionName,
4706            String packageName, int userId) {
4707        if (UserHandle.getCallingUserId() != userId) {
4708            mContext.enforceCallingPermission(
4709                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4710                    "canShowRequestPermissionRationale for user " + userId);
4711        }
4712
4713        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4714        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4715            return false;
4716        }
4717
4718        if (checkPermission(permissionName, packageName, userId)
4719                == PackageManager.PERMISSION_GRANTED) {
4720            return false;
4721        }
4722
4723        final int flags;
4724
4725        final long identity = Binder.clearCallingIdentity();
4726        try {
4727            flags = getPermissionFlags(permissionName,
4728                    packageName, userId);
4729        } finally {
4730            Binder.restoreCallingIdentity(identity);
4731        }
4732
4733        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4734                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4735                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4736
4737        if ((flags & fixedFlags) != 0) {
4738            return false;
4739        }
4740
4741        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4742    }
4743
4744    @Override
4745    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4746        mContext.enforceCallingOrSelfPermission(
4747                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4748                "addOnPermissionsChangeListener");
4749
4750        synchronized (mPackages) {
4751            mOnPermissionChangeListeners.addListenerLocked(listener);
4752        }
4753    }
4754
4755    @Override
4756    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4757        synchronized (mPackages) {
4758            mOnPermissionChangeListeners.removeListenerLocked(listener);
4759        }
4760    }
4761
4762    @Override
4763    public boolean isProtectedBroadcast(String actionName) {
4764        synchronized (mPackages) {
4765            if (mProtectedBroadcasts.contains(actionName)) {
4766                return true;
4767            } else if (actionName != null) {
4768                // TODO: remove these terrible hacks
4769                if (actionName.startsWith("android.net.netmon.lingerExpired")
4770                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4771                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4772                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4773                    return true;
4774                }
4775            }
4776        }
4777        return false;
4778    }
4779
4780    @Override
4781    public int checkSignatures(String pkg1, String pkg2) {
4782        synchronized (mPackages) {
4783            final PackageParser.Package p1 = mPackages.get(pkg1);
4784            final PackageParser.Package p2 = mPackages.get(pkg2);
4785            if (p1 == null || p1.mExtras == null
4786                    || p2 == null || p2.mExtras == null) {
4787                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4788            }
4789            return compareSignatures(p1.mSignatures, p2.mSignatures);
4790        }
4791    }
4792
4793    @Override
4794    public int checkUidSignatures(int uid1, int uid2) {
4795        // Map to base uids.
4796        uid1 = UserHandle.getAppId(uid1);
4797        uid2 = UserHandle.getAppId(uid2);
4798        // reader
4799        synchronized (mPackages) {
4800            Signature[] s1;
4801            Signature[] s2;
4802            Object obj = mSettings.getUserIdLPr(uid1);
4803            if (obj != null) {
4804                if (obj instanceof SharedUserSetting) {
4805                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4806                } else if (obj instanceof PackageSetting) {
4807                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4808                } else {
4809                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4810                }
4811            } else {
4812                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4813            }
4814            obj = mSettings.getUserIdLPr(uid2);
4815            if (obj != null) {
4816                if (obj instanceof SharedUserSetting) {
4817                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4818                } else if (obj instanceof PackageSetting) {
4819                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4820                } else {
4821                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4822                }
4823            } else {
4824                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4825            }
4826            return compareSignatures(s1, s2);
4827        }
4828    }
4829
4830    /**
4831     * This method should typically only be used when granting or revoking
4832     * permissions, since the app may immediately restart after this call.
4833     * <p>
4834     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4835     * guard your work against the app being relaunched.
4836     */
4837    private void killUid(int appId, int userId, String reason) {
4838        final long identity = Binder.clearCallingIdentity();
4839        try {
4840            IActivityManager am = ActivityManager.getService();
4841            if (am != null) {
4842                try {
4843                    am.killUid(appId, userId, reason);
4844                } catch (RemoteException e) {
4845                    /* ignore - same process */
4846                }
4847            }
4848        } finally {
4849            Binder.restoreCallingIdentity(identity);
4850        }
4851    }
4852
4853    /**
4854     * Compares two sets of signatures. Returns:
4855     * <br />
4856     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4857     * <br />
4858     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4859     * <br />
4860     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4861     * <br />
4862     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4863     * <br />
4864     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4865     */
4866    static int compareSignatures(Signature[] s1, Signature[] s2) {
4867        if (s1 == null) {
4868            return s2 == null
4869                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4870                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4871        }
4872
4873        if (s2 == null) {
4874            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4875        }
4876
4877        if (s1.length != s2.length) {
4878            return PackageManager.SIGNATURE_NO_MATCH;
4879        }
4880
4881        // Since both signature sets are of size 1, we can compare without HashSets.
4882        if (s1.length == 1) {
4883            return s1[0].equals(s2[0]) ?
4884                    PackageManager.SIGNATURE_MATCH :
4885                    PackageManager.SIGNATURE_NO_MATCH;
4886        }
4887
4888        ArraySet<Signature> set1 = new ArraySet<Signature>();
4889        for (Signature sig : s1) {
4890            set1.add(sig);
4891        }
4892        ArraySet<Signature> set2 = new ArraySet<Signature>();
4893        for (Signature sig : s2) {
4894            set2.add(sig);
4895        }
4896        // Make sure s2 contains all signatures in s1.
4897        if (set1.equals(set2)) {
4898            return PackageManager.SIGNATURE_MATCH;
4899        }
4900        return PackageManager.SIGNATURE_NO_MATCH;
4901    }
4902
4903    /**
4904     * If the database version for this type of package (internal storage or
4905     * external storage) is less than the version where package signatures
4906     * were updated, return true.
4907     */
4908    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4909        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4910        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4911    }
4912
4913    /**
4914     * Used for backward compatibility to make sure any packages with
4915     * certificate chains get upgraded to the new style. {@code existingSigs}
4916     * will be in the old format (since they were stored on disk from before the
4917     * system upgrade) and {@code scannedSigs} will be in the newer format.
4918     */
4919    private int compareSignaturesCompat(PackageSignatures existingSigs,
4920            PackageParser.Package scannedPkg) {
4921        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4922            return PackageManager.SIGNATURE_NO_MATCH;
4923        }
4924
4925        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4926        for (Signature sig : existingSigs.mSignatures) {
4927            existingSet.add(sig);
4928        }
4929        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4930        for (Signature sig : scannedPkg.mSignatures) {
4931            try {
4932                Signature[] chainSignatures = sig.getChainSignatures();
4933                for (Signature chainSig : chainSignatures) {
4934                    scannedCompatSet.add(chainSig);
4935                }
4936            } catch (CertificateEncodingException e) {
4937                scannedCompatSet.add(sig);
4938            }
4939        }
4940        /*
4941         * Make sure the expanded scanned set contains all signatures in the
4942         * existing one.
4943         */
4944        if (scannedCompatSet.equals(existingSet)) {
4945            // Migrate the old signatures to the new scheme.
4946            existingSigs.assignSignatures(scannedPkg.mSignatures);
4947            // The new KeySets will be re-added later in the scanning process.
4948            synchronized (mPackages) {
4949                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4950            }
4951            return PackageManager.SIGNATURE_MATCH;
4952        }
4953        return PackageManager.SIGNATURE_NO_MATCH;
4954    }
4955
4956    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4957        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4958        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4959    }
4960
4961    private int compareSignaturesRecover(PackageSignatures existingSigs,
4962            PackageParser.Package scannedPkg) {
4963        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4964            return PackageManager.SIGNATURE_NO_MATCH;
4965        }
4966
4967        String msg = null;
4968        try {
4969            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4970                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4971                        + scannedPkg.packageName);
4972                return PackageManager.SIGNATURE_MATCH;
4973            }
4974        } catch (CertificateException e) {
4975            msg = e.getMessage();
4976        }
4977
4978        logCriticalInfo(Log.INFO,
4979                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4980        return PackageManager.SIGNATURE_NO_MATCH;
4981    }
4982
4983    @Override
4984    public List<String> getAllPackages() {
4985        synchronized (mPackages) {
4986            return new ArrayList<String>(mPackages.keySet());
4987        }
4988    }
4989
4990    @Override
4991    public String[] getPackagesForUid(int uid) {
4992        final int userId = UserHandle.getUserId(uid);
4993        uid = UserHandle.getAppId(uid);
4994        // reader
4995        synchronized (mPackages) {
4996            Object obj = mSettings.getUserIdLPr(uid);
4997            if (obj instanceof SharedUserSetting) {
4998                final SharedUserSetting sus = (SharedUserSetting) obj;
4999                final int N = sus.packages.size();
5000                String[] res = new String[N];
5001                final Iterator<PackageSetting> it = sus.packages.iterator();
5002                int i = 0;
5003                while (it.hasNext()) {
5004                    PackageSetting ps = it.next();
5005                    if (ps.getInstalled(userId)) {
5006                        res[i++] = ps.name;
5007                    } else {
5008                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5009                    }
5010                }
5011                return res;
5012            } else if (obj instanceof PackageSetting) {
5013                final PackageSetting ps = (PackageSetting) obj;
5014                return new String[] { ps.name };
5015            }
5016        }
5017        return null;
5018    }
5019
5020    @Override
5021    public String getNameForUid(int uid) {
5022        // reader
5023        synchronized (mPackages) {
5024            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5025            if (obj instanceof SharedUserSetting) {
5026                final SharedUserSetting sus = (SharedUserSetting) obj;
5027                return sus.name + ":" + sus.userId;
5028            } else if (obj instanceof PackageSetting) {
5029                final PackageSetting ps = (PackageSetting) obj;
5030                return ps.name;
5031            }
5032        }
5033        return null;
5034    }
5035
5036    @Override
5037    public int getUidForSharedUser(String sharedUserName) {
5038        if(sharedUserName == null) {
5039            return -1;
5040        }
5041        // reader
5042        synchronized (mPackages) {
5043            SharedUserSetting suid;
5044            try {
5045                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5046                if (suid != null) {
5047                    return suid.userId;
5048                }
5049            } catch (PackageManagerException ignore) {
5050                // can't happen, but, still need to catch it
5051            }
5052            return -1;
5053        }
5054    }
5055
5056    @Override
5057    public int getFlagsForUid(int uid) {
5058        synchronized (mPackages) {
5059            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5060            if (obj instanceof SharedUserSetting) {
5061                final SharedUserSetting sus = (SharedUserSetting) obj;
5062                return sus.pkgFlags;
5063            } else if (obj instanceof PackageSetting) {
5064                final PackageSetting ps = (PackageSetting) obj;
5065                return ps.pkgFlags;
5066            }
5067        }
5068        return 0;
5069    }
5070
5071    @Override
5072    public int getPrivateFlagsForUid(int uid) {
5073        synchronized (mPackages) {
5074            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5075            if (obj instanceof SharedUserSetting) {
5076                final SharedUserSetting sus = (SharedUserSetting) obj;
5077                return sus.pkgPrivateFlags;
5078            } else if (obj instanceof PackageSetting) {
5079                final PackageSetting ps = (PackageSetting) obj;
5080                return ps.pkgPrivateFlags;
5081            }
5082        }
5083        return 0;
5084    }
5085
5086    @Override
5087    public boolean isUidPrivileged(int uid) {
5088        uid = UserHandle.getAppId(uid);
5089        // reader
5090        synchronized (mPackages) {
5091            Object obj = mSettings.getUserIdLPr(uid);
5092            if (obj instanceof SharedUserSetting) {
5093                final SharedUserSetting sus = (SharedUserSetting) obj;
5094                final Iterator<PackageSetting> it = sus.packages.iterator();
5095                while (it.hasNext()) {
5096                    if (it.next().isPrivileged()) {
5097                        return true;
5098                    }
5099                }
5100            } else if (obj instanceof PackageSetting) {
5101                final PackageSetting ps = (PackageSetting) obj;
5102                return ps.isPrivileged();
5103            }
5104        }
5105        return false;
5106    }
5107
5108    @Override
5109    public String[] getAppOpPermissionPackages(String permissionName) {
5110        synchronized (mPackages) {
5111            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5112            if (pkgs == null) {
5113                return null;
5114            }
5115            return pkgs.toArray(new String[pkgs.size()]);
5116        }
5117    }
5118
5119    @Override
5120    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5121            int flags, int userId) {
5122        try {
5123            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5124
5125            if (!sUserManager.exists(userId)) return null;
5126            flags = updateFlagsForResolve(flags, userId, intent);
5127            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5128                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5129
5130            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5131            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5132                    flags, userId);
5133            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5134
5135            final ResolveInfo bestChoice =
5136                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5137            return bestChoice;
5138        } finally {
5139            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5140        }
5141    }
5142
5143    @Override
5144    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5145        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5146            throw new SecurityException(
5147                    "findPersistentPreferredActivity can only be run by the system");
5148        }
5149        if (!sUserManager.exists(userId)) {
5150            return null;
5151        }
5152        intent = updateIntentForResolve(intent);
5153        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5154        final int flags = updateFlagsForResolve(0, userId, intent);
5155        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5156                userId);
5157        synchronized (mPackages) {
5158            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5159                    userId);
5160        }
5161    }
5162
5163    @Override
5164    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5165            IntentFilter filter, int match, ComponentName activity) {
5166        final int userId = UserHandle.getCallingUserId();
5167        if (DEBUG_PREFERRED) {
5168            Log.v(TAG, "setLastChosenActivity intent=" + intent
5169                + " resolvedType=" + resolvedType
5170                + " flags=" + flags
5171                + " filter=" + filter
5172                + " match=" + match
5173                + " activity=" + activity);
5174            filter.dump(new PrintStreamPrinter(System.out), "    ");
5175        }
5176        intent.setComponent(null);
5177        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5178                userId);
5179        // Find any earlier preferred or last chosen entries and nuke them
5180        findPreferredActivity(intent, resolvedType,
5181                flags, query, 0, false, true, false, userId);
5182        // Add the new activity as the last chosen for this filter
5183        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5184                "Setting last chosen");
5185    }
5186
5187    @Override
5188    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5189        final int userId = UserHandle.getCallingUserId();
5190        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5191        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5192                userId);
5193        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5194                false, false, false, userId);
5195    }
5196
5197    private boolean isEphemeralDisabled() {
5198        // ephemeral apps have been disabled across the board
5199        if (DISABLE_EPHEMERAL_APPS) {
5200            return true;
5201        }
5202        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5203        if (!mSystemReady) {
5204            return true;
5205        }
5206        // we can't get a content resolver until the system is ready; these checks must happen last
5207        final ContentResolver resolver = mContext.getContentResolver();
5208        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5209            return true;
5210        }
5211        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5212    }
5213
5214    private boolean isEphemeralAllowed(
5215            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5216            boolean skipPackageCheck) {
5217        // Short circuit and return early if possible.
5218        if (isEphemeralDisabled()) {
5219            return false;
5220        }
5221        final int callingUser = UserHandle.getCallingUserId();
5222        if (callingUser != UserHandle.USER_SYSTEM) {
5223            return false;
5224        }
5225        if (mEphemeralResolverConnection == null) {
5226            return false;
5227        }
5228        if (mEphemeralInstallerComponent == null) {
5229            return false;
5230        }
5231        if (intent.getComponent() != null) {
5232            return false;
5233        }
5234        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5235            return false;
5236        }
5237        if (!skipPackageCheck && intent.getPackage() != null) {
5238            return false;
5239        }
5240        final boolean isWebUri = hasWebURI(intent);
5241        if (!isWebUri || intent.getData().getHost() == null) {
5242            return false;
5243        }
5244        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5245        synchronized (mPackages) {
5246            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5247            for (int n = 0; n < count; n++) {
5248                ResolveInfo info = resolvedActivities.get(n);
5249                String packageName = info.activityInfo.packageName;
5250                PackageSetting ps = mSettings.mPackages.get(packageName);
5251                if (ps != null) {
5252                    // Try to get the status from User settings first
5253                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5254                    int status = (int) (packedStatus >> 32);
5255                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5256                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5257                        if (DEBUG_EPHEMERAL) {
5258                            Slog.v(TAG, "DENY ephemeral apps;"
5259                                + " pkg: " + packageName + ", status: " + status);
5260                        }
5261                        return false;
5262                    }
5263                }
5264            }
5265        }
5266        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5267        return true;
5268    }
5269
5270    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5271            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5272            int userId) {
5273        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5274                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5275                        callingPackage, userId));
5276        mHandler.sendMessage(msg);
5277    }
5278
5279    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5280            int flags, List<ResolveInfo> query, int userId) {
5281        if (query != null) {
5282            final int N = query.size();
5283            if (N == 1) {
5284                return query.get(0);
5285            } else if (N > 1) {
5286                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5287                // If there is more than one activity with the same priority,
5288                // then let the user decide between them.
5289                ResolveInfo r0 = query.get(0);
5290                ResolveInfo r1 = query.get(1);
5291                if (DEBUG_INTENT_MATCHING || debug) {
5292                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5293                            + r1.activityInfo.name + "=" + r1.priority);
5294                }
5295                // If the first activity has a higher priority, or a different
5296                // default, then it is always desirable to pick it.
5297                if (r0.priority != r1.priority
5298                        || r0.preferredOrder != r1.preferredOrder
5299                        || r0.isDefault != r1.isDefault) {
5300                    return query.get(0);
5301                }
5302                // If we have saved a preference for a preferred activity for
5303                // this Intent, use that.
5304                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5305                        flags, query, r0.priority, true, false, debug, userId);
5306                if (ri != null) {
5307                    return ri;
5308                }
5309                ri = new ResolveInfo(mResolveInfo);
5310                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5311                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5312                // If all of the options come from the same package, show the application's
5313                // label and icon instead of the generic resolver's.
5314                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5315                // and then throw away the ResolveInfo itself, meaning that the caller loses
5316                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5317                // a fallback for this case; we only set the target package's resources on
5318                // the ResolveInfo, not the ActivityInfo.
5319                final String intentPackage = intent.getPackage();
5320                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5321                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5322                    ri.resolvePackageName = intentPackage;
5323                    if (userNeedsBadging(userId)) {
5324                        ri.noResourceId = true;
5325                    } else {
5326                        ri.icon = appi.icon;
5327                    }
5328                    ri.iconResourceId = appi.icon;
5329                    ri.labelRes = appi.labelRes;
5330                }
5331                ri.activityInfo.applicationInfo = new ApplicationInfo(
5332                        ri.activityInfo.applicationInfo);
5333                if (userId != 0) {
5334                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5335                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5336                }
5337                // Make sure that the resolver is displayable in car mode
5338                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5339                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5340                return ri;
5341            }
5342        }
5343        return null;
5344    }
5345
5346    /**
5347     * Return true if the given list is not empty and all of its contents have
5348     * an activityInfo with the given package name.
5349     */
5350    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5351        if (ArrayUtils.isEmpty(list)) {
5352            return false;
5353        }
5354        for (int i = 0, N = list.size(); i < N; i++) {
5355            final ResolveInfo ri = list.get(i);
5356            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5357            if (ai == null || !packageName.equals(ai.packageName)) {
5358                return false;
5359            }
5360        }
5361        return true;
5362    }
5363
5364    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5365            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5366        final int N = query.size();
5367        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5368                .get(userId);
5369        // Get the list of persistent preferred activities that handle the intent
5370        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5371        List<PersistentPreferredActivity> pprefs = ppir != null
5372                ? ppir.queryIntent(intent, resolvedType,
5373                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5374                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5375                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5376                : null;
5377        if (pprefs != null && pprefs.size() > 0) {
5378            final int M = pprefs.size();
5379            for (int i=0; i<M; i++) {
5380                final PersistentPreferredActivity ppa = pprefs.get(i);
5381                if (DEBUG_PREFERRED || debug) {
5382                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5383                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5384                            + "\n  component=" + ppa.mComponent);
5385                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5386                }
5387                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5388                        flags | MATCH_DISABLED_COMPONENTS, userId);
5389                if (DEBUG_PREFERRED || debug) {
5390                    Slog.v(TAG, "Found persistent preferred activity:");
5391                    if (ai != null) {
5392                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5393                    } else {
5394                        Slog.v(TAG, "  null");
5395                    }
5396                }
5397                if (ai == null) {
5398                    // This previously registered persistent preferred activity
5399                    // component is no longer known. Ignore it and do NOT remove it.
5400                    continue;
5401                }
5402                for (int j=0; j<N; j++) {
5403                    final ResolveInfo ri = query.get(j);
5404                    if (!ri.activityInfo.applicationInfo.packageName
5405                            .equals(ai.applicationInfo.packageName)) {
5406                        continue;
5407                    }
5408                    if (!ri.activityInfo.name.equals(ai.name)) {
5409                        continue;
5410                    }
5411                    //  Found a persistent preference that can handle the intent.
5412                    if (DEBUG_PREFERRED || debug) {
5413                        Slog.v(TAG, "Returning persistent preferred activity: " +
5414                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5415                    }
5416                    return ri;
5417                }
5418            }
5419        }
5420        return null;
5421    }
5422
5423    // TODO: handle preferred activities missing while user has amnesia
5424    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5425            List<ResolveInfo> query, int priority, boolean always,
5426            boolean removeMatches, boolean debug, int userId) {
5427        if (!sUserManager.exists(userId)) return null;
5428        flags = updateFlagsForResolve(flags, userId, intent);
5429        intent = updateIntentForResolve(intent);
5430        // writer
5431        synchronized (mPackages) {
5432            // Try to find a matching persistent preferred activity.
5433            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5434                    debug, userId);
5435
5436            // If a persistent preferred activity matched, use it.
5437            if (pri != null) {
5438                return pri;
5439            }
5440
5441            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5442            // Get the list of preferred activities that handle the intent
5443            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5444            List<PreferredActivity> prefs = pir != null
5445                    ? pir.queryIntent(intent, resolvedType,
5446                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5447                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5448                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5449                    : null;
5450            if (prefs != null && prefs.size() > 0) {
5451                boolean changed = false;
5452                try {
5453                    // First figure out how good the original match set is.
5454                    // We will only allow preferred activities that came
5455                    // from the same match quality.
5456                    int match = 0;
5457
5458                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5459
5460                    final int N = query.size();
5461                    for (int j=0; j<N; j++) {
5462                        final ResolveInfo ri = query.get(j);
5463                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5464                                + ": 0x" + Integer.toHexString(match));
5465                        if (ri.match > match) {
5466                            match = ri.match;
5467                        }
5468                    }
5469
5470                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5471                            + Integer.toHexString(match));
5472
5473                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5474                    final int M = prefs.size();
5475                    for (int i=0; i<M; i++) {
5476                        final PreferredActivity pa = prefs.get(i);
5477                        if (DEBUG_PREFERRED || debug) {
5478                            Slog.v(TAG, "Checking PreferredActivity ds="
5479                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5480                                    + "\n  component=" + pa.mPref.mComponent);
5481                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5482                        }
5483                        if (pa.mPref.mMatch != match) {
5484                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5485                                    + Integer.toHexString(pa.mPref.mMatch));
5486                            continue;
5487                        }
5488                        // If it's not an "always" type preferred activity and that's what we're
5489                        // looking for, skip it.
5490                        if (always && !pa.mPref.mAlways) {
5491                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5492                            continue;
5493                        }
5494                        final ActivityInfo ai = getActivityInfo(
5495                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5496                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5497                                userId);
5498                        if (DEBUG_PREFERRED || debug) {
5499                            Slog.v(TAG, "Found preferred activity:");
5500                            if (ai != null) {
5501                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5502                            } else {
5503                                Slog.v(TAG, "  null");
5504                            }
5505                        }
5506                        if (ai == null) {
5507                            // This previously registered preferred activity
5508                            // component is no longer known.  Most likely an update
5509                            // to the app was installed and in the new version this
5510                            // component no longer exists.  Clean it up by removing
5511                            // it from the preferred activities list, and skip it.
5512                            Slog.w(TAG, "Removing dangling preferred activity: "
5513                                    + pa.mPref.mComponent);
5514                            pir.removeFilter(pa);
5515                            changed = true;
5516                            continue;
5517                        }
5518                        for (int j=0; j<N; j++) {
5519                            final ResolveInfo ri = query.get(j);
5520                            if (!ri.activityInfo.applicationInfo.packageName
5521                                    .equals(ai.applicationInfo.packageName)) {
5522                                continue;
5523                            }
5524                            if (!ri.activityInfo.name.equals(ai.name)) {
5525                                continue;
5526                            }
5527
5528                            if (removeMatches) {
5529                                pir.removeFilter(pa);
5530                                changed = true;
5531                                if (DEBUG_PREFERRED) {
5532                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5533                                }
5534                                break;
5535                            }
5536
5537                            // Okay we found a previously set preferred or last chosen app.
5538                            // If the result set is different from when this
5539                            // was created, we need to clear it and re-ask the
5540                            // user their preference, if we're looking for an "always" type entry.
5541                            if (always && !pa.mPref.sameSet(query)) {
5542                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5543                                        + intent + " type " + resolvedType);
5544                                if (DEBUG_PREFERRED) {
5545                                    Slog.v(TAG, "Removing preferred activity since set changed "
5546                                            + pa.mPref.mComponent);
5547                                }
5548                                pir.removeFilter(pa);
5549                                // Re-add the filter as a "last chosen" entry (!always)
5550                                PreferredActivity lastChosen = new PreferredActivity(
5551                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5552                                pir.addFilter(lastChosen);
5553                                changed = true;
5554                                return null;
5555                            }
5556
5557                            // Yay! Either the set matched or we're looking for the last chosen
5558                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5559                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5560                            return ri;
5561                        }
5562                    }
5563                } finally {
5564                    if (changed) {
5565                        if (DEBUG_PREFERRED) {
5566                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5567                        }
5568                        scheduleWritePackageRestrictionsLocked(userId);
5569                    }
5570                }
5571            }
5572        }
5573        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5574        return null;
5575    }
5576
5577    /*
5578     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5579     */
5580    @Override
5581    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5582            int targetUserId) {
5583        mContext.enforceCallingOrSelfPermission(
5584                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5585        List<CrossProfileIntentFilter> matches =
5586                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5587        if (matches != null) {
5588            int size = matches.size();
5589            for (int i = 0; i < size; i++) {
5590                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5591            }
5592        }
5593        if (hasWebURI(intent)) {
5594            // cross-profile app linking works only towards the parent.
5595            final UserInfo parent = getProfileParent(sourceUserId);
5596            synchronized(mPackages) {
5597                int flags = updateFlagsForResolve(0, parent.id, intent);
5598                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5599                        intent, resolvedType, flags, sourceUserId, parent.id);
5600                return xpDomainInfo != null;
5601            }
5602        }
5603        return false;
5604    }
5605
5606    private UserInfo getProfileParent(int userId) {
5607        final long identity = Binder.clearCallingIdentity();
5608        try {
5609            return sUserManager.getProfileParent(userId);
5610        } finally {
5611            Binder.restoreCallingIdentity(identity);
5612        }
5613    }
5614
5615    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5616            String resolvedType, int userId) {
5617        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5618        if (resolver != null) {
5619            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5620                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5621        }
5622        return null;
5623    }
5624
5625    @Override
5626    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5627            String resolvedType, int flags, int userId) {
5628        try {
5629            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5630
5631            return new ParceledListSlice<>(
5632                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5633        } finally {
5634            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5635        }
5636    }
5637
5638    /**
5639     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5640     * ephemeral, returns {@code null}.
5641     */
5642    private String getEphemeralPackageName(int callingUid) {
5643        final int appId = UserHandle.getAppId(callingUid);
5644        synchronized (mPackages) {
5645            final Object obj = mSettings.getUserIdLPr(appId);
5646            if (obj instanceof PackageSetting) {
5647                final PackageSetting ps = (PackageSetting) obj;
5648                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5649            }
5650        }
5651        return null;
5652    }
5653
5654    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5655            String resolvedType, int flags, int userId) {
5656        if (!sUserManager.exists(userId)) return Collections.emptyList();
5657        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5658        flags = updateFlagsForResolve(flags, userId, intent);
5659        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5660                false /* requireFullPermission */, false /* checkShell */,
5661                "query intent activities");
5662        ComponentName comp = intent.getComponent();
5663        if (comp == null) {
5664            if (intent.getSelector() != null) {
5665                intent = intent.getSelector();
5666                comp = intent.getComponent();
5667            }
5668        }
5669
5670        if (comp != null) {
5671            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5672            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5673            if (ai != null) {
5674                // When specifying an explicit component, we prevent the activity from being
5675                // used when either 1) the calling package is normal and the activity is within
5676                // an ephemeral application or 2) the calling package is ephemeral and the
5677                // activity is not visible to ephemeral applications.
5678                boolean matchEphemeral =
5679                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5680                boolean ephemeralVisibleOnly =
5681                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5682                boolean blockResolution =
5683                        (!matchEphemeral && ephemeralPkgName == null
5684                                && (ai.applicationInfo.privateFlags
5685                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5686                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5687                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5688                if (!blockResolution) {
5689                    final ResolveInfo ri = new ResolveInfo();
5690                    ri.activityInfo = ai;
5691                    list.add(ri);
5692                }
5693            }
5694            return list;
5695        }
5696
5697        // reader
5698        boolean sortResult = false;
5699        boolean addEphemeral = false;
5700        List<ResolveInfo> result;
5701        final String pkgName = intent.getPackage();
5702        synchronized (mPackages) {
5703            if (pkgName == null) {
5704                List<CrossProfileIntentFilter> matchingFilters =
5705                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5706                // Check for results that need to skip the current profile.
5707                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5708                        resolvedType, flags, userId);
5709                if (xpResolveInfo != null) {
5710                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5711                    xpResult.add(xpResolveInfo);
5712                    return filterForEphemeral(
5713                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5714                }
5715
5716                // Check for results in the current profile.
5717                result = filterIfNotSystemUser(mActivities.queryIntent(
5718                        intent, resolvedType, flags, userId), userId);
5719                addEphemeral =
5720                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5721
5722                // Check for cross profile results.
5723                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5724                xpResolveInfo = queryCrossProfileIntents(
5725                        matchingFilters, intent, resolvedType, flags, userId,
5726                        hasNonNegativePriorityResult);
5727                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5728                    boolean isVisibleToUser = filterIfNotSystemUser(
5729                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5730                    if (isVisibleToUser) {
5731                        result.add(xpResolveInfo);
5732                        sortResult = true;
5733                    }
5734                }
5735                if (hasWebURI(intent)) {
5736                    CrossProfileDomainInfo xpDomainInfo = null;
5737                    final UserInfo parent = getProfileParent(userId);
5738                    if (parent != null) {
5739                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5740                                flags, userId, parent.id);
5741                    }
5742                    if (xpDomainInfo != null) {
5743                        if (xpResolveInfo != null) {
5744                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5745                            // in the result.
5746                            result.remove(xpResolveInfo);
5747                        }
5748                        if (result.size() == 0 && !addEphemeral) {
5749                            // No result in current profile, but found candidate in parent user.
5750                            // And we are not going to add emphemeral app, so we can return the
5751                            // result straight away.
5752                            result.add(xpDomainInfo.resolveInfo);
5753                            return filterForEphemeral(result, ephemeralPkgName);
5754                        }
5755                    } else if (result.size() <= 1 && !addEphemeral) {
5756                        // No result in parent user and <= 1 result in current profile, and we
5757                        // are not going to add emphemeral app, so we can return the result without
5758                        // further processing.
5759                        return filterForEphemeral(result, ephemeralPkgName);
5760                    }
5761                    // We have more than one candidate (combining results from current and parent
5762                    // profile), so we need filtering and sorting.
5763                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5764                            intent, flags, result, xpDomainInfo, userId);
5765                    sortResult = true;
5766                }
5767            } else {
5768                final PackageParser.Package pkg = mPackages.get(pkgName);
5769                if (pkg != null) {
5770                    result = filterForEphemeral(filterIfNotSystemUser(
5771                            mActivities.queryIntentForPackage(
5772                                    intent, resolvedType, flags, pkg.activities, userId),
5773                            userId), ephemeralPkgName);
5774                } else {
5775                    // the caller wants to resolve for a particular package; however, there
5776                    // were no installed results, so, try to find an ephemeral result
5777                    addEphemeral = isEphemeralAllowed(
5778                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5779                    result = new ArrayList<ResolveInfo>();
5780                }
5781            }
5782        }
5783        if (addEphemeral) {
5784            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5785            final EphemeralRequest requestObject = new EphemeralRequest(
5786                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5787                    null /*launchIntent*/, null /*callingPackage*/, userId);
5788            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5789                    mContext, mEphemeralResolverConnection, requestObject);
5790            if (intentInfo != null) {
5791                if (DEBUG_EPHEMERAL) {
5792                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5793                }
5794                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5795                ephemeralInstaller.ephemeralResponse = intentInfo;
5796                // make sure this resolver is the default
5797                ephemeralInstaller.isDefault = true;
5798                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5799                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5800                // add a non-generic filter
5801                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5802                ephemeralInstaller.filter.addDataPath(
5803                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5804                result.add(ephemeralInstaller);
5805            }
5806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5807        }
5808        if (sortResult) {
5809            Collections.sort(result, mResolvePrioritySorter);
5810        }
5811        return filterForEphemeral(result, ephemeralPkgName);
5812    }
5813
5814    private static class CrossProfileDomainInfo {
5815        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5816        ResolveInfo resolveInfo;
5817        /* Best domain verification status of the activities found in the other profile */
5818        int bestDomainVerificationStatus;
5819    }
5820
5821    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5822            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5823        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5824                sourceUserId)) {
5825            return null;
5826        }
5827        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5828                resolvedType, flags, parentUserId);
5829
5830        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5831            return null;
5832        }
5833        CrossProfileDomainInfo result = null;
5834        int size = resultTargetUser.size();
5835        for (int i = 0; i < size; i++) {
5836            ResolveInfo riTargetUser = resultTargetUser.get(i);
5837            // Intent filter verification is only for filters that specify a host. So don't return
5838            // those that handle all web uris.
5839            if (riTargetUser.handleAllWebDataURI) {
5840                continue;
5841            }
5842            String packageName = riTargetUser.activityInfo.packageName;
5843            PackageSetting ps = mSettings.mPackages.get(packageName);
5844            if (ps == null) {
5845                continue;
5846            }
5847            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5848            int status = (int)(verificationState >> 32);
5849            if (result == null) {
5850                result = new CrossProfileDomainInfo();
5851                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5852                        sourceUserId, parentUserId);
5853                result.bestDomainVerificationStatus = status;
5854            } else {
5855                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5856                        result.bestDomainVerificationStatus);
5857            }
5858        }
5859        // Don't consider matches with status NEVER across profiles.
5860        if (result != null && result.bestDomainVerificationStatus
5861                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5862            return null;
5863        }
5864        return result;
5865    }
5866
5867    /**
5868     * Verification statuses are ordered from the worse to the best, except for
5869     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5870     */
5871    private int bestDomainVerificationStatus(int status1, int status2) {
5872        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5873            return status2;
5874        }
5875        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5876            return status1;
5877        }
5878        return (int) MathUtils.max(status1, status2);
5879    }
5880
5881    private boolean isUserEnabled(int userId) {
5882        long callingId = Binder.clearCallingIdentity();
5883        try {
5884            UserInfo userInfo = sUserManager.getUserInfo(userId);
5885            return userInfo != null && userInfo.isEnabled();
5886        } finally {
5887            Binder.restoreCallingIdentity(callingId);
5888        }
5889    }
5890
5891    /**
5892     * Filter out activities with systemUserOnly flag set, when current user is not System.
5893     *
5894     * @return filtered list
5895     */
5896    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5897        if (userId == UserHandle.USER_SYSTEM) {
5898            return resolveInfos;
5899        }
5900        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5901            ResolveInfo info = resolveInfos.get(i);
5902            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5903                resolveInfos.remove(i);
5904            }
5905        }
5906        return resolveInfos;
5907    }
5908
5909    /**
5910     * Filters out ephemeral activities.
5911     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5912     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5913     *
5914     * @param resolveInfos The pre-filtered list of resolved activities
5915     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5916     *          is performed.
5917     * @return A filtered list of resolved activities.
5918     */
5919    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5920            String ephemeralPkgName) {
5921        if (ephemeralPkgName == null) {
5922            return resolveInfos;
5923        }
5924        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5925            ResolveInfo info = resolveInfos.get(i);
5926            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5927            // allow activities that are defined in the provided package
5928            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5929                continue;
5930            }
5931            // allow activities that have been explicitly exposed to ephemeral apps
5932            if (!isEphemeralApp
5933                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5934                continue;
5935            }
5936            resolveInfos.remove(i);
5937        }
5938        return resolveInfos;
5939    }
5940
5941    /**
5942     * @param resolveInfos list of resolve infos in descending priority order
5943     * @return if the list contains a resolve info with non-negative priority
5944     */
5945    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5946        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5947    }
5948
5949    private static boolean hasWebURI(Intent intent) {
5950        if (intent.getData() == null) {
5951            return false;
5952        }
5953        final String scheme = intent.getScheme();
5954        if (TextUtils.isEmpty(scheme)) {
5955            return false;
5956        }
5957        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5958    }
5959
5960    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5961            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5962            int userId) {
5963        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5964
5965        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5966            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5967                    candidates.size());
5968        }
5969
5970        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5971        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5972        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5973        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5974        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5975        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5976
5977        synchronized (mPackages) {
5978            final int count = candidates.size();
5979            // First, try to use linked apps. Partition the candidates into four lists:
5980            // one for the final results, one for the "do not use ever", one for "undefined status"
5981            // and finally one for "browser app type".
5982            for (int n=0; n<count; n++) {
5983                ResolveInfo info = candidates.get(n);
5984                String packageName = info.activityInfo.packageName;
5985                PackageSetting ps = mSettings.mPackages.get(packageName);
5986                if (ps != null) {
5987                    // Add to the special match all list (Browser use case)
5988                    if (info.handleAllWebDataURI) {
5989                        matchAllList.add(info);
5990                        continue;
5991                    }
5992                    // Try to get the status from User settings first
5993                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5994                    int status = (int)(packedStatus >> 32);
5995                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5996                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5997                        if (DEBUG_DOMAIN_VERIFICATION) {
5998                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5999                                    + " : linkgen=" + linkGeneration);
6000                        }
6001                        // Use link-enabled generation as preferredOrder, i.e.
6002                        // prefer newly-enabled over earlier-enabled.
6003                        info.preferredOrder = linkGeneration;
6004                        alwaysList.add(info);
6005                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6006                        if (DEBUG_DOMAIN_VERIFICATION) {
6007                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6008                        }
6009                        neverList.add(info);
6010                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6011                        if (DEBUG_DOMAIN_VERIFICATION) {
6012                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6013                        }
6014                        alwaysAskList.add(info);
6015                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6016                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6017                        if (DEBUG_DOMAIN_VERIFICATION) {
6018                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6019                        }
6020                        undefinedList.add(info);
6021                    }
6022                }
6023            }
6024
6025            // We'll want to include browser possibilities in a few cases
6026            boolean includeBrowser = false;
6027
6028            // First try to add the "always" resolution(s) for the current user, if any
6029            if (alwaysList.size() > 0) {
6030                result.addAll(alwaysList);
6031            } else {
6032                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6033                result.addAll(undefinedList);
6034                // Maybe add one for the other profile.
6035                if (xpDomainInfo != null && (
6036                        xpDomainInfo.bestDomainVerificationStatus
6037                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6038                    result.add(xpDomainInfo.resolveInfo);
6039                }
6040                includeBrowser = true;
6041            }
6042
6043            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6044            // If there were 'always' entries their preferred order has been set, so we also
6045            // back that off to make the alternatives equivalent
6046            if (alwaysAskList.size() > 0) {
6047                for (ResolveInfo i : result) {
6048                    i.preferredOrder = 0;
6049                }
6050                result.addAll(alwaysAskList);
6051                includeBrowser = true;
6052            }
6053
6054            if (includeBrowser) {
6055                // Also add browsers (all of them or only the default one)
6056                if (DEBUG_DOMAIN_VERIFICATION) {
6057                    Slog.v(TAG, "   ...including browsers in candidate set");
6058                }
6059                if ((matchFlags & MATCH_ALL) != 0) {
6060                    result.addAll(matchAllList);
6061                } else {
6062                    // Browser/generic handling case.  If there's a default browser, go straight
6063                    // to that (but only if there is no other higher-priority match).
6064                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6065                    int maxMatchPrio = 0;
6066                    ResolveInfo defaultBrowserMatch = null;
6067                    final int numCandidates = matchAllList.size();
6068                    for (int n = 0; n < numCandidates; n++) {
6069                        ResolveInfo info = matchAllList.get(n);
6070                        // track the highest overall match priority...
6071                        if (info.priority > maxMatchPrio) {
6072                            maxMatchPrio = info.priority;
6073                        }
6074                        // ...and the highest-priority default browser match
6075                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6076                            if (defaultBrowserMatch == null
6077                                    || (defaultBrowserMatch.priority < info.priority)) {
6078                                if (debug) {
6079                                    Slog.v(TAG, "Considering default browser match " + info);
6080                                }
6081                                defaultBrowserMatch = info;
6082                            }
6083                        }
6084                    }
6085                    if (defaultBrowserMatch != null
6086                            && defaultBrowserMatch.priority >= maxMatchPrio
6087                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6088                    {
6089                        if (debug) {
6090                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6091                        }
6092                        result.add(defaultBrowserMatch);
6093                    } else {
6094                        result.addAll(matchAllList);
6095                    }
6096                }
6097
6098                // If there is nothing selected, add all candidates and remove the ones that the user
6099                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6100                if (result.size() == 0) {
6101                    result.addAll(candidates);
6102                    result.removeAll(neverList);
6103                }
6104            }
6105        }
6106        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6107            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6108                    result.size());
6109            for (ResolveInfo info : result) {
6110                Slog.v(TAG, "  + " + info.activityInfo);
6111            }
6112        }
6113        return result;
6114    }
6115
6116    // Returns a packed value as a long:
6117    //
6118    // high 'int'-sized word: link status: undefined/ask/never/always.
6119    // low 'int'-sized word: relative priority among 'always' results.
6120    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6121        long result = ps.getDomainVerificationStatusForUser(userId);
6122        // if none available, get the master status
6123        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6124            if (ps.getIntentFilterVerificationInfo() != null) {
6125                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6126            }
6127        }
6128        return result;
6129    }
6130
6131    private ResolveInfo querySkipCurrentProfileIntents(
6132            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6133            int flags, int sourceUserId) {
6134        if (matchingFilters != null) {
6135            int size = matchingFilters.size();
6136            for (int i = 0; i < size; i ++) {
6137                CrossProfileIntentFilter filter = matchingFilters.get(i);
6138                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6139                    // Checking if there are activities in the target user that can handle the
6140                    // intent.
6141                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6142                            resolvedType, flags, sourceUserId);
6143                    if (resolveInfo != null) {
6144                        return resolveInfo;
6145                    }
6146                }
6147            }
6148        }
6149        return null;
6150    }
6151
6152    // Return matching ResolveInfo in target user if any.
6153    private ResolveInfo queryCrossProfileIntents(
6154            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6155            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6156        if (matchingFilters != null) {
6157            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6158            // match the same intent. For performance reasons, it is better not to
6159            // run queryIntent twice for the same userId
6160            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6161            int size = matchingFilters.size();
6162            for (int i = 0; i < size; i++) {
6163                CrossProfileIntentFilter filter = matchingFilters.get(i);
6164                int targetUserId = filter.getTargetUserId();
6165                boolean skipCurrentProfile =
6166                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6167                boolean skipCurrentProfileIfNoMatchFound =
6168                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6169                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6170                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6171                    // Checking if there are activities in the target user that can handle the
6172                    // intent.
6173                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6174                            resolvedType, flags, sourceUserId);
6175                    if (resolveInfo != null) return resolveInfo;
6176                    alreadyTriedUserIds.put(targetUserId, true);
6177                }
6178            }
6179        }
6180        return null;
6181    }
6182
6183    /**
6184     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6185     * will forward the intent to the filter's target user.
6186     * Otherwise, returns null.
6187     */
6188    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6189            String resolvedType, int flags, int sourceUserId) {
6190        int targetUserId = filter.getTargetUserId();
6191        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6192                resolvedType, flags, targetUserId);
6193        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6194            // If all the matches in the target profile are suspended, return null.
6195            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6196                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6197                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6198                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6199                            targetUserId);
6200                }
6201            }
6202        }
6203        return null;
6204    }
6205
6206    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6207            int sourceUserId, int targetUserId) {
6208        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6209        long ident = Binder.clearCallingIdentity();
6210        boolean targetIsProfile;
6211        try {
6212            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6213        } finally {
6214            Binder.restoreCallingIdentity(ident);
6215        }
6216        String className;
6217        if (targetIsProfile) {
6218            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6219        } else {
6220            className = FORWARD_INTENT_TO_PARENT;
6221        }
6222        ComponentName forwardingActivityComponentName = new ComponentName(
6223                mAndroidApplication.packageName, className);
6224        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6225                sourceUserId);
6226        if (!targetIsProfile) {
6227            forwardingActivityInfo.showUserIcon = targetUserId;
6228            forwardingResolveInfo.noResourceId = true;
6229        }
6230        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6231        forwardingResolveInfo.priority = 0;
6232        forwardingResolveInfo.preferredOrder = 0;
6233        forwardingResolveInfo.match = 0;
6234        forwardingResolveInfo.isDefault = true;
6235        forwardingResolveInfo.filter = filter;
6236        forwardingResolveInfo.targetUserId = targetUserId;
6237        return forwardingResolveInfo;
6238    }
6239
6240    @Override
6241    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6242            Intent[] specifics, String[] specificTypes, Intent intent,
6243            String resolvedType, int flags, int userId) {
6244        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6245                specificTypes, intent, resolvedType, flags, userId));
6246    }
6247
6248    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6249            Intent[] specifics, String[] specificTypes, Intent intent,
6250            String resolvedType, int flags, int userId) {
6251        if (!sUserManager.exists(userId)) return Collections.emptyList();
6252        flags = updateFlagsForResolve(flags, userId, intent);
6253        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6254                false /* requireFullPermission */, false /* checkShell */,
6255                "query intent activity options");
6256        final String resultsAction = intent.getAction();
6257
6258        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6259                | PackageManager.GET_RESOLVED_FILTER, userId);
6260
6261        if (DEBUG_INTENT_MATCHING) {
6262            Log.v(TAG, "Query " + intent + ": " + results);
6263        }
6264
6265        int specificsPos = 0;
6266        int N;
6267
6268        // todo: note that the algorithm used here is O(N^2).  This
6269        // isn't a problem in our current environment, but if we start running
6270        // into situations where we have more than 5 or 10 matches then this
6271        // should probably be changed to something smarter...
6272
6273        // First we go through and resolve each of the specific items
6274        // that were supplied, taking care of removing any corresponding
6275        // duplicate items in the generic resolve list.
6276        if (specifics != null) {
6277            for (int i=0; i<specifics.length; i++) {
6278                final Intent sintent = specifics[i];
6279                if (sintent == null) {
6280                    continue;
6281                }
6282
6283                if (DEBUG_INTENT_MATCHING) {
6284                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6285                }
6286
6287                String action = sintent.getAction();
6288                if (resultsAction != null && resultsAction.equals(action)) {
6289                    // If this action was explicitly requested, then don't
6290                    // remove things that have it.
6291                    action = null;
6292                }
6293
6294                ResolveInfo ri = null;
6295                ActivityInfo ai = null;
6296
6297                ComponentName comp = sintent.getComponent();
6298                if (comp == null) {
6299                    ri = resolveIntent(
6300                        sintent,
6301                        specificTypes != null ? specificTypes[i] : null,
6302                            flags, userId);
6303                    if (ri == null) {
6304                        continue;
6305                    }
6306                    if (ri == mResolveInfo) {
6307                        // ACK!  Must do something better with this.
6308                    }
6309                    ai = ri.activityInfo;
6310                    comp = new ComponentName(ai.applicationInfo.packageName,
6311                            ai.name);
6312                } else {
6313                    ai = getActivityInfo(comp, flags, userId);
6314                    if (ai == null) {
6315                        continue;
6316                    }
6317                }
6318
6319                // Look for any generic query activities that are duplicates
6320                // of this specific one, and remove them from the results.
6321                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6322                N = results.size();
6323                int j;
6324                for (j=specificsPos; j<N; j++) {
6325                    ResolveInfo sri = results.get(j);
6326                    if ((sri.activityInfo.name.equals(comp.getClassName())
6327                            && sri.activityInfo.applicationInfo.packageName.equals(
6328                                    comp.getPackageName()))
6329                        || (action != null && sri.filter.matchAction(action))) {
6330                        results.remove(j);
6331                        if (DEBUG_INTENT_MATCHING) Log.v(
6332                            TAG, "Removing duplicate item from " + j
6333                            + " due to specific " + specificsPos);
6334                        if (ri == null) {
6335                            ri = sri;
6336                        }
6337                        j--;
6338                        N--;
6339                    }
6340                }
6341
6342                // Add this specific item to its proper place.
6343                if (ri == null) {
6344                    ri = new ResolveInfo();
6345                    ri.activityInfo = ai;
6346                }
6347                results.add(specificsPos, ri);
6348                ri.specificIndex = i;
6349                specificsPos++;
6350            }
6351        }
6352
6353        // Now we go through the remaining generic results and remove any
6354        // duplicate actions that are found here.
6355        N = results.size();
6356        for (int i=specificsPos; i<N-1; i++) {
6357            final ResolveInfo rii = results.get(i);
6358            if (rii.filter == null) {
6359                continue;
6360            }
6361
6362            // Iterate over all of the actions of this result's intent
6363            // filter...  typically this should be just one.
6364            final Iterator<String> it = rii.filter.actionsIterator();
6365            if (it == null) {
6366                continue;
6367            }
6368            while (it.hasNext()) {
6369                final String action = it.next();
6370                if (resultsAction != null && resultsAction.equals(action)) {
6371                    // If this action was explicitly requested, then don't
6372                    // remove things that have it.
6373                    continue;
6374                }
6375                for (int j=i+1; j<N; j++) {
6376                    final ResolveInfo rij = results.get(j);
6377                    if (rij.filter != null && rij.filter.hasAction(action)) {
6378                        results.remove(j);
6379                        if (DEBUG_INTENT_MATCHING) Log.v(
6380                            TAG, "Removing duplicate item from " + j
6381                            + " due to action " + action + " at " + i);
6382                        j--;
6383                        N--;
6384                    }
6385                }
6386            }
6387
6388            // If the caller didn't request filter information, drop it now
6389            // so we don't have to marshall/unmarshall it.
6390            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6391                rii.filter = null;
6392            }
6393        }
6394
6395        // Filter out the caller activity if so requested.
6396        if (caller != null) {
6397            N = results.size();
6398            for (int i=0; i<N; i++) {
6399                ActivityInfo ainfo = results.get(i).activityInfo;
6400                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6401                        && caller.getClassName().equals(ainfo.name)) {
6402                    results.remove(i);
6403                    break;
6404                }
6405            }
6406        }
6407
6408        // If the caller didn't request filter information,
6409        // drop them now so we don't have to
6410        // marshall/unmarshall it.
6411        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6412            N = results.size();
6413            for (int i=0; i<N; i++) {
6414                results.get(i).filter = null;
6415            }
6416        }
6417
6418        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6419        return results;
6420    }
6421
6422    @Override
6423    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6424            String resolvedType, int flags, int userId) {
6425        return new ParceledListSlice<>(
6426                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6427    }
6428
6429    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6430            String resolvedType, int flags, int userId) {
6431        if (!sUserManager.exists(userId)) return Collections.emptyList();
6432        flags = updateFlagsForResolve(flags, userId, intent);
6433        ComponentName comp = intent.getComponent();
6434        if (comp == null) {
6435            if (intent.getSelector() != null) {
6436                intent = intent.getSelector();
6437                comp = intent.getComponent();
6438            }
6439        }
6440        if (comp != null) {
6441            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6442            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6443            if (ai != null) {
6444                ResolveInfo ri = new ResolveInfo();
6445                ri.activityInfo = ai;
6446                list.add(ri);
6447            }
6448            return list;
6449        }
6450
6451        // reader
6452        synchronized (mPackages) {
6453            String pkgName = intent.getPackage();
6454            if (pkgName == null) {
6455                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6456            }
6457            final PackageParser.Package pkg = mPackages.get(pkgName);
6458            if (pkg != null) {
6459                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6460                        userId);
6461            }
6462            return Collections.emptyList();
6463        }
6464    }
6465
6466    @Override
6467    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6468        if (!sUserManager.exists(userId)) return null;
6469        flags = updateFlagsForResolve(flags, userId, intent);
6470        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6471        if (query != null) {
6472            if (query.size() >= 1) {
6473                // If there is more than one service with the same priority,
6474                // just arbitrarily pick the first one.
6475                return query.get(0);
6476            }
6477        }
6478        return null;
6479    }
6480
6481    @Override
6482    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6483            String resolvedType, int flags, int userId) {
6484        return new ParceledListSlice<>(
6485                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6486    }
6487
6488    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6489            String resolvedType, int flags, int userId) {
6490        if (!sUserManager.exists(userId)) return Collections.emptyList();
6491        flags = updateFlagsForResolve(flags, userId, intent);
6492        ComponentName comp = intent.getComponent();
6493        if (comp == null) {
6494            if (intent.getSelector() != null) {
6495                intent = intent.getSelector();
6496                comp = intent.getComponent();
6497            }
6498        }
6499        if (comp != null) {
6500            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6501            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6502            if (si != null) {
6503                final ResolveInfo ri = new ResolveInfo();
6504                ri.serviceInfo = si;
6505                list.add(ri);
6506            }
6507            return list;
6508        }
6509
6510        // reader
6511        synchronized (mPackages) {
6512            String pkgName = intent.getPackage();
6513            if (pkgName == null) {
6514                return mServices.queryIntent(intent, resolvedType, flags, userId);
6515            }
6516            final PackageParser.Package pkg = mPackages.get(pkgName);
6517            if (pkg != null) {
6518                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6519                        userId);
6520            }
6521            return Collections.emptyList();
6522        }
6523    }
6524
6525    @Override
6526    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6527            String resolvedType, int flags, int userId) {
6528        return new ParceledListSlice<>(
6529                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6530    }
6531
6532    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6533            Intent intent, String resolvedType, int flags, int userId) {
6534        if (!sUserManager.exists(userId)) return Collections.emptyList();
6535        flags = updateFlagsForResolve(flags, userId, intent);
6536        ComponentName comp = intent.getComponent();
6537        if (comp == null) {
6538            if (intent.getSelector() != null) {
6539                intent = intent.getSelector();
6540                comp = intent.getComponent();
6541            }
6542        }
6543        if (comp != null) {
6544            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6545            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6546            if (pi != null) {
6547                final ResolveInfo ri = new ResolveInfo();
6548                ri.providerInfo = pi;
6549                list.add(ri);
6550            }
6551            return list;
6552        }
6553
6554        // reader
6555        synchronized (mPackages) {
6556            String pkgName = intent.getPackage();
6557            if (pkgName == null) {
6558                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6559            }
6560            final PackageParser.Package pkg = mPackages.get(pkgName);
6561            if (pkg != null) {
6562                return mProviders.queryIntentForPackage(
6563                        intent, resolvedType, flags, pkg.providers, userId);
6564            }
6565            return Collections.emptyList();
6566        }
6567    }
6568
6569    @Override
6570    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6571        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6572        flags = updateFlagsForPackage(flags, userId, null);
6573        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6574        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6575                true /* requireFullPermission */, false /* checkShell */,
6576                "get installed packages");
6577
6578        // writer
6579        synchronized (mPackages) {
6580            ArrayList<PackageInfo> list;
6581            if (listUninstalled) {
6582                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6583                for (PackageSetting ps : mSettings.mPackages.values()) {
6584                    final PackageInfo pi;
6585                    if (ps.pkg != null) {
6586                        pi = generatePackageInfo(ps, flags, userId);
6587                    } else {
6588                        pi = generatePackageInfo(ps, flags, userId);
6589                    }
6590                    if (pi != null) {
6591                        list.add(pi);
6592                    }
6593                }
6594            } else {
6595                list = new ArrayList<PackageInfo>(mPackages.size());
6596                for (PackageParser.Package p : mPackages.values()) {
6597                    final PackageInfo pi =
6598                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6599                    if (pi != null) {
6600                        list.add(pi);
6601                    }
6602                }
6603            }
6604
6605            return new ParceledListSlice<PackageInfo>(list);
6606        }
6607    }
6608
6609    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6610            String[] permissions, boolean[] tmp, int flags, int userId) {
6611        int numMatch = 0;
6612        final PermissionsState permissionsState = ps.getPermissionsState();
6613        for (int i=0; i<permissions.length; i++) {
6614            final String permission = permissions[i];
6615            if (permissionsState.hasPermission(permission, userId)) {
6616                tmp[i] = true;
6617                numMatch++;
6618            } else {
6619                tmp[i] = false;
6620            }
6621        }
6622        if (numMatch == 0) {
6623            return;
6624        }
6625        final PackageInfo pi;
6626        if (ps.pkg != null) {
6627            pi = generatePackageInfo(ps, flags, userId);
6628        } else {
6629            pi = generatePackageInfo(ps, flags, userId);
6630        }
6631        // The above might return null in cases of uninstalled apps or install-state
6632        // skew across users/profiles.
6633        if (pi != null) {
6634            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6635                if (numMatch == permissions.length) {
6636                    pi.requestedPermissions = permissions;
6637                } else {
6638                    pi.requestedPermissions = new String[numMatch];
6639                    numMatch = 0;
6640                    for (int i=0; i<permissions.length; i++) {
6641                        if (tmp[i]) {
6642                            pi.requestedPermissions[numMatch] = permissions[i];
6643                            numMatch++;
6644                        }
6645                    }
6646                }
6647            }
6648            list.add(pi);
6649        }
6650    }
6651
6652    @Override
6653    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6654            String[] permissions, int flags, int userId) {
6655        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6656        flags = updateFlagsForPackage(flags, userId, permissions);
6657        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6658                true /* requireFullPermission */, false /* checkShell */,
6659                "get packages holding permissions");
6660        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6661
6662        // writer
6663        synchronized (mPackages) {
6664            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6665            boolean[] tmpBools = new boolean[permissions.length];
6666            if (listUninstalled) {
6667                for (PackageSetting ps : mSettings.mPackages.values()) {
6668                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6669                            userId);
6670                }
6671            } else {
6672                for (PackageParser.Package pkg : mPackages.values()) {
6673                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6674                    if (ps != null) {
6675                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6676                                userId);
6677                    }
6678                }
6679            }
6680
6681            return new ParceledListSlice<PackageInfo>(list);
6682        }
6683    }
6684
6685    @Override
6686    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6687        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6688        flags = updateFlagsForApplication(flags, userId, null);
6689        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6690
6691        // writer
6692        synchronized (mPackages) {
6693            ArrayList<ApplicationInfo> list;
6694            if (listUninstalled) {
6695                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6696                for (PackageSetting ps : mSettings.mPackages.values()) {
6697                    ApplicationInfo ai;
6698                    int effectiveFlags = flags;
6699                    if (ps.isSystem()) {
6700                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6701                    }
6702                    if (ps.pkg != null) {
6703                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6704                                ps.readUserState(userId), userId);
6705                    } else {
6706                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6707                                userId);
6708                    }
6709                    if (ai != null) {
6710                        list.add(ai);
6711                    }
6712                }
6713            } else {
6714                list = new ArrayList<ApplicationInfo>(mPackages.size());
6715                for (PackageParser.Package p : mPackages.values()) {
6716                    if (p.mExtras != null) {
6717                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6718                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6719                        if (ai != null) {
6720                            list.add(ai);
6721                        }
6722                    }
6723                }
6724            }
6725
6726            return new ParceledListSlice<ApplicationInfo>(list);
6727        }
6728    }
6729
6730    @Override
6731    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6732        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6733            return null;
6734        }
6735
6736        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6737                "getEphemeralApplications");
6738        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6739                true /* requireFullPermission */, false /* checkShell */,
6740                "getEphemeralApplications");
6741        synchronized (mPackages) {
6742            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6743                    .getEphemeralApplicationsLPw(userId);
6744            if (ephemeralApps != null) {
6745                return new ParceledListSlice<>(ephemeralApps);
6746            }
6747        }
6748        return null;
6749    }
6750
6751    @Override
6752    public boolean isEphemeralApplication(String packageName, int userId) {
6753        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6754                true /* requireFullPermission */, false /* checkShell */,
6755                "isEphemeral");
6756        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6757            return false;
6758        }
6759
6760        if (!isCallerSameApp(packageName)) {
6761            return false;
6762        }
6763        synchronized (mPackages) {
6764            PackageParser.Package pkg = mPackages.get(packageName);
6765            if (pkg != null) {
6766                return pkg.applicationInfo.isEphemeralApp();
6767            }
6768        }
6769        return false;
6770    }
6771
6772    @Override
6773    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6774        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6775            return null;
6776        }
6777
6778        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6779                true /* requireFullPermission */, false /* checkShell */,
6780                "getCookie");
6781        if (!isCallerSameApp(packageName)) {
6782            return null;
6783        }
6784        synchronized (mPackages) {
6785            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6786                    packageName, userId);
6787        }
6788    }
6789
6790    @Override
6791    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6792        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6793            return true;
6794        }
6795
6796        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6797                true /* requireFullPermission */, true /* checkShell */,
6798                "setCookie");
6799        if (!isCallerSameApp(packageName)) {
6800            return false;
6801        }
6802        synchronized (mPackages) {
6803            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6804                    packageName, cookie, userId);
6805        }
6806    }
6807
6808    @Override
6809    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6810        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6811            return null;
6812        }
6813
6814        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6815                "getEphemeralApplicationIcon");
6816        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6817                true /* requireFullPermission */, false /* checkShell */,
6818                "getEphemeralApplicationIcon");
6819        synchronized (mPackages) {
6820            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6821                    packageName, userId);
6822        }
6823    }
6824
6825    private boolean isCallerSameApp(String packageName) {
6826        PackageParser.Package pkg = mPackages.get(packageName);
6827        return pkg != null
6828                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6829    }
6830
6831    @Override
6832    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6833        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6834    }
6835
6836    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6837        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6838
6839        // reader
6840        synchronized (mPackages) {
6841            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6842            final int userId = UserHandle.getCallingUserId();
6843            while (i.hasNext()) {
6844                final PackageParser.Package p = i.next();
6845                if (p.applicationInfo == null) continue;
6846
6847                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6848                        && !p.applicationInfo.isDirectBootAware();
6849                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6850                        && p.applicationInfo.isDirectBootAware();
6851
6852                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6853                        && (!mSafeMode || isSystemApp(p))
6854                        && (matchesUnaware || matchesAware)) {
6855                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6856                    if (ps != null) {
6857                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6858                                ps.readUserState(userId), userId);
6859                        if (ai != null) {
6860                            finalList.add(ai);
6861                        }
6862                    }
6863                }
6864            }
6865        }
6866
6867        return finalList;
6868    }
6869
6870    @Override
6871    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6872        if (!sUserManager.exists(userId)) return null;
6873        flags = updateFlagsForComponent(flags, userId, name);
6874        // reader
6875        synchronized (mPackages) {
6876            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6877            PackageSetting ps = provider != null
6878                    ? mSettings.mPackages.get(provider.owner.packageName)
6879                    : null;
6880            return ps != null
6881                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6882                    ? PackageParser.generateProviderInfo(provider, flags,
6883                            ps.readUserState(userId), userId)
6884                    : null;
6885        }
6886    }
6887
6888    /**
6889     * @deprecated
6890     */
6891    @Deprecated
6892    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6893        // reader
6894        synchronized (mPackages) {
6895            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6896                    .entrySet().iterator();
6897            final int userId = UserHandle.getCallingUserId();
6898            while (i.hasNext()) {
6899                Map.Entry<String, PackageParser.Provider> entry = i.next();
6900                PackageParser.Provider p = entry.getValue();
6901                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6902
6903                if (ps != null && p.syncable
6904                        && (!mSafeMode || (p.info.applicationInfo.flags
6905                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6906                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6907                            ps.readUserState(userId), userId);
6908                    if (info != null) {
6909                        outNames.add(entry.getKey());
6910                        outInfo.add(info);
6911                    }
6912                }
6913            }
6914        }
6915    }
6916
6917    @Override
6918    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6919            int uid, int flags) {
6920        final int userId = processName != null ? UserHandle.getUserId(uid)
6921                : UserHandle.getCallingUserId();
6922        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6923        flags = updateFlagsForComponent(flags, userId, processName);
6924
6925        ArrayList<ProviderInfo> finalList = null;
6926        // reader
6927        synchronized (mPackages) {
6928            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6929            while (i.hasNext()) {
6930                final PackageParser.Provider p = i.next();
6931                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6932                if (ps != null && p.info.authority != null
6933                        && (processName == null
6934                                || (p.info.processName.equals(processName)
6935                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6936                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6937                    if (finalList == null) {
6938                        finalList = new ArrayList<ProviderInfo>(3);
6939                    }
6940                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6941                            ps.readUserState(userId), userId);
6942                    if (info != null) {
6943                        finalList.add(info);
6944                    }
6945                }
6946            }
6947        }
6948
6949        if (finalList != null) {
6950            Collections.sort(finalList, mProviderInitOrderSorter);
6951            return new ParceledListSlice<ProviderInfo>(finalList);
6952        }
6953
6954        return ParceledListSlice.emptyList();
6955    }
6956
6957    @Override
6958    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6959        // reader
6960        synchronized (mPackages) {
6961            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6962            return PackageParser.generateInstrumentationInfo(i, flags);
6963        }
6964    }
6965
6966    @Override
6967    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6968            String targetPackage, int flags) {
6969        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6970    }
6971
6972    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6973            int flags) {
6974        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6975
6976        // reader
6977        synchronized (mPackages) {
6978            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6979            while (i.hasNext()) {
6980                final PackageParser.Instrumentation p = i.next();
6981                if (targetPackage == null
6982                        || targetPackage.equals(p.info.targetPackage)) {
6983                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6984                            flags);
6985                    if (ii != null) {
6986                        finalList.add(ii);
6987                    }
6988                }
6989            }
6990        }
6991
6992        return finalList;
6993    }
6994
6995    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6996        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6997        if (overlays == null) {
6998            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6999            return;
7000        }
7001        for (PackageParser.Package opkg : overlays.values()) {
7002            // Not much to do if idmap fails: we already logged the error
7003            // and we certainly don't want to abort installation of pkg simply
7004            // because an overlay didn't fit properly. For these reasons,
7005            // ignore the return value of createIdmapForPackagePairLI.
7006            createIdmapForPackagePairLI(pkg, opkg);
7007        }
7008    }
7009
7010    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7011            PackageParser.Package opkg) {
7012        if (!opkg.mTrustedOverlay) {
7013            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7014                    opkg.baseCodePath + ": overlay not trusted");
7015            return false;
7016        }
7017        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7018        if (overlaySet == null) {
7019            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7020                    opkg.baseCodePath + " but target package has no known overlays");
7021            return false;
7022        }
7023        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7024        // TODO: generate idmap for split APKs
7025        try {
7026            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7027        } catch (InstallerException e) {
7028            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7029                    + opkg.baseCodePath);
7030            return false;
7031        }
7032        PackageParser.Package[] overlayArray =
7033            overlaySet.values().toArray(new PackageParser.Package[0]);
7034        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7035            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7036                return p1.mOverlayPriority - p2.mOverlayPriority;
7037            }
7038        };
7039        Arrays.sort(overlayArray, cmp);
7040
7041        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7042        int i = 0;
7043        for (PackageParser.Package p : overlayArray) {
7044            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7045        }
7046        return true;
7047    }
7048
7049    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7050        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7051        try {
7052            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7053        } finally {
7054            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7055        }
7056    }
7057
7058    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7059        final File[] files = dir.listFiles();
7060        if (ArrayUtils.isEmpty(files)) {
7061            Log.d(TAG, "No files in app dir " + dir);
7062            return;
7063        }
7064
7065        if (DEBUG_PACKAGE_SCANNING) {
7066            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7067                    + " flags=0x" + Integer.toHexString(parseFlags));
7068        }
7069        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7070                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7071
7072        // Submit files for parsing in parallel
7073        int fileCount = 0;
7074        for (File file : files) {
7075            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7076                    && !PackageInstallerService.isStageName(file.getName());
7077            if (!isPackage) {
7078                // Ignore entries which are not packages
7079                continue;
7080            }
7081            parallelPackageParser.submit(file, parseFlags);
7082            fileCount++;
7083        }
7084
7085        // Process results one by one
7086        for (; fileCount > 0; fileCount--) {
7087            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7088            Throwable throwable = parseResult.throwable;
7089            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7090
7091            if (throwable == null) {
7092                try {
7093                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7094                            currentTime, null);
7095                } catch (PackageManagerException e) {
7096                    errorCode = e.error;
7097                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7098                }
7099            } else if (throwable instanceof PackageParser.PackageParserException) {
7100                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7101                        throwable;
7102                errorCode = e.error;
7103                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7104            } else {
7105                throw new IllegalStateException("Unexpected exception occurred while parsing "
7106                        + parseResult.scanFile, throwable);
7107            }
7108
7109            // Delete invalid userdata apps
7110            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7111                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7112                logCriticalInfo(Log.WARN,
7113                        "Deleting invalid package at " + parseResult.scanFile);
7114                removeCodePathLI(parseResult.scanFile);
7115            }
7116        }
7117        parallelPackageParser.close();
7118    }
7119
7120    private static File getSettingsProblemFile() {
7121        File dataDir = Environment.getDataDirectory();
7122        File systemDir = new File(dataDir, "system");
7123        File fname = new File(systemDir, "uiderrors.txt");
7124        return fname;
7125    }
7126
7127    static void reportSettingsProblem(int priority, String msg) {
7128        logCriticalInfo(priority, msg);
7129    }
7130
7131    static void logCriticalInfo(int priority, String msg) {
7132        Slog.println(priority, TAG, msg);
7133        EventLogTags.writePmCriticalInfo(msg);
7134        try {
7135            File fname = getSettingsProblemFile();
7136            FileOutputStream out = new FileOutputStream(fname, true);
7137            PrintWriter pw = new FastPrintWriter(out);
7138            SimpleDateFormat formatter = new SimpleDateFormat();
7139            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7140            pw.println(dateString + ": " + msg);
7141            pw.close();
7142            FileUtils.setPermissions(
7143                    fname.toString(),
7144                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7145                    -1, -1);
7146        } catch (java.io.IOException e) {
7147        }
7148    }
7149
7150    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7151        if (srcFile.isDirectory()) {
7152            final File baseFile = new File(pkg.baseCodePath);
7153            long maxModifiedTime = baseFile.lastModified();
7154            if (pkg.splitCodePaths != null) {
7155                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7156                    final File splitFile = new File(pkg.splitCodePaths[i]);
7157                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7158                }
7159            }
7160            return maxModifiedTime;
7161        }
7162        return srcFile.lastModified();
7163    }
7164
7165    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7166            final int policyFlags) throws PackageManagerException {
7167        // When upgrading from pre-N MR1, verify the package time stamp using the package
7168        // directory and not the APK file.
7169        final long lastModifiedTime = mIsPreNMR1Upgrade
7170                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7171        if (ps != null
7172                && ps.codePath.equals(srcFile)
7173                && ps.timeStamp == lastModifiedTime
7174                && !isCompatSignatureUpdateNeeded(pkg)
7175                && !isRecoverSignatureUpdateNeeded(pkg)) {
7176            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7178            ArraySet<PublicKey> signingKs;
7179            synchronized (mPackages) {
7180                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7181            }
7182            if (ps.signatures.mSignatures != null
7183                    && ps.signatures.mSignatures.length != 0
7184                    && signingKs != null) {
7185                // Optimization: reuse the existing cached certificates
7186                // if the package appears to be unchanged.
7187                pkg.mSignatures = ps.signatures.mSignatures;
7188                pkg.mSigningKeys = signingKs;
7189                return;
7190            }
7191
7192            Slog.w(TAG, "PackageSetting for " + ps.name
7193                    + " is missing signatures.  Collecting certs again to recover them.");
7194        } else {
7195            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7196        }
7197
7198        try {
7199            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7200            PackageParser.collectCertificates(pkg, policyFlags);
7201        } catch (PackageParserException e) {
7202            throw PackageManagerException.from(e);
7203        } finally {
7204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7205        }
7206    }
7207
7208    /**
7209     *  Traces a package scan.
7210     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7211     */
7212    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7213            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7215        try {
7216            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7217        } finally {
7218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7219        }
7220    }
7221
7222    /**
7223     *  Scans a package and returns the newly parsed package.
7224     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7225     */
7226    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7227            long currentTime, UserHandle user) throws PackageManagerException {
7228        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7229        PackageParser pp = new PackageParser();
7230        pp.setSeparateProcesses(mSeparateProcesses);
7231        pp.setOnlyCoreApps(mOnlyCore);
7232        pp.setDisplayMetrics(mMetrics);
7233
7234        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7235            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7236        }
7237
7238        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7239        final PackageParser.Package pkg;
7240        try {
7241            pkg = pp.parsePackage(scanFile, parseFlags);
7242        } catch (PackageParserException e) {
7243            throw PackageManagerException.from(e);
7244        } finally {
7245            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7246        }
7247
7248        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7249    }
7250
7251    /**
7252     *  Scans a package and returns the newly parsed package.
7253     *  @throws PackageManagerException on a parse error.
7254     */
7255    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7256            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7257            throws PackageManagerException {
7258        // If the package has children and this is the first dive in the function
7259        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7260        // packages (parent and children) would be successfully scanned before the
7261        // actual scan since scanning mutates internal state and we want to atomically
7262        // install the package and its children.
7263        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7264            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7265                scanFlags |= SCAN_CHECK_ONLY;
7266            }
7267        } else {
7268            scanFlags &= ~SCAN_CHECK_ONLY;
7269        }
7270
7271        // Scan the parent
7272        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7273                scanFlags, currentTime, user);
7274
7275        // Scan the children
7276        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7277        for (int i = 0; i < childCount; i++) {
7278            PackageParser.Package childPackage = pkg.childPackages.get(i);
7279            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7280                    currentTime, user);
7281        }
7282
7283
7284        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7285            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7286        }
7287
7288        return scannedPkg;
7289    }
7290
7291    /**
7292     *  Scans a package and returns the newly parsed package.
7293     *  @throws PackageManagerException on a parse error.
7294     */
7295    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7296            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7297            throws PackageManagerException {
7298        PackageSetting ps = null;
7299        PackageSetting updatedPkg;
7300        // reader
7301        synchronized (mPackages) {
7302            // Look to see if we already know about this package.
7303            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7304            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7305                // This package has been renamed to its original name.  Let's
7306                // use that.
7307                ps = mSettings.getPackageLPr(oldName);
7308            }
7309            // If there was no original package, see one for the real package name.
7310            if (ps == null) {
7311                ps = mSettings.getPackageLPr(pkg.packageName);
7312            }
7313            // Check to see if this package could be hiding/updating a system
7314            // package.  Must look for it either under the original or real
7315            // package name depending on our state.
7316            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7317            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7318
7319            // If this is a package we don't know about on the system partition, we
7320            // may need to remove disabled child packages on the system partition
7321            // or may need to not add child packages if the parent apk is updated
7322            // on the data partition and no longer defines this child package.
7323            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7324                // If this is a parent package for an updated system app and this system
7325                // app got an OTA update which no longer defines some of the child packages
7326                // we have to prune them from the disabled system packages.
7327                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7328                if (disabledPs != null) {
7329                    final int scannedChildCount = (pkg.childPackages != null)
7330                            ? pkg.childPackages.size() : 0;
7331                    final int disabledChildCount = disabledPs.childPackageNames != null
7332                            ? disabledPs.childPackageNames.size() : 0;
7333                    for (int i = 0; i < disabledChildCount; i++) {
7334                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7335                        boolean disabledPackageAvailable = false;
7336                        for (int j = 0; j < scannedChildCount; j++) {
7337                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7338                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7339                                disabledPackageAvailable = true;
7340                                break;
7341                            }
7342                         }
7343                         if (!disabledPackageAvailable) {
7344                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7345                         }
7346                    }
7347                }
7348            }
7349        }
7350
7351        boolean updatedPkgBetter = false;
7352        // First check if this is a system package that may involve an update
7353        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7354            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7355            // it needs to drop FLAG_PRIVILEGED.
7356            if (locationIsPrivileged(scanFile)) {
7357                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7358            } else {
7359                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7360            }
7361
7362            if (ps != null && !ps.codePath.equals(scanFile)) {
7363                // The path has changed from what was last scanned...  check the
7364                // version of the new path against what we have stored to determine
7365                // what to do.
7366                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7367                if (pkg.mVersionCode <= ps.versionCode) {
7368                    // The system package has been updated and the code path does not match
7369                    // Ignore entry. Skip it.
7370                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7371                            + " ignored: updated version " + ps.versionCode
7372                            + " better than this " + pkg.mVersionCode);
7373                    if (!updatedPkg.codePath.equals(scanFile)) {
7374                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7375                                + ps.name + " changing from " + updatedPkg.codePathString
7376                                + " to " + scanFile);
7377                        updatedPkg.codePath = scanFile;
7378                        updatedPkg.codePathString = scanFile.toString();
7379                        updatedPkg.resourcePath = scanFile;
7380                        updatedPkg.resourcePathString = scanFile.toString();
7381                    }
7382                    updatedPkg.pkg = pkg;
7383                    updatedPkg.versionCode = pkg.mVersionCode;
7384
7385                    // Update the disabled system child packages to point to the package too.
7386                    final int childCount = updatedPkg.childPackageNames != null
7387                            ? updatedPkg.childPackageNames.size() : 0;
7388                    for (int i = 0; i < childCount; i++) {
7389                        String childPackageName = updatedPkg.childPackageNames.get(i);
7390                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7391                                childPackageName);
7392                        if (updatedChildPkg != null) {
7393                            updatedChildPkg.pkg = pkg;
7394                            updatedChildPkg.versionCode = pkg.mVersionCode;
7395                        }
7396                    }
7397
7398                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7399                            + scanFile + " ignored: updated version " + ps.versionCode
7400                            + " better than this " + pkg.mVersionCode);
7401                } else {
7402                    // The current app on the system partition is better than
7403                    // what we have updated to on the data partition; switch
7404                    // back to the system partition version.
7405                    // At this point, its safely assumed that package installation for
7406                    // apps in system partition will go through. If not there won't be a working
7407                    // version of the app
7408                    // writer
7409                    synchronized (mPackages) {
7410                        // Just remove the loaded entries from package lists.
7411                        mPackages.remove(ps.name);
7412                    }
7413
7414                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7415                            + " reverting from " + ps.codePathString
7416                            + ": new version " + pkg.mVersionCode
7417                            + " better than installed " + ps.versionCode);
7418
7419                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7420                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7421                    synchronized (mInstallLock) {
7422                        args.cleanUpResourcesLI();
7423                    }
7424                    synchronized (mPackages) {
7425                        mSettings.enableSystemPackageLPw(ps.name);
7426                    }
7427                    updatedPkgBetter = true;
7428                }
7429            }
7430        }
7431
7432        if (updatedPkg != null) {
7433            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7434            // initially
7435            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7436
7437            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7438            // flag set initially
7439            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7440                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7441            }
7442        }
7443
7444        // Verify certificates against what was last scanned
7445        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7446
7447        /*
7448         * A new system app appeared, but we already had a non-system one of the
7449         * same name installed earlier.
7450         */
7451        boolean shouldHideSystemApp = false;
7452        if (updatedPkg == null && ps != null
7453                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7454            /*
7455             * Check to make sure the signatures match first. If they don't,
7456             * wipe the installed application and its data.
7457             */
7458            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7459                    != PackageManager.SIGNATURE_MATCH) {
7460                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7461                        + " signatures don't match existing userdata copy; removing");
7462                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7463                        "scanPackageInternalLI")) {
7464                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7465                }
7466                ps = null;
7467            } else {
7468                /*
7469                 * If the newly-added system app is an older version than the
7470                 * already installed version, hide it. It will be scanned later
7471                 * and re-added like an update.
7472                 */
7473                if (pkg.mVersionCode <= ps.versionCode) {
7474                    shouldHideSystemApp = true;
7475                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7476                            + " but new version " + pkg.mVersionCode + " better than installed "
7477                            + ps.versionCode + "; hiding system");
7478                } else {
7479                    /*
7480                     * The newly found system app is a newer version that the
7481                     * one previously installed. Simply remove the
7482                     * already-installed application and replace it with our own
7483                     * while keeping the application data.
7484                     */
7485                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7486                            + " reverting from " + ps.codePathString + ": new version "
7487                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7488                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7489                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7490                    synchronized (mInstallLock) {
7491                        args.cleanUpResourcesLI();
7492                    }
7493                }
7494            }
7495        }
7496
7497        // The apk is forward locked (not public) if its code and resources
7498        // are kept in different files. (except for app in either system or
7499        // vendor path).
7500        // TODO grab this value from PackageSettings
7501        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7502            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7503                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7504            }
7505        }
7506
7507        // TODO: extend to support forward-locked splits
7508        String resourcePath = null;
7509        String baseResourcePath = null;
7510        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7511            if (ps != null && ps.resourcePathString != null) {
7512                resourcePath = ps.resourcePathString;
7513                baseResourcePath = ps.resourcePathString;
7514            } else {
7515                // Should not happen at all. Just log an error.
7516                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7517            }
7518        } else {
7519            resourcePath = pkg.codePath;
7520            baseResourcePath = pkg.baseCodePath;
7521        }
7522
7523        // Set application objects path explicitly.
7524        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7525        pkg.setApplicationInfoCodePath(pkg.codePath);
7526        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7527        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7528        pkg.setApplicationInfoResourcePath(resourcePath);
7529        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7530        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7531
7532        // Note that we invoke the following method only if we are about to unpack an application
7533        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7534                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7535
7536        /*
7537         * If the system app should be overridden by a previously installed
7538         * data, hide the system app now and let the /data/app scan pick it up
7539         * again.
7540         */
7541        if (shouldHideSystemApp) {
7542            synchronized (mPackages) {
7543                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7544            }
7545        }
7546
7547        return scannedPkg;
7548    }
7549
7550    private static String fixProcessName(String defProcessName,
7551            String processName) {
7552        if (processName == null) {
7553            return defProcessName;
7554        }
7555        return processName;
7556    }
7557
7558    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7559            throws PackageManagerException {
7560        if (pkgSetting.signatures.mSignatures != null) {
7561            // Already existing package. Make sure signatures match
7562            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7563                    == PackageManager.SIGNATURE_MATCH;
7564            if (!match) {
7565                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7566                        == PackageManager.SIGNATURE_MATCH;
7567            }
7568            if (!match) {
7569                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7570                        == PackageManager.SIGNATURE_MATCH;
7571            }
7572            if (!match) {
7573                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7574                        + pkg.packageName + " signatures do not match the "
7575                        + "previously installed version; ignoring!");
7576            }
7577        }
7578
7579        // Check for shared user signatures
7580        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7581            // Already existing package. Make sure signatures match
7582            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7583                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7584            if (!match) {
7585                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7586                        == PackageManager.SIGNATURE_MATCH;
7587            }
7588            if (!match) {
7589                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7590                        == PackageManager.SIGNATURE_MATCH;
7591            }
7592            if (!match) {
7593                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7594                        "Package " + pkg.packageName
7595                        + " has no signatures that match those in shared user "
7596                        + pkgSetting.sharedUser.name + "; ignoring!");
7597            }
7598        }
7599    }
7600
7601    /**
7602     * Enforces that only the system UID or root's UID can call a method exposed
7603     * via Binder.
7604     *
7605     * @param message used as message if SecurityException is thrown
7606     * @throws SecurityException if the caller is not system or root
7607     */
7608    private static final void enforceSystemOrRoot(String message) {
7609        final int uid = Binder.getCallingUid();
7610        if (uid != Process.SYSTEM_UID && uid != 0) {
7611            throw new SecurityException(message);
7612        }
7613    }
7614
7615    @Override
7616    public void performFstrimIfNeeded() {
7617        enforceSystemOrRoot("Only the system can request fstrim");
7618
7619        // Before everything else, see whether we need to fstrim.
7620        try {
7621            IStorageManager sm = PackageHelper.getStorageManager();
7622            if (sm != null) {
7623                boolean doTrim = false;
7624                final long interval = android.provider.Settings.Global.getLong(
7625                        mContext.getContentResolver(),
7626                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7627                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7628                if (interval > 0) {
7629                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7630                    if (timeSinceLast > interval) {
7631                        doTrim = true;
7632                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7633                                + "; running immediately");
7634                    }
7635                }
7636                if (doTrim) {
7637                    final boolean dexOptDialogShown;
7638                    synchronized (mPackages) {
7639                        dexOptDialogShown = mDexOptDialogShown;
7640                    }
7641                    if (!isFirstBoot() && dexOptDialogShown) {
7642                        try {
7643                            ActivityManager.getService().showBootMessage(
7644                                    mContext.getResources().getString(
7645                                            R.string.android_upgrading_fstrim), true);
7646                        } catch (RemoteException e) {
7647                        }
7648                    }
7649                    sm.runMaintenance();
7650                }
7651            } else {
7652                Slog.e(TAG, "storageManager service unavailable!");
7653            }
7654        } catch (RemoteException e) {
7655            // Can't happen; StorageManagerService is local
7656        }
7657    }
7658
7659    @Override
7660    public void updatePackagesIfNeeded() {
7661        enforceSystemOrRoot("Only the system can request package update");
7662
7663        // We need to re-extract after an OTA.
7664        boolean causeUpgrade = isUpgrade();
7665
7666        // First boot or factory reset.
7667        // Note: we also handle devices that are upgrading to N right now as if it is their
7668        //       first boot, as they do not have profile data.
7669        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7670
7671        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7672        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7673
7674        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7675            return;
7676        }
7677
7678        List<PackageParser.Package> pkgs;
7679        synchronized (mPackages) {
7680            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7681        }
7682
7683        final long startTime = System.nanoTime();
7684        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7685                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7686
7687        final int elapsedTimeSeconds =
7688                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7689
7690        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7691        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7692        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7693        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7694        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7695    }
7696
7697    /**
7698     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7699     * containing statistics about the invocation. The array consists of three elements,
7700     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7701     * and {@code numberOfPackagesFailed}.
7702     */
7703    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7704            String compilerFilter) {
7705
7706        int numberOfPackagesVisited = 0;
7707        int numberOfPackagesOptimized = 0;
7708        int numberOfPackagesSkipped = 0;
7709        int numberOfPackagesFailed = 0;
7710        final int numberOfPackagesToDexopt = pkgs.size();
7711
7712        for (PackageParser.Package pkg : pkgs) {
7713            numberOfPackagesVisited++;
7714
7715            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7716                if (DEBUG_DEXOPT) {
7717                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7718                }
7719                numberOfPackagesSkipped++;
7720                continue;
7721            }
7722
7723            if (DEBUG_DEXOPT) {
7724                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7725                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7726            }
7727
7728            if (showDialog) {
7729                try {
7730                    ActivityManager.getService().showBootMessage(
7731                            mContext.getResources().getString(R.string.android_upgrading_apk,
7732                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7733                } catch (RemoteException e) {
7734                }
7735                synchronized (mPackages) {
7736                    mDexOptDialogShown = true;
7737                }
7738            }
7739
7740            // If the OTA updates a system app which was previously preopted to a non-preopted state
7741            // the app might end up being verified at runtime. That's because by default the apps
7742            // are verify-profile but for preopted apps there's no profile.
7743            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7744            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7745            // filter (by default interpret-only).
7746            // Note that at this stage unused apps are already filtered.
7747            if (isSystemApp(pkg) &&
7748                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7749                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7750                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7751            }
7752
7753            // checkProfiles is false to avoid merging profiles during boot which
7754            // might interfere with background compilation (b/28612421).
7755            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7756            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7757            // trade-off worth doing to save boot time work.
7758            int dexOptStatus = performDexOptTraced(pkg.packageName,
7759                    false /* checkProfiles */,
7760                    compilerFilter,
7761                    false /* force */);
7762            switch (dexOptStatus) {
7763                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7764                    numberOfPackagesOptimized++;
7765                    break;
7766                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7767                    numberOfPackagesSkipped++;
7768                    break;
7769                case PackageDexOptimizer.DEX_OPT_FAILED:
7770                    numberOfPackagesFailed++;
7771                    break;
7772                default:
7773                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7774                    break;
7775            }
7776        }
7777
7778        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7779                numberOfPackagesFailed };
7780    }
7781
7782    @Override
7783    public void notifyPackageUse(String packageName, int reason) {
7784        synchronized (mPackages) {
7785            PackageParser.Package p = mPackages.get(packageName);
7786            if (p == null) {
7787                return;
7788            }
7789            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7790        }
7791    }
7792
7793    @Override
7794    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7795        int userId = UserHandle.getCallingUserId();
7796        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7797        if (ai == null) {
7798            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7799                + loadingPackageName + ", user=" + userId);
7800            return;
7801        }
7802        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7803    }
7804
7805    // TODO: this is not used nor needed. Delete it.
7806    @Override
7807    public boolean performDexOptIfNeeded(String packageName) {
7808        int dexOptStatus = performDexOptTraced(packageName,
7809                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7810        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7811    }
7812
7813    @Override
7814    public boolean performDexOpt(String packageName,
7815            boolean checkProfiles, int compileReason, boolean force) {
7816        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7817                getCompilerFilterForReason(compileReason), force);
7818        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7819    }
7820
7821    @Override
7822    public boolean performDexOptMode(String packageName,
7823            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7824        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7825                targetCompilerFilter, force);
7826        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7827    }
7828
7829    private int performDexOptTraced(String packageName,
7830                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7831        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7832        try {
7833            return performDexOptInternal(packageName, checkProfiles,
7834                    targetCompilerFilter, force);
7835        } finally {
7836            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7837        }
7838    }
7839
7840    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7841    // if the package can now be considered up to date for the given filter.
7842    private int performDexOptInternal(String packageName,
7843                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7844        PackageParser.Package p;
7845        synchronized (mPackages) {
7846            p = mPackages.get(packageName);
7847            if (p == null) {
7848                // Package could not be found. Report failure.
7849                return PackageDexOptimizer.DEX_OPT_FAILED;
7850            }
7851            mPackageUsage.maybeWriteAsync(mPackages);
7852            mCompilerStats.maybeWriteAsync();
7853        }
7854        long callingId = Binder.clearCallingIdentity();
7855        try {
7856            synchronized (mInstallLock) {
7857                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7858                        targetCompilerFilter, force);
7859            }
7860        } finally {
7861            Binder.restoreCallingIdentity(callingId);
7862        }
7863    }
7864
7865    public ArraySet<String> getOptimizablePackages() {
7866        ArraySet<String> pkgs = new ArraySet<String>();
7867        synchronized (mPackages) {
7868            for (PackageParser.Package p : mPackages.values()) {
7869                if (PackageDexOptimizer.canOptimizePackage(p)) {
7870                    pkgs.add(p.packageName);
7871                }
7872            }
7873        }
7874        return pkgs;
7875    }
7876
7877    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7878            boolean checkProfiles, String targetCompilerFilter,
7879            boolean force) {
7880        // Select the dex optimizer based on the force parameter.
7881        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7882        //       allocate an object here.
7883        PackageDexOptimizer pdo = force
7884                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7885                : mPackageDexOptimizer;
7886
7887        // Optimize all dependencies first. Note: we ignore the return value and march on
7888        // on errors.
7889        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7890        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7891        if (!deps.isEmpty()) {
7892            for (PackageParser.Package depPackage : deps) {
7893                // TODO: Analyze and investigate if we (should) profile libraries.
7894                // Currently this will do a full compilation of the library by default.
7895                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7896                        false /* checkProfiles */,
7897                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7898                        getOrCreateCompilerPackageStats(depPackage));
7899            }
7900        }
7901        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7902                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7903    }
7904
7905    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7906        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7907            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7908            Set<String> collectedNames = new HashSet<>();
7909            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7910
7911            retValue.remove(p);
7912
7913            return retValue;
7914        } else {
7915            return Collections.emptyList();
7916        }
7917    }
7918
7919    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7920            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7921        if (!collectedNames.contains(p.packageName)) {
7922            collectedNames.add(p.packageName);
7923            collected.add(p);
7924
7925            if (p.usesLibraries != null) {
7926                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7927            }
7928            if (p.usesOptionalLibraries != null) {
7929                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7930                        collectedNames);
7931            }
7932        }
7933    }
7934
7935    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7936            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7937        for (String libName : libs) {
7938            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7939            if (libPkg != null) {
7940                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7941            }
7942        }
7943    }
7944
7945    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7946        synchronized (mPackages) {
7947            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7948            if (lib != null && lib.apk != null) {
7949                return mPackages.get(lib.apk);
7950            }
7951        }
7952        return null;
7953    }
7954
7955    public void shutdown() {
7956        mPackageUsage.writeNow(mPackages);
7957        mCompilerStats.writeNow();
7958    }
7959
7960    @Override
7961    public void dumpProfiles(String packageName) {
7962        PackageParser.Package pkg;
7963        synchronized (mPackages) {
7964            pkg = mPackages.get(packageName);
7965            if (pkg == null) {
7966                throw new IllegalArgumentException("Unknown package: " + packageName);
7967            }
7968        }
7969        /* Only the shell, root, or the app user should be able to dump profiles. */
7970        int callingUid = Binder.getCallingUid();
7971        if (callingUid != Process.SHELL_UID &&
7972            callingUid != Process.ROOT_UID &&
7973            callingUid != pkg.applicationInfo.uid) {
7974            throw new SecurityException("dumpProfiles");
7975        }
7976
7977        synchronized (mInstallLock) {
7978            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7979            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7980            try {
7981                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7982                String codePaths = TextUtils.join(";", allCodePaths);
7983                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7984            } catch (InstallerException e) {
7985                Slog.w(TAG, "Failed to dump profiles", e);
7986            }
7987            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7988        }
7989    }
7990
7991    @Override
7992    public void forceDexOpt(String packageName) {
7993        enforceSystemOrRoot("forceDexOpt");
7994
7995        PackageParser.Package pkg;
7996        synchronized (mPackages) {
7997            pkg = mPackages.get(packageName);
7998            if (pkg == null) {
7999                throw new IllegalArgumentException("Unknown package: " + packageName);
8000            }
8001        }
8002
8003        synchronized (mInstallLock) {
8004            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8005
8006            // Whoever is calling forceDexOpt wants a fully compiled package.
8007            // Don't use profiles since that may cause compilation to be skipped.
8008            final int res = performDexOptInternalWithDependenciesLI(pkg,
8009                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8010                    true /* force */);
8011
8012            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8013            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8014                throw new IllegalStateException("Failed to dexopt: " + res);
8015            }
8016        }
8017    }
8018
8019    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8020        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8021            Slog.w(TAG, "Unable to update from " + oldPkg.name
8022                    + " to " + newPkg.packageName
8023                    + ": old package not in system partition");
8024            return false;
8025        } else if (mPackages.get(oldPkg.name) != null) {
8026            Slog.w(TAG, "Unable to update from " + oldPkg.name
8027                    + " to " + newPkg.packageName
8028                    + ": old package still exists");
8029            return false;
8030        }
8031        return true;
8032    }
8033
8034    void removeCodePathLI(File codePath) {
8035        if (codePath.isDirectory()) {
8036            try {
8037                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8038            } catch (InstallerException e) {
8039                Slog.w(TAG, "Failed to remove code path", e);
8040            }
8041        } else {
8042            codePath.delete();
8043        }
8044    }
8045
8046    private int[] resolveUserIds(int userId) {
8047        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8048    }
8049
8050    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8051        if (pkg == null) {
8052            Slog.wtf(TAG, "Package was null!", new Throwable());
8053            return;
8054        }
8055        clearAppDataLeafLIF(pkg, userId, flags);
8056        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8057        for (int i = 0; i < childCount; i++) {
8058            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8059        }
8060    }
8061
8062    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8063        final PackageSetting ps;
8064        synchronized (mPackages) {
8065            ps = mSettings.mPackages.get(pkg.packageName);
8066        }
8067        for (int realUserId : resolveUserIds(userId)) {
8068            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8069            try {
8070                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8071                        ceDataInode);
8072            } catch (InstallerException e) {
8073                Slog.w(TAG, String.valueOf(e));
8074            }
8075        }
8076    }
8077
8078    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8079        if (pkg == null) {
8080            Slog.wtf(TAG, "Package was null!", new Throwable());
8081            return;
8082        }
8083        destroyAppDataLeafLIF(pkg, userId, flags);
8084        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8085        for (int i = 0; i < childCount; i++) {
8086            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8087        }
8088    }
8089
8090    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8091        final PackageSetting ps;
8092        synchronized (mPackages) {
8093            ps = mSettings.mPackages.get(pkg.packageName);
8094        }
8095        for (int realUserId : resolveUserIds(userId)) {
8096            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8097            try {
8098                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8099                        ceDataInode);
8100            } catch (InstallerException e) {
8101                Slog.w(TAG, String.valueOf(e));
8102            }
8103        }
8104    }
8105
8106    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8107        if (pkg == null) {
8108            Slog.wtf(TAG, "Package was null!", new Throwable());
8109            return;
8110        }
8111        destroyAppProfilesLeafLIF(pkg);
8112        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8113        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8114        for (int i = 0; i < childCount; i++) {
8115            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8116            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8117                    true /* removeBaseMarker */);
8118        }
8119    }
8120
8121    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8122            boolean removeBaseMarker) {
8123        if (pkg.isForwardLocked()) {
8124            return;
8125        }
8126
8127        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8128            try {
8129                path = PackageManagerServiceUtils.realpath(new File(path));
8130            } catch (IOException e) {
8131                // TODO: Should we return early here ?
8132                Slog.w(TAG, "Failed to get canonical path", e);
8133                continue;
8134            }
8135
8136            final String useMarker = path.replace('/', '@');
8137            for (int realUserId : resolveUserIds(userId)) {
8138                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8139                if (removeBaseMarker) {
8140                    File foreignUseMark = new File(profileDir, useMarker);
8141                    if (foreignUseMark.exists()) {
8142                        if (!foreignUseMark.delete()) {
8143                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8144                                    + pkg.packageName);
8145                        }
8146                    }
8147                }
8148
8149                File[] markers = profileDir.listFiles();
8150                if (markers != null) {
8151                    final String searchString = "@" + pkg.packageName + "@";
8152                    // We also delete all markers that contain the package name we're
8153                    // uninstalling. These are associated with secondary dex-files belonging
8154                    // to the package. Reconstructing the path of these dex files is messy
8155                    // in general.
8156                    for (File marker : markers) {
8157                        if (marker.getName().indexOf(searchString) > 0) {
8158                            if (!marker.delete()) {
8159                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8160                                    + pkg.packageName);
8161                            }
8162                        }
8163                    }
8164                }
8165            }
8166        }
8167    }
8168
8169    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8170        try {
8171            mInstaller.destroyAppProfiles(pkg.packageName);
8172        } catch (InstallerException e) {
8173            Slog.w(TAG, String.valueOf(e));
8174        }
8175    }
8176
8177    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8178        if (pkg == null) {
8179            Slog.wtf(TAG, "Package was null!", new Throwable());
8180            return;
8181        }
8182        clearAppProfilesLeafLIF(pkg);
8183        // We don't remove the base foreign use marker when clearing profiles because
8184        // we will rename it when the app is updated. Unlike the actual profile contents,
8185        // the foreign use marker is good across installs.
8186        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8187        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8188        for (int i = 0; i < childCount; i++) {
8189            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8190        }
8191    }
8192
8193    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8194        try {
8195            mInstaller.clearAppProfiles(pkg.packageName);
8196        } catch (InstallerException e) {
8197            Slog.w(TAG, String.valueOf(e));
8198        }
8199    }
8200
8201    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8202            long lastUpdateTime) {
8203        // Set parent install/update time
8204        PackageSetting ps = (PackageSetting) pkg.mExtras;
8205        if (ps != null) {
8206            ps.firstInstallTime = firstInstallTime;
8207            ps.lastUpdateTime = lastUpdateTime;
8208        }
8209        // Set children install/update time
8210        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8211        for (int i = 0; i < childCount; i++) {
8212            PackageParser.Package childPkg = pkg.childPackages.get(i);
8213            ps = (PackageSetting) childPkg.mExtras;
8214            if (ps != null) {
8215                ps.firstInstallTime = firstInstallTime;
8216                ps.lastUpdateTime = lastUpdateTime;
8217            }
8218        }
8219    }
8220
8221    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8222            PackageParser.Package changingLib) {
8223        if (file.path != null) {
8224            usesLibraryFiles.add(file.path);
8225            return;
8226        }
8227        PackageParser.Package p = mPackages.get(file.apk);
8228        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8229            // If we are doing this while in the middle of updating a library apk,
8230            // then we need to make sure to use that new apk for determining the
8231            // dependencies here.  (We haven't yet finished committing the new apk
8232            // to the package manager state.)
8233            if (p == null || p.packageName.equals(changingLib.packageName)) {
8234                p = changingLib;
8235            }
8236        }
8237        if (p != null) {
8238            usesLibraryFiles.addAll(p.getAllCodePaths());
8239        }
8240    }
8241
8242    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8243            PackageParser.Package changingLib) throws PackageManagerException {
8244        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8245            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8246            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8247            for (int i=0; i<N; i++) {
8248                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8249                if (file == null) {
8250                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8251                            "Package " + pkg.packageName + " requires unavailable shared library "
8252                            + pkg.usesLibraries.get(i) + "; failing!");
8253                }
8254                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8255            }
8256            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8257            for (int i=0; i<N; i++) {
8258                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8259                if (file == null) {
8260                    Slog.w(TAG, "Package " + pkg.packageName
8261                            + " desires unavailable shared library "
8262                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8263                } else {
8264                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8265                }
8266            }
8267            N = usesLibraryFiles.size();
8268            if (N > 0) {
8269                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8270            } else {
8271                pkg.usesLibraryFiles = null;
8272            }
8273        }
8274    }
8275
8276    private static boolean hasString(List<String> list, List<String> which) {
8277        if (list == null) {
8278            return false;
8279        }
8280        for (int i=list.size()-1; i>=0; i--) {
8281            for (int j=which.size()-1; j>=0; j--) {
8282                if (which.get(j).equals(list.get(i))) {
8283                    return true;
8284                }
8285            }
8286        }
8287        return false;
8288    }
8289
8290    private void updateAllSharedLibrariesLPw() {
8291        for (PackageParser.Package pkg : mPackages.values()) {
8292            try {
8293                updateSharedLibrariesLPr(pkg, null);
8294            } catch (PackageManagerException e) {
8295                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8296            }
8297        }
8298    }
8299
8300    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8301            PackageParser.Package changingPkg) {
8302        ArrayList<PackageParser.Package> res = null;
8303        for (PackageParser.Package pkg : mPackages.values()) {
8304            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8305                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8306                if (res == null) {
8307                    res = new ArrayList<PackageParser.Package>();
8308                }
8309                res.add(pkg);
8310                try {
8311                    updateSharedLibrariesLPr(pkg, changingPkg);
8312                } catch (PackageManagerException e) {
8313                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8314                }
8315            }
8316        }
8317        return res;
8318    }
8319
8320    /**
8321     * Derive the value of the {@code cpuAbiOverride} based on the provided
8322     * value and an optional stored value from the package settings.
8323     */
8324    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8325        String cpuAbiOverride = null;
8326
8327        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8328            cpuAbiOverride = null;
8329        } else if (abiOverride != null) {
8330            cpuAbiOverride = abiOverride;
8331        } else if (settings != null) {
8332            cpuAbiOverride = settings.cpuAbiOverrideString;
8333        }
8334
8335        return cpuAbiOverride;
8336    }
8337
8338    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8339            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8340                    throws PackageManagerException {
8341        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8342        // If the package has children and this is the first dive in the function
8343        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8344        // whether all packages (parent and children) would be successfully scanned
8345        // before the actual scan since scanning mutates internal state and we want
8346        // to atomically install the package and its children.
8347        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8348            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8349                scanFlags |= SCAN_CHECK_ONLY;
8350            }
8351        } else {
8352            scanFlags &= ~SCAN_CHECK_ONLY;
8353        }
8354
8355        final PackageParser.Package scannedPkg;
8356        try {
8357            // Scan the parent
8358            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8359            // Scan the children
8360            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8361            for (int i = 0; i < childCount; i++) {
8362                PackageParser.Package childPkg = pkg.childPackages.get(i);
8363                scanPackageLI(childPkg, policyFlags,
8364                        scanFlags, currentTime, user);
8365            }
8366        } finally {
8367            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8368        }
8369
8370        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8371            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8372        }
8373
8374        return scannedPkg;
8375    }
8376
8377    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8378            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8379        boolean success = false;
8380        try {
8381            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8382                    currentTime, user);
8383            success = true;
8384            return res;
8385        } finally {
8386            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8387                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8388                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8389                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8390                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8391            }
8392        }
8393    }
8394
8395    /**
8396     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8397     */
8398    private static boolean apkHasCode(String fileName) {
8399        StrictJarFile jarFile = null;
8400        try {
8401            jarFile = new StrictJarFile(fileName,
8402                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8403            return jarFile.findEntry("classes.dex") != null;
8404        } catch (IOException ignore) {
8405        } finally {
8406            try {
8407                if (jarFile != null) {
8408                    jarFile.close();
8409                }
8410            } catch (IOException ignore) {}
8411        }
8412        return false;
8413    }
8414
8415    /**
8416     * Enforces code policy for the package. This ensures that if an APK has
8417     * declared hasCode="true" in its manifest that the APK actually contains
8418     * code.
8419     *
8420     * @throws PackageManagerException If bytecode could not be found when it should exist
8421     */
8422    private static void assertCodePolicy(PackageParser.Package pkg)
8423            throws PackageManagerException {
8424        final boolean shouldHaveCode =
8425                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8426        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8427            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8428                    "Package " + pkg.baseCodePath + " code is missing");
8429        }
8430
8431        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8432            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8433                final boolean splitShouldHaveCode =
8434                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8435                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8436                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8437                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8438                }
8439            }
8440        }
8441    }
8442
8443    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8444            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8445                    throws PackageManagerException {
8446        if (DEBUG_PACKAGE_SCANNING) {
8447            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8448                Log.d(TAG, "Scanning package " + pkg.packageName);
8449        }
8450
8451        applyPolicy(pkg, policyFlags);
8452
8453        assertPackageIsValid(pkg, policyFlags, scanFlags);
8454
8455        // Initialize package source and resource directories
8456        final File scanFile = new File(pkg.codePath);
8457        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8458        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8459
8460        SharedUserSetting suid = null;
8461        PackageSetting pkgSetting = null;
8462
8463        // Getting the package setting may have a side-effect, so if we
8464        // are only checking if scan would succeed, stash a copy of the
8465        // old setting to restore at the end.
8466        PackageSetting nonMutatedPs = null;
8467
8468        // We keep references to the derived CPU Abis from settings in oder to reuse
8469        // them in the case where we're not upgrading or booting for the first time.
8470        String primaryCpuAbiFromSettings = null;
8471        String secondaryCpuAbiFromSettings = null;
8472
8473        // writer
8474        synchronized (mPackages) {
8475            if (pkg.mSharedUserId != null) {
8476                // SIDE EFFECTS; may potentially allocate a new shared user
8477                suid = mSettings.getSharedUserLPw(
8478                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8479                if (DEBUG_PACKAGE_SCANNING) {
8480                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8481                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8482                                + "): packages=" + suid.packages);
8483                }
8484            }
8485
8486            // Check if we are renaming from an original package name.
8487            PackageSetting origPackage = null;
8488            String realName = null;
8489            if (pkg.mOriginalPackages != null) {
8490                // This package may need to be renamed to a previously
8491                // installed name.  Let's check on that...
8492                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8493                if (pkg.mOriginalPackages.contains(renamed)) {
8494                    // This package had originally been installed as the
8495                    // original name, and we have already taken care of
8496                    // transitioning to the new one.  Just update the new
8497                    // one to continue using the old name.
8498                    realName = pkg.mRealPackage;
8499                    if (!pkg.packageName.equals(renamed)) {
8500                        // Callers into this function may have already taken
8501                        // care of renaming the package; only do it here if
8502                        // it is not already done.
8503                        pkg.setPackageName(renamed);
8504                    }
8505                } else {
8506                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8507                        if ((origPackage = mSettings.getPackageLPr(
8508                                pkg.mOriginalPackages.get(i))) != null) {
8509                            // We do have the package already installed under its
8510                            // original name...  should we use it?
8511                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8512                                // New package is not compatible with original.
8513                                origPackage = null;
8514                                continue;
8515                            } else if (origPackage.sharedUser != null) {
8516                                // Make sure uid is compatible between packages.
8517                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8518                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8519                                            + " to " + pkg.packageName + ": old uid "
8520                                            + origPackage.sharedUser.name
8521                                            + " differs from " + pkg.mSharedUserId);
8522                                    origPackage = null;
8523                                    continue;
8524                                }
8525                                // TODO: Add case when shared user id is added [b/28144775]
8526                            } else {
8527                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8528                                        + pkg.packageName + " to old name " + origPackage.name);
8529                            }
8530                            break;
8531                        }
8532                    }
8533                }
8534            }
8535
8536            if (mTransferedPackages.contains(pkg.packageName)) {
8537                Slog.w(TAG, "Package " + pkg.packageName
8538                        + " was transferred to another, but its .apk remains");
8539            }
8540
8541            // See comments in nonMutatedPs declaration
8542            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8543                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8544                if (foundPs != null) {
8545                    nonMutatedPs = new PackageSetting(foundPs);
8546                }
8547            }
8548
8549            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8550                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8551                if (foundPs != null) {
8552                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8553                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8554                }
8555            }
8556
8557            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8558            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8559                PackageManagerService.reportSettingsProblem(Log.WARN,
8560                        "Package " + pkg.packageName + " shared user changed from "
8561                                + (pkgSetting.sharedUser != null
8562                                        ? pkgSetting.sharedUser.name : "<nothing>")
8563                                + " to "
8564                                + (suid != null ? suid.name : "<nothing>")
8565                                + "; replacing with new");
8566                pkgSetting = null;
8567            }
8568            final PackageSetting oldPkgSetting =
8569                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8570            final PackageSetting disabledPkgSetting =
8571                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8572            if (pkgSetting == null) {
8573                final String parentPackageName = (pkg.parentPackage != null)
8574                        ? pkg.parentPackage.packageName : null;
8575                // REMOVE SharedUserSetting from method; update in a separate call
8576                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8577                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8578                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8579                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8580                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8581                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8582                        UserManagerService.getInstance());
8583                // SIDE EFFECTS; updates system state; move elsewhere
8584                if (origPackage != null) {
8585                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8586                }
8587                mSettings.addUserToSettingLPw(pkgSetting);
8588            } else {
8589                // REMOVE SharedUserSetting from method; update in a separate call.
8590                //
8591                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8592                // secondaryCpuAbi are not known at this point so we always update them
8593                // to null here, only to reset them at a later point.
8594                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8595                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8596                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8597                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8598                        UserManagerService.getInstance());
8599            }
8600            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8601            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8602
8603            // SIDE EFFECTS; modifies system state; move elsewhere
8604            if (pkgSetting.origPackage != null) {
8605                // If we are first transitioning from an original package,
8606                // fix up the new package's name now.  We need to do this after
8607                // looking up the package under its new name, so getPackageLP
8608                // can take care of fiddling things correctly.
8609                pkg.setPackageName(origPackage.name);
8610
8611                // File a report about this.
8612                String msg = "New package " + pkgSetting.realName
8613                        + " renamed to replace old package " + pkgSetting.name;
8614                reportSettingsProblem(Log.WARN, msg);
8615
8616                // Make a note of it.
8617                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8618                    mTransferedPackages.add(origPackage.name);
8619                }
8620
8621                // No longer need to retain this.
8622                pkgSetting.origPackage = null;
8623            }
8624
8625            // SIDE EFFECTS; modifies system state; move elsewhere
8626            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8627                // Make a note of it.
8628                mTransferedPackages.add(pkg.packageName);
8629            }
8630
8631            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8632                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8633            }
8634
8635            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8636                // Check all shared libraries and map to their actual file path.
8637                // We only do this here for apps not on a system dir, because those
8638                // are the only ones that can fail an install due to this.  We
8639                // will take care of the system apps by updating all of their
8640                // library paths after the scan is done.
8641                updateSharedLibrariesLPr(pkg, null);
8642            }
8643
8644            if (mFoundPolicyFile) {
8645                SELinuxMMAC.assignSeinfoValue(pkg);
8646            }
8647
8648            pkg.applicationInfo.uid = pkgSetting.appId;
8649            pkg.mExtras = pkgSetting;
8650            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8651                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8652                    // We just determined the app is signed correctly, so bring
8653                    // over the latest parsed certs.
8654                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8655                } else {
8656                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8657                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8658                                "Package " + pkg.packageName + " upgrade keys do not match the "
8659                                + "previously installed version");
8660                    } else {
8661                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8662                        String msg = "System package " + pkg.packageName
8663                                + " signature changed; retaining data.";
8664                        reportSettingsProblem(Log.WARN, msg);
8665                    }
8666                }
8667            } else {
8668                try {
8669                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8670                    verifySignaturesLP(pkgSetting, pkg);
8671                    // We just determined the app is signed correctly, so bring
8672                    // over the latest parsed certs.
8673                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8674                } catch (PackageManagerException e) {
8675                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8676                        throw e;
8677                    }
8678                    // The signature has changed, but this package is in the system
8679                    // image...  let's recover!
8680                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8681                    // However...  if this package is part of a shared user, but it
8682                    // doesn't match the signature of the shared user, let's fail.
8683                    // What this means is that you can't change the signatures
8684                    // associated with an overall shared user, which doesn't seem all
8685                    // that unreasonable.
8686                    if (pkgSetting.sharedUser != null) {
8687                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8688                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8689                            throw new PackageManagerException(
8690                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8691                                    "Signature mismatch for shared user: "
8692                                            + pkgSetting.sharedUser);
8693                        }
8694                    }
8695                    // File a report about this.
8696                    String msg = "System package " + pkg.packageName
8697                            + " signature changed; retaining data.";
8698                    reportSettingsProblem(Log.WARN, msg);
8699                }
8700            }
8701
8702            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8703                // This package wants to adopt ownership of permissions from
8704                // another package.
8705                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8706                    final String origName = pkg.mAdoptPermissions.get(i);
8707                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8708                    if (orig != null) {
8709                        if (verifyPackageUpdateLPr(orig, pkg)) {
8710                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8711                                    + pkg.packageName);
8712                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8713                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8714                        }
8715                    }
8716                }
8717            }
8718        }
8719
8720        pkg.applicationInfo.processName = fixProcessName(
8721                pkg.applicationInfo.packageName,
8722                pkg.applicationInfo.processName);
8723
8724        if (pkg != mPlatformPackage) {
8725            // Get all of our default paths setup
8726            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8727        }
8728
8729        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8730
8731        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8732            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8733                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8734                derivePackageAbi(
8735                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8736                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8737
8738                // Some system apps still use directory structure for native libraries
8739                // in which case we might end up not detecting abi solely based on apk
8740                // structure. Try to detect abi based on directory structure.
8741                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8742                        pkg.applicationInfo.primaryCpuAbi == null) {
8743                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8744                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8745                }
8746            } else {
8747                // This is not a first boot or an upgrade, don't bother deriving the
8748                // ABI during the scan. Instead, trust the value that was stored in the
8749                // package setting.
8750                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8751                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8752
8753                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8754
8755                if (DEBUG_ABI_SELECTION) {
8756                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8757                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8758                        pkg.applicationInfo.secondaryCpuAbi);
8759                }
8760            }
8761        } else {
8762            if ((scanFlags & SCAN_MOVE) != 0) {
8763                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8764                // but we already have this packages package info in the PackageSetting. We just
8765                // use that and derive the native library path based on the new codepath.
8766                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8767                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8768            }
8769
8770            // Set native library paths again. For moves, the path will be updated based on the
8771            // ABIs we've determined above. For non-moves, the path will be updated based on the
8772            // ABIs we determined during compilation, but the path will depend on the final
8773            // package path (after the rename away from the stage path).
8774            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8775        }
8776
8777        // This is a special case for the "system" package, where the ABI is
8778        // dictated by the zygote configuration (and init.rc). We should keep track
8779        // of this ABI so that we can deal with "normal" applications that run under
8780        // the same UID correctly.
8781        if (mPlatformPackage == pkg) {
8782            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8783                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8784        }
8785
8786        // If there's a mismatch between the abi-override in the package setting
8787        // and the abiOverride specified for the install. Warn about this because we
8788        // would've already compiled the app without taking the package setting into
8789        // account.
8790        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8791            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8792                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8793                        " for package " + pkg.packageName);
8794            }
8795        }
8796
8797        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8798        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8799        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8800
8801        // Copy the derived override back to the parsed package, so that we can
8802        // update the package settings accordingly.
8803        pkg.cpuAbiOverride = cpuAbiOverride;
8804
8805        if (DEBUG_ABI_SELECTION) {
8806            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8807                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8808                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8809        }
8810
8811        // Push the derived path down into PackageSettings so we know what to
8812        // clean up at uninstall time.
8813        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8814
8815        if (DEBUG_ABI_SELECTION) {
8816            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8817                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8818                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8819        }
8820
8821        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8822        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8823            // We don't do this here during boot because we can do it all
8824            // at once after scanning all existing packages.
8825            //
8826            // We also do this *before* we perform dexopt on this package, so that
8827            // we can avoid redundant dexopts, and also to make sure we've got the
8828            // code and package path correct.
8829            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8830        }
8831
8832        if (mFactoryTest && pkg.requestedPermissions.contains(
8833                android.Manifest.permission.FACTORY_TEST)) {
8834            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8835        }
8836
8837        if (isSystemApp(pkg)) {
8838            pkgSetting.isOrphaned = true;
8839        }
8840
8841        // Take care of first install / last update times.
8842        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8843        if (currentTime != 0) {
8844            if (pkgSetting.firstInstallTime == 0) {
8845                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8846            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8847                pkgSetting.lastUpdateTime = currentTime;
8848            }
8849        } else if (pkgSetting.firstInstallTime == 0) {
8850            // We need *something*.  Take time time stamp of the file.
8851            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8852        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8853            if (scanFileTime != pkgSetting.timeStamp) {
8854                // A package on the system image has changed; consider this
8855                // to be an update.
8856                pkgSetting.lastUpdateTime = scanFileTime;
8857            }
8858        }
8859        pkgSetting.setTimeStamp(scanFileTime);
8860
8861        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8862            if (nonMutatedPs != null) {
8863                synchronized (mPackages) {
8864                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8865                }
8866            }
8867        } else {
8868            // Modify state for the given package setting
8869            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8870                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8871        }
8872        return pkg;
8873    }
8874
8875    /**
8876     * Applies policy to the parsed package based upon the given policy flags.
8877     * Ensures the package is in a good state.
8878     * <p>
8879     * Implementation detail: This method must NOT have any side effect. It would
8880     * ideally be static, but, it requires locks to read system state.
8881     */
8882    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8883        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8884            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8885            if (pkg.applicationInfo.isDirectBootAware()) {
8886                // we're direct boot aware; set for all components
8887                for (PackageParser.Service s : pkg.services) {
8888                    s.info.encryptionAware = s.info.directBootAware = true;
8889                }
8890                for (PackageParser.Provider p : pkg.providers) {
8891                    p.info.encryptionAware = p.info.directBootAware = true;
8892                }
8893                for (PackageParser.Activity a : pkg.activities) {
8894                    a.info.encryptionAware = a.info.directBootAware = true;
8895                }
8896                for (PackageParser.Activity r : pkg.receivers) {
8897                    r.info.encryptionAware = r.info.directBootAware = true;
8898                }
8899            }
8900        } else {
8901            // Only allow system apps to be flagged as core apps.
8902            pkg.coreApp = false;
8903            // clear flags not applicable to regular apps
8904            pkg.applicationInfo.privateFlags &=
8905                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8906            pkg.applicationInfo.privateFlags &=
8907                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8908        }
8909        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8910
8911        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8912            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8913        }
8914
8915        if (!isSystemApp(pkg)) {
8916            // Only system apps can use these features.
8917            pkg.mOriginalPackages = null;
8918            pkg.mRealPackage = null;
8919            pkg.mAdoptPermissions = null;
8920        }
8921    }
8922
8923    /**
8924     * Asserts the parsed package is valid according to teh given policy. If the
8925     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8926     * <p>
8927     * Implementation detail: This method must NOT have any side effects. It would
8928     * ideally be static, but, it requires locks to read system state.
8929     *
8930     * @throws PackageManagerException If the package fails any of the validation checks
8931     */
8932    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8933            throws PackageManagerException {
8934        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8935            assertCodePolicy(pkg);
8936        }
8937
8938        if (pkg.applicationInfo.getCodePath() == null ||
8939                pkg.applicationInfo.getResourcePath() == null) {
8940            // Bail out. The resource and code paths haven't been set.
8941            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8942                    "Code and resource paths haven't been set correctly");
8943        }
8944
8945        // Make sure we're not adding any bogus keyset info
8946        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8947        ksms.assertScannedPackageValid(pkg);
8948
8949        synchronized (mPackages) {
8950            // The special "android" package can only be defined once
8951            if (pkg.packageName.equals("android")) {
8952                if (mAndroidApplication != null) {
8953                    Slog.w(TAG, "*************************************************");
8954                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8955                    Slog.w(TAG, " codePath=" + pkg.codePath);
8956                    Slog.w(TAG, "*************************************************");
8957                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8958                            "Core android package being redefined.  Skipping.");
8959                }
8960            }
8961
8962            // A package name must be unique; don't allow duplicates
8963            if (mPackages.containsKey(pkg.packageName)
8964                    || mSharedLibraries.containsKey(pkg.packageName)) {
8965                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8966                        "Application package " + pkg.packageName
8967                        + " already installed.  Skipping duplicate.");
8968            }
8969
8970            // Only privileged apps and updated privileged apps can add child packages.
8971            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8972                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8973                    throw new PackageManagerException("Only privileged apps can add child "
8974                            + "packages. Ignoring package " + pkg.packageName);
8975                }
8976                final int childCount = pkg.childPackages.size();
8977                for (int i = 0; i < childCount; i++) {
8978                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8979                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8980                            childPkg.packageName)) {
8981                        throw new PackageManagerException("Can't override child of "
8982                                + "another disabled app. Ignoring package " + pkg.packageName);
8983                    }
8984                }
8985            }
8986
8987            // If we're only installing presumed-existing packages, require that the
8988            // scanned APK is both already known and at the path previously established
8989            // for it.  Previously unknown packages we pick up normally, but if we have an
8990            // a priori expectation about this package's install presence, enforce it.
8991            // With a singular exception for new system packages. When an OTA contains
8992            // a new system package, we allow the codepath to change from a system location
8993            // to the user-installed location. If we don't allow this change, any newer,
8994            // user-installed version of the application will be ignored.
8995            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8996                if (mExpectingBetter.containsKey(pkg.packageName)) {
8997                    logCriticalInfo(Log.WARN,
8998                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8999                } else {
9000                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9001                    if (known != null) {
9002                        if (DEBUG_PACKAGE_SCANNING) {
9003                            Log.d(TAG, "Examining " + pkg.codePath
9004                                    + " and requiring known paths " + known.codePathString
9005                                    + " & " + known.resourcePathString);
9006                        }
9007                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9008                                || !pkg.applicationInfo.getResourcePath().equals(
9009                                        known.resourcePathString)) {
9010                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9011                                    "Application package " + pkg.packageName
9012                                    + " found at " + pkg.applicationInfo.getCodePath()
9013                                    + " but expected at " + known.codePathString
9014                                    + "; ignoring.");
9015                        }
9016                    }
9017                }
9018            }
9019
9020            // Verify that this new package doesn't have any content providers
9021            // that conflict with existing packages.  Only do this if the
9022            // package isn't already installed, since we don't want to break
9023            // things that are installed.
9024            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9025                final int N = pkg.providers.size();
9026                int i;
9027                for (i=0; i<N; i++) {
9028                    PackageParser.Provider p = pkg.providers.get(i);
9029                    if (p.info.authority != null) {
9030                        String names[] = p.info.authority.split(";");
9031                        for (int j = 0; j < names.length; j++) {
9032                            if (mProvidersByAuthority.containsKey(names[j])) {
9033                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9034                                final String otherPackageName =
9035                                        ((other != null && other.getComponentName() != null) ?
9036                                                other.getComponentName().getPackageName() : "?");
9037                                throw new PackageManagerException(
9038                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9039                                        "Can't install because provider name " + names[j]
9040                                                + " (in package " + pkg.applicationInfo.packageName
9041                                                + ") is already used by " + otherPackageName);
9042                            }
9043                        }
9044                    }
9045                }
9046            }
9047        }
9048    }
9049
9050    /**
9051     * Adds a scanned package to the system. When this method is finished, the package will
9052     * be available for query, resolution, etc...
9053     */
9054    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9055            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9056        final String pkgName = pkg.packageName;
9057        if (mCustomResolverComponentName != null &&
9058                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9059            setUpCustomResolverActivity(pkg);
9060        }
9061
9062        if (pkg.packageName.equals("android")) {
9063            synchronized (mPackages) {
9064                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9065                    // Set up information for our fall-back user intent resolution activity.
9066                    mPlatformPackage = pkg;
9067                    pkg.mVersionCode = mSdkVersion;
9068                    mAndroidApplication = pkg.applicationInfo;
9069
9070                    if (!mResolverReplaced) {
9071                        mResolveActivity.applicationInfo = mAndroidApplication;
9072                        mResolveActivity.name = ResolverActivity.class.getName();
9073                        mResolveActivity.packageName = mAndroidApplication.packageName;
9074                        mResolveActivity.processName = "system:ui";
9075                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9076                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9077                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9078                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9079                        mResolveActivity.exported = true;
9080                        mResolveActivity.enabled = true;
9081                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9082                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9083                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9084                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9085                                | ActivityInfo.CONFIG_ORIENTATION
9086                                | ActivityInfo.CONFIG_KEYBOARD
9087                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9088                        mResolveInfo.activityInfo = mResolveActivity;
9089                        mResolveInfo.priority = 0;
9090                        mResolveInfo.preferredOrder = 0;
9091                        mResolveInfo.match = 0;
9092                        mResolveComponentName = new ComponentName(
9093                                mAndroidApplication.packageName, mResolveActivity.name);
9094                    }
9095                }
9096            }
9097        }
9098
9099        ArrayList<PackageParser.Package> clientLibPkgs = null;
9100        // writer
9101        synchronized (mPackages) {
9102            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9103                // Only system apps can add new shared libraries.
9104                if (pkg.libraryNames != null) {
9105                    for (int i=0; i<pkg.libraryNames.size(); i++) {
9106                        String name = pkg.libraryNames.get(i);
9107                        boolean allowed = false;
9108                        if (pkg.isUpdatedSystemApp()) {
9109                            // New library entries can only be added through the
9110                            // system image.  This is important to get rid of a lot
9111                            // of nasty edge cases: for example if we allowed a non-
9112                            // system update of the app to add a library, then uninstalling
9113                            // the update would make the library go away, and assumptions
9114                            // we made such as through app install filtering would now
9115                            // have allowed apps on the device which aren't compatible
9116                            // with it.  Better to just have the restriction here, be
9117                            // conservative, and create many fewer cases that can negatively
9118                            // impact the user experience.
9119                            final PackageSetting sysPs = mSettings
9120                                    .getDisabledSystemPkgLPr(pkg.packageName);
9121                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9122                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
9123                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9124                                        allowed = true;
9125                                        break;
9126                                    }
9127                                }
9128                            }
9129                        } else {
9130                            allowed = true;
9131                        }
9132                        if (allowed) {
9133                            if (!mSharedLibraries.containsKey(name)) {
9134                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
9135                            } else if (!name.equals(pkg.packageName)) {
9136                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9137                                        + name + " already exists; skipping");
9138                            }
9139                        } else {
9140                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9141                                    + name + " that is not declared on system image; skipping");
9142                        }
9143                    }
9144                    if ((scanFlags & SCAN_BOOTING) == 0) {
9145                        // If we are not booting, we need to update any applications
9146                        // that are clients of our shared library.  If we are booting,
9147                        // this will all be done once the scan is complete.
9148                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9149                    }
9150                }
9151            }
9152        }
9153
9154        if ((scanFlags & SCAN_BOOTING) != 0) {
9155            // No apps can run during boot scan, so they don't need to be frozen
9156        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9157            // Caller asked to not kill app, so it's probably not frozen
9158        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9159            // Caller asked us to ignore frozen check for some reason; they
9160            // probably didn't know the package name
9161        } else {
9162            // We're doing major surgery on this package, so it better be frozen
9163            // right now to keep it from launching
9164            checkPackageFrozen(pkgName);
9165        }
9166
9167        // Also need to kill any apps that are dependent on the library.
9168        if (clientLibPkgs != null) {
9169            for (int i=0; i<clientLibPkgs.size(); i++) {
9170                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9171                killApplication(clientPkg.applicationInfo.packageName,
9172                        clientPkg.applicationInfo.uid, "update lib");
9173            }
9174        }
9175
9176        // writer
9177        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9178
9179        boolean createIdmapFailed = false;
9180        synchronized (mPackages) {
9181            // We don't expect installation to fail beyond this point
9182
9183            if (pkgSetting.pkg != null) {
9184                // Note that |user| might be null during the initial boot scan. If a codePath
9185                // for an app has changed during a boot scan, it's due to an app update that's
9186                // part of the system partition and marker changes must be applied to all users.
9187                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9188                final int[] userIds = resolveUserIds(userId);
9189                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9190            }
9191
9192            // Add the new setting to mSettings
9193            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9194            // Add the new setting to mPackages
9195            mPackages.put(pkg.applicationInfo.packageName, pkg);
9196            // Make sure we don't accidentally delete its data.
9197            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9198            while (iter.hasNext()) {
9199                PackageCleanItem item = iter.next();
9200                if (pkgName.equals(item.packageName)) {
9201                    iter.remove();
9202                }
9203            }
9204
9205            // Add the package's KeySets to the global KeySetManagerService
9206            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9207            ksms.addScannedPackageLPw(pkg);
9208
9209            int N = pkg.providers.size();
9210            StringBuilder r = null;
9211            int i;
9212            for (i=0; i<N; i++) {
9213                PackageParser.Provider p = pkg.providers.get(i);
9214                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9215                        p.info.processName);
9216                mProviders.addProvider(p);
9217                p.syncable = p.info.isSyncable;
9218                if (p.info.authority != null) {
9219                    String names[] = p.info.authority.split(";");
9220                    p.info.authority = null;
9221                    for (int j = 0; j < names.length; j++) {
9222                        if (j == 1 && p.syncable) {
9223                            // We only want the first authority for a provider to possibly be
9224                            // syncable, so if we already added this provider using a different
9225                            // authority clear the syncable flag. We copy the provider before
9226                            // changing it because the mProviders object contains a reference
9227                            // to a provider that we don't want to change.
9228                            // Only do this for the second authority since the resulting provider
9229                            // object can be the same for all future authorities for this provider.
9230                            p = new PackageParser.Provider(p);
9231                            p.syncable = false;
9232                        }
9233                        if (!mProvidersByAuthority.containsKey(names[j])) {
9234                            mProvidersByAuthority.put(names[j], p);
9235                            if (p.info.authority == null) {
9236                                p.info.authority = names[j];
9237                            } else {
9238                                p.info.authority = p.info.authority + ";" + names[j];
9239                            }
9240                            if (DEBUG_PACKAGE_SCANNING) {
9241                                if (chatty)
9242                                    Log.d(TAG, "Registered content provider: " + names[j]
9243                                            + ", className = " + p.info.name + ", isSyncable = "
9244                                            + p.info.isSyncable);
9245                            }
9246                        } else {
9247                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9248                            Slog.w(TAG, "Skipping provider name " + names[j] +
9249                                    " (in package " + pkg.applicationInfo.packageName +
9250                                    "): name already used by "
9251                                    + ((other != null && other.getComponentName() != null)
9252                                            ? other.getComponentName().getPackageName() : "?"));
9253                        }
9254                    }
9255                }
9256                if (chatty) {
9257                    if (r == null) {
9258                        r = new StringBuilder(256);
9259                    } else {
9260                        r.append(' ');
9261                    }
9262                    r.append(p.info.name);
9263                }
9264            }
9265            if (r != null) {
9266                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9267            }
9268
9269            N = pkg.services.size();
9270            r = null;
9271            for (i=0; i<N; i++) {
9272                PackageParser.Service s = pkg.services.get(i);
9273                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9274                        s.info.processName);
9275                mServices.addService(s);
9276                if (chatty) {
9277                    if (r == null) {
9278                        r = new StringBuilder(256);
9279                    } else {
9280                        r.append(' ');
9281                    }
9282                    r.append(s.info.name);
9283                }
9284            }
9285            if (r != null) {
9286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9287            }
9288
9289            N = pkg.receivers.size();
9290            r = null;
9291            for (i=0; i<N; i++) {
9292                PackageParser.Activity a = pkg.receivers.get(i);
9293                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9294                        a.info.processName);
9295                mReceivers.addActivity(a, "receiver");
9296                if (chatty) {
9297                    if (r == null) {
9298                        r = new StringBuilder(256);
9299                    } else {
9300                        r.append(' ');
9301                    }
9302                    r.append(a.info.name);
9303                }
9304            }
9305            if (r != null) {
9306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9307            }
9308
9309            N = pkg.activities.size();
9310            r = null;
9311            for (i=0; i<N; i++) {
9312                PackageParser.Activity a = pkg.activities.get(i);
9313                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9314                        a.info.processName);
9315                mActivities.addActivity(a, "activity");
9316                if (chatty) {
9317                    if (r == null) {
9318                        r = new StringBuilder(256);
9319                    } else {
9320                        r.append(' ');
9321                    }
9322                    r.append(a.info.name);
9323                }
9324            }
9325            if (r != null) {
9326                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9327            }
9328
9329            N = pkg.permissionGroups.size();
9330            r = null;
9331            for (i=0; i<N; i++) {
9332                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9333                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9334                final String curPackageName = cur == null ? null : cur.info.packageName;
9335                // Dont allow ephemeral apps to define new permission groups.
9336                if (pkg.applicationInfo.isEphemeralApp()) {
9337                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9338                            + pg.info.packageName
9339                            + " ignored: ephemeral apps cannot define new permission groups.");
9340                    continue;
9341                }
9342                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9343                if (cur == null || isPackageUpdate) {
9344                    mPermissionGroups.put(pg.info.name, pg);
9345                    if (chatty) {
9346                        if (r == null) {
9347                            r = new StringBuilder(256);
9348                        } else {
9349                            r.append(' ');
9350                        }
9351                        if (isPackageUpdate) {
9352                            r.append("UPD:");
9353                        }
9354                        r.append(pg.info.name);
9355                    }
9356                } else {
9357                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9358                            + pg.info.packageName + " ignored: original from "
9359                            + cur.info.packageName);
9360                    if (chatty) {
9361                        if (r == null) {
9362                            r = new StringBuilder(256);
9363                        } else {
9364                            r.append(' ');
9365                        }
9366                        r.append("DUP:");
9367                        r.append(pg.info.name);
9368                    }
9369                }
9370            }
9371            if (r != null) {
9372                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9373            }
9374
9375            N = pkg.permissions.size();
9376            r = null;
9377            for (i=0; i<N; i++) {
9378                PackageParser.Permission p = pkg.permissions.get(i);
9379
9380                // Dont allow ephemeral apps to define new permissions.
9381                if (pkg.applicationInfo.isEphemeralApp()) {
9382                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9383                            + p.info.packageName
9384                            + " ignored: ephemeral apps cannot define new permissions.");
9385                    continue;
9386                }
9387
9388                // Assume by default that we did not install this permission into the system.
9389                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9390
9391                // Now that permission groups have a special meaning, we ignore permission
9392                // groups for legacy apps to prevent unexpected behavior. In particular,
9393                // permissions for one app being granted to someone just becase they happen
9394                // to be in a group defined by another app (before this had no implications).
9395                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9396                    p.group = mPermissionGroups.get(p.info.group);
9397                    // Warn for a permission in an unknown group.
9398                    if (p.info.group != null && p.group == null) {
9399                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9400                                + p.info.packageName + " in an unknown group " + p.info.group);
9401                    }
9402                }
9403
9404                ArrayMap<String, BasePermission> permissionMap =
9405                        p.tree ? mSettings.mPermissionTrees
9406                                : mSettings.mPermissions;
9407                BasePermission bp = permissionMap.get(p.info.name);
9408
9409                // Allow system apps to redefine non-system permissions
9410                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9411                    final boolean currentOwnerIsSystem = (bp.perm != null
9412                            && isSystemApp(bp.perm.owner));
9413                    if (isSystemApp(p.owner)) {
9414                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9415                            // It's a built-in permission and no owner, take ownership now
9416                            bp.packageSetting = pkgSetting;
9417                            bp.perm = p;
9418                            bp.uid = pkg.applicationInfo.uid;
9419                            bp.sourcePackage = p.info.packageName;
9420                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9421                        } else if (!currentOwnerIsSystem) {
9422                            String msg = "New decl " + p.owner + " of permission  "
9423                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9424                            reportSettingsProblem(Log.WARN, msg);
9425                            bp = null;
9426                        }
9427                    }
9428                }
9429
9430                if (bp == null) {
9431                    bp = new BasePermission(p.info.name, p.info.packageName,
9432                            BasePermission.TYPE_NORMAL);
9433                    permissionMap.put(p.info.name, bp);
9434                }
9435
9436                if (bp.perm == null) {
9437                    if (bp.sourcePackage == null
9438                            || bp.sourcePackage.equals(p.info.packageName)) {
9439                        BasePermission tree = findPermissionTreeLP(p.info.name);
9440                        if (tree == null
9441                                || tree.sourcePackage.equals(p.info.packageName)) {
9442                            bp.packageSetting = pkgSetting;
9443                            bp.perm = p;
9444                            bp.uid = pkg.applicationInfo.uid;
9445                            bp.sourcePackage = p.info.packageName;
9446                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9447                            if (chatty) {
9448                                if (r == null) {
9449                                    r = new StringBuilder(256);
9450                                } else {
9451                                    r.append(' ');
9452                                }
9453                                r.append(p.info.name);
9454                            }
9455                        } else {
9456                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9457                                    + p.info.packageName + " ignored: base tree "
9458                                    + tree.name + " is from package "
9459                                    + tree.sourcePackage);
9460                        }
9461                    } else {
9462                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9463                                + p.info.packageName + " ignored: original from "
9464                                + bp.sourcePackage);
9465                    }
9466                } else if (chatty) {
9467                    if (r == null) {
9468                        r = new StringBuilder(256);
9469                    } else {
9470                        r.append(' ');
9471                    }
9472                    r.append("DUP:");
9473                    r.append(p.info.name);
9474                }
9475                if (bp.perm == p) {
9476                    bp.protectionLevel = p.info.protectionLevel;
9477                }
9478            }
9479
9480            if (r != null) {
9481                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9482            }
9483
9484            N = pkg.instrumentation.size();
9485            r = null;
9486            for (i=0; i<N; i++) {
9487                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9488                a.info.packageName = pkg.applicationInfo.packageName;
9489                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9490                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9491                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9492                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9493                a.info.dataDir = pkg.applicationInfo.dataDir;
9494                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9495                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9496                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9497                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9498                mInstrumentation.put(a.getComponentName(), a);
9499                if (chatty) {
9500                    if (r == null) {
9501                        r = new StringBuilder(256);
9502                    } else {
9503                        r.append(' ');
9504                    }
9505                    r.append(a.info.name);
9506                }
9507            }
9508            if (r != null) {
9509                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9510            }
9511
9512            if (pkg.protectedBroadcasts != null) {
9513                N = pkg.protectedBroadcasts.size();
9514                for (i=0; i<N; i++) {
9515                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9516                }
9517            }
9518
9519            // Create idmap files for pairs of (packages, overlay packages).
9520            // Note: "android", ie framework-res.apk, is handled by native layers.
9521            if (pkg.mOverlayTarget != null) {
9522                // This is an overlay package.
9523                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9524                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9525                        mOverlays.put(pkg.mOverlayTarget,
9526                                new ArrayMap<String, PackageParser.Package>());
9527                    }
9528                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9529                    map.put(pkg.packageName, pkg);
9530                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9531                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9532                        createIdmapFailed = true;
9533                    }
9534                }
9535            } else if (mOverlays.containsKey(pkg.packageName) &&
9536                    !pkg.packageName.equals("android")) {
9537                // This is a regular package, with one or more known overlay packages.
9538                createIdmapsForPackageLI(pkg);
9539            }
9540        }
9541
9542        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9543
9544        if (createIdmapFailed) {
9545            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9546                    "scanPackageLI failed to createIdmap");
9547        }
9548    }
9549
9550    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9551            PackageParser.Package update, int[] userIds) {
9552        if (existing.applicationInfo == null || update.applicationInfo == null) {
9553            // This isn't due to an app installation.
9554            return;
9555        }
9556
9557        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9558        final File newCodePath = new File(update.applicationInfo.getCodePath());
9559
9560        // The codePath hasn't changed, so there's nothing for us to do.
9561        if (Objects.equals(oldCodePath, newCodePath)) {
9562            return;
9563        }
9564
9565        File canonicalNewCodePath;
9566        try {
9567            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9568        } catch (IOException e) {
9569            Slog.w(TAG, "Failed to get canonical path.", e);
9570            return;
9571        }
9572
9573        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9574        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9575        // that the last component of the path (i.e, the name) doesn't need canonicalization
9576        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9577        // but may change in the future. Hopefully this function won't exist at that point.
9578        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9579                oldCodePath.getName());
9580
9581        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9582        // with "@".
9583        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9584        if (!oldMarkerPrefix.endsWith("@")) {
9585            oldMarkerPrefix += "@";
9586        }
9587        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9588        if (!newMarkerPrefix.endsWith("@")) {
9589            newMarkerPrefix += "@";
9590        }
9591
9592        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9593        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9594        for (String updatedPath : updatedPaths) {
9595            String updatedPathName = new File(updatedPath).getName();
9596            markerSuffixes.add(updatedPathName.replace('/', '@'));
9597        }
9598
9599        for (int userId : userIds) {
9600            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9601
9602            for (String markerSuffix : markerSuffixes) {
9603                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9604                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9605                if (oldForeignUseMark.exists()) {
9606                    try {
9607                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9608                                newForeignUseMark.getAbsolutePath());
9609                    } catch (ErrnoException e) {
9610                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9611                        oldForeignUseMark.delete();
9612                    }
9613                }
9614            }
9615        }
9616    }
9617
9618    /**
9619     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9620     * is derived purely on the basis of the contents of {@code scanFile} and
9621     * {@code cpuAbiOverride}.
9622     *
9623     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9624     */
9625    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9626                                 String cpuAbiOverride, boolean extractLibs,
9627                                 File appLib32InstallDir)
9628            throws PackageManagerException {
9629        // Give ourselves some initial paths; we'll come back for another
9630        // pass once we've determined ABI below.
9631        setNativeLibraryPaths(pkg, appLib32InstallDir);
9632
9633        // We would never need to extract libs for forward-locked and external packages,
9634        // since the container service will do it for us. We shouldn't attempt to
9635        // extract libs from system app when it was not updated.
9636        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9637                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9638            extractLibs = false;
9639        }
9640
9641        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9642        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9643
9644        NativeLibraryHelper.Handle handle = null;
9645        try {
9646            handle = NativeLibraryHelper.Handle.create(pkg);
9647            // TODO(multiArch): This can be null for apps that didn't go through the
9648            // usual installation process. We can calculate it again, like we
9649            // do during install time.
9650            //
9651            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9652            // unnecessary.
9653            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9654
9655            // Null out the abis so that they can be recalculated.
9656            pkg.applicationInfo.primaryCpuAbi = null;
9657            pkg.applicationInfo.secondaryCpuAbi = null;
9658            if (isMultiArch(pkg.applicationInfo)) {
9659                // Warn if we've set an abiOverride for multi-lib packages..
9660                // By definition, we need to copy both 32 and 64 bit libraries for
9661                // such packages.
9662                if (pkg.cpuAbiOverride != null
9663                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9664                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9665                }
9666
9667                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9668                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9669                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9670                    if (extractLibs) {
9671                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9672                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9673                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9674                                useIsaSpecificSubdirs);
9675                    } else {
9676                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9677                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9678                    }
9679                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9680                }
9681
9682                maybeThrowExceptionForMultiArchCopy(
9683                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9684
9685                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9686                    if (extractLibs) {
9687                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9688                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9689                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9690                                useIsaSpecificSubdirs);
9691                    } else {
9692                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9693                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9694                    }
9695                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9696                }
9697
9698                maybeThrowExceptionForMultiArchCopy(
9699                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9700
9701                if (abi64 >= 0) {
9702                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9703                }
9704
9705                if (abi32 >= 0) {
9706                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9707                    if (abi64 >= 0) {
9708                        if (pkg.use32bitAbi) {
9709                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9710                            pkg.applicationInfo.primaryCpuAbi = abi;
9711                        } else {
9712                            pkg.applicationInfo.secondaryCpuAbi = abi;
9713                        }
9714                    } else {
9715                        pkg.applicationInfo.primaryCpuAbi = abi;
9716                    }
9717                }
9718
9719            } else {
9720                String[] abiList = (cpuAbiOverride != null) ?
9721                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9722
9723                // Enable gross and lame hacks for apps that are built with old
9724                // SDK tools. We must scan their APKs for renderscript bitcode and
9725                // not launch them if it's present. Don't bother checking on devices
9726                // that don't have 64 bit support.
9727                boolean needsRenderScriptOverride = false;
9728                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9729                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9730                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9731                    needsRenderScriptOverride = true;
9732                }
9733
9734                final int copyRet;
9735                if (extractLibs) {
9736                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9737                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9738                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9739                } else {
9740                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9741                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9742                }
9743                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9744
9745                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9746                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9747                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9748                }
9749
9750                if (copyRet >= 0) {
9751                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9752                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9753                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9754                } else if (needsRenderScriptOverride) {
9755                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9756                }
9757            }
9758        } catch (IOException ioe) {
9759            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9760        } finally {
9761            IoUtils.closeQuietly(handle);
9762        }
9763
9764        // Now that we've calculated the ABIs and determined if it's an internal app,
9765        // we will go ahead and populate the nativeLibraryPath.
9766        setNativeLibraryPaths(pkg, appLib32InstallDir);
9767    }
9768
9769    /**
9770     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9771     * i.e, so that all packages can be run inside a single process if required.
9772     *
9773     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9774     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9775     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9776     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9777     * updating a package that belongs to a shared user.
9778     *
9779     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9780     * adds unnecessary complexity.
9781     */
9782    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9783            PackageParser.Package scannedPackage) {
9784        String requiredInstructionSet = null;
9785        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9786            requiredInstructionSet = VMRuntime.getInstructionSet(
9787                     scannedPackage.applicationInfo.primaryCpuAbi);
9788        }
9789
9790        PackageSetting requirer = null;
9791        for (PackageSetting ps : packagesForUser) {
9792            // If packagesForUser contains scannedPackage, we skip it. This will happen
9793            // when scannedPackage is an update of an existing package. Without this check,
9794            // we will never be able to change the ABI of any package belonging to a shared
9795            // user, even if it's compatible with other packages.
9796            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9797                if (ps.primaryCpuAbiString == null) {
9798                    continue;
9799                }
9800
9801                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9802                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9803                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9804                    // this but there's not much we can do.
9805                    String errorMessage = "Instruction set mismatch, "
9806                            + ((requirer == null) ? "[caller]" : requirer)
9807                            + " requires " + requiredInstructionSet + " whereas " + ps
9808                            + " requires " + instructionSet;
9809                    Slog.w(TAG, errorMessage);
9810                }
9811
9812                if (requiredInstructionSet == null) {
9813                    requiredInstructionSet = instructionSet;
9814                    requirer = ps;
9815                }
9816            }
9817        }
9818
9819        if (requiredInstructionSet != null) {
9820            String adjustedAbi;
9821            if (requirer != null) {
9822                // requirer != null implies that either scannedPackage was null or that scannedPackage
9823                // did not require an ABI, in which case we have to adjust scannedPackage to match
9824                // the ABI of the set (which is the same as requirer's ABI)
9825                adjustedAbi = requirer.primaryCpuAbiString;
9826                if (scannedPackage != null) {
9827                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9828                }
9829            } else {
9830                // requirer == null implies that we're updating all ABIs in the set to
9831                // match scannedPackage.
9832                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9833            }
9834
9835            for (PackageSetting ps : packagesForUser) {
9836                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9837                    if (ps.primaryCpuAbiString != null) {
9838                        continue;
9839                    }
9840
9841                    ps.primaryCpuAbiString = adjustedAbi;
9842                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9843                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9844                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9845                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9846                                + " (requirer="
9847                                + (requirer == null ? "null" : requirer.pkg.packageName)
9848                                + ", scannedPackage="
9849                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9850                                + ")");
9851                        try {
9852                            mInstaller.rmdex(ps.codePathString,
9853                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9854                        } catch (InstallerException ignored) {
9855                        }
9856                    }
9857                }
9858            }
9859        }
9860    }
9861
9862    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9863        synchronized (mPackages) {
9864            mResolverReplaced = true;
9865            // Set up information for custom user intent resolution activity.
9866            mResolveActivity.applicationInfo = pkg.applicationInfo;
9867            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9868            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9869            mResolveActivity.processName = pkg.applicationInfo.packageName;
9870            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9871            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9872                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9873            mResolveActivity.theme = 0;
9874            mResolveActivity.exported = true;
9875            mResolveActivity.enabled = true;
9876            mResolveInfo.activityInfo = mResolveActivity;
9877            mResolveInfo.priority = 0;
9878            mResolveInfo.preferredOrder = 0;
9879            mResolveInfo.match = 0;
9880            mResolveComponentName = mCustomResolverComponentName;
9881            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9882                    mResolveComponentName);
9883        }
9884    }
9885
9886    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9887        if (installerComponent == null) {
9888            if (DEBUG_EPHEMERAL) {
9889                Slog.d(TAG, "Clear ephemeral installer activity");
9890            }
9891            mEphemeralInstallerActivity.applicationInfo = null;
9892            return;
9893        }
9894
9895        if (DEBUG_EPHEMERAL) {
9896            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9897        }
9898        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9899        // Set up information for ephemeral installer activity
9900        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9901        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9902        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9903        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9904        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9905        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9906                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9907        mEphemeralInstallerActivity.theme = 0;
9908        mEphemeralInstallerActivity.exported = true;
9909        mEphemeralInstallerActivity.enabled = true;
9910        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9911        mEphemeralInstallerInfo.priority = 0;
9912        mEphemeralInstallerInfo.preferredOrder = 1;
9913        mEphemeralInstallerInfo.isDefault = true;
9914        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9915                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9916    }
9917
9918    private static String calculateBundledApkRoot(final String codePathString) {
9919        final File codePath = new File(codePathString);
9920        final File codeRoot;
9921        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9922            codeRoot = Environment.getRootDirectory();
9923        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9924            codeRoot = Environment.getOemDirectory();
9925        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9926            codeRoot = Environment.getVendorDirectory();
9927        } else {
9928            // Unrecognized code path; take its top real segment as the apk root:
9929            // e.g. /something/app/blah.apk => /something
9930            try {
9931                File f = codePath.getCanonicalFile();
9932                File parent = f.getParentFile();    // non-null because codePath is a file
9933                File tmp;
9934                while ((tmp = parent.getParentFile()) != null) {
9935                    f = parent;
9936                    parent = tmp;
9937                }
9938                codeRoot = f;
9939                Slog.w(TAG, "Unrecognized code path "
9940                        + codePath + " - using " + codeRoot);
9941            } catch (IOException e) {
9942                // Can't canonicalize the code path -- shenanigans?
9943                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9944                return Environment.getRootDirectory().getPath();
9945            }
9946        }
9947        return codeRoot.getPath();
9948    }
9949
9950    /**
9951     * Derive and set the location of native libraries for the given package,
9952     * which varies depending on where and how the package was installed.
9953     */
9954    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9955        final ApplicationInfo info = pkg.applicationInfo;
9956        final String codePath = pkg.codePath;
9957        final File codeFile = new File(codePath);
9958        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9959        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9960
9961        info.nativeLibraryRootDir = null;
9962        info.nativeLibraryRootRequiresIsa = false;
9963        info.nativeLibraryDir = null;
9964        info.secondaryNativeLibraryDir = null;
9965
9966        if (isApkFile(codeFile)) {
9967            // Monolithic install
9968            if (bundledApp) {
9969                // If "/system/lib64/apkname" exists, assume that is the per-package
9970                // native library directory to use; otherwise use "/system/lib/apkname".
9971                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9972                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9973                        getPrimaryInstructionSet(info));
9974
9975                // This is a bundled system app so choose the path based on the ABI.
9976                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9977                // is just the default path.
9978                final String apkName = deriveCodePathName(codePath);
9979                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9980                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9981                        apkName).getAbsolutePath();
9982
9983                if (info.secondaryCpuAbi != null) {
9984                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9985                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9986                            secondaryLibDir, apkName).getAbsolutePath();
9987                }
9988            } else if (asecApp) {
9989                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9990                        .getAbsolutePath();
9991            } else {
9992                final String apkName = deriveCodePathName(codePath);
9993                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9994                        .getAbsolutePath();
9995            }
9996
9997            info.nativeLibraryRootRequiresIsa = false;
9998            info.nativeLibraryDir = info.nativeLibraryRootDir;
9999        } else {
10000            // Cluster install
10001            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10002            info.nativeLibraryRootRequiresIsa = true;
10003
10004            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10005                    getPrimaryInstructionSet(info)).getAbsolutePath();
10006
10007            if (info.secondaryCpuAbi != null) {
10008                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10009                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10010            }
10011        }
10012    }
10013
10014    /**
10015     * Calculate the abis and roots for a bundled app. These can uniquely
10016     * be determined from the contents of the system partition, i.e whether
10017     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10018     * of this information, and instead assume that the system was built
10019     * sensibly.
10020     */
10021    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10022                                           PackageSetting pkgSetting) {
10023        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10024
10025        // If "/system/lib64/apkname" exists, assume that is the per-package
10026        // native library directory to use; otherwise use "/system/lib/apkname".
10027        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10028        setBundledAppAbi(pkg, apkRoot, apkName);
10029        // pkgSetting might be null during rescan following uninstall of updates
10030        // to a bundled app, so accommodate that possibility.  The settings in
10031        // that case will be established later from the parsed package.
10032        //
10033        // If the settings aren't null, sync them up with what we've just derived.
10034        // note that apkRoot isn't stored in the package settings.
10035        if (pkgSetting != null) {
10036            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10037            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10038        }
10039    }
10040
10041    /**
10042     * Deduces the ABI of a bundled app and sets the relevant fields on the
10043     * parsed pkg object.
10044     *
10045     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10046     *        under which system libraries are installed.
10047     * @param apkName the name of the installed package.
10048     */
10049    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10050        final File codeFile = new File(pkg.codePath);
10051
10052        final boolean has64BitLibs;
10053        final boolean has32BitLibs;
10054        if (isApkFile(codeFile)) {
10055            // Monolithic install
10056            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10057            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10058        } else {
10059            // Cluster install
10060            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10061            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10062                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10063                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10064                has64BitLibs = (new File(rootDir, isa)).exists();
10065            } else {
10066                has64BitLibs = false;
10067            }
10068            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10069                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10070                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10071                has32BitLibs = (new File(rootDir, isa)).exists();
10072            } else {
10073                has32BitLibs = false;
10074            }
10075        }
10076
10077        if (has64BitLibs && !has32BitLibs) {
10078            // The package has 64 bit libs, but not 32 bit libs. Its primary
10079            // ABI should be 64 bit. We can safely assume here that the bundled
10080            // native libraries correspond to the most preferred ABI in the list.
10081
10082            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10083            pkg.applicationInfo.secondaryCpuAbi = null;
10084        } else if (has32BitLibs && !has64BitLibs) {
10085            // The package has 32 bit libs but not 64 bit libs. Its primary
10086            // ABI should be 32 bit.
10087
10088            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10089            pkg.applicationInfo.secondaryCpuAbi = null;
10090        } else if (has32BitLibs && has64BitLibs) {
10091            // The application has both 64 and 32 bit bundled libraries. We check
10092            // here that the app declares multiArch support, and warn if it doesn't.
10093            //
10094            // We will be lenient here and record both ABIs. The primary will be the
10095            // ABI that's higher on the list, i.e, a device that's configured to prefer
10096            // 64 bit apps will see a 64 bit primary ABI,
10097
10098            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10099                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10100            }
10101
10102            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10103                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10104                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10105            } else {
10106                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10107                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10108            }
10109        } else {
10110            pkg.applicationInfo.primaryCpuAbi = null;
10111            pkg.applicationInfo.secondaryCpuAbi = null;
10112        }
10113    }
10114
10115    private void killApplication(String pkgName, int appId, String reason) {
10116        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10117    }
10118
10119    private void killApplication(String pkgName, int appId, int userId, String reason) {
10120        // Request the ActivityManager to kill the process(only for existing packages)
10121        // so that we do not end up in a confused state while the user is still using the older
10122        // version of the application while the new one gets installed.
10123        final long token = Binder.clearCallingIdentity();
10124        try {
10125            IActivityManager am = ActivityManager.getService();
10126            if (am != null) {
10127                try {
10128                    am.killApplication(pkgName, appId, userId, reason);
10129                } catch (RemoteException e) {
10130                }
10131            }
10132        } finally {
10133            Binder.restoreCallingIdentity(token);
10134        }
10135    }
10136
10137    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10138        // Remove the parent package setting
10139        PackageSetting ps = (PackageSetting) pkg.mExtras;
10140        if (ps != null) {
10141            removePackageLI(ps, chatty);
10142        }
10143        // Remove the child package setting
10144        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10145        for (int i = 0; i < childCount; i++) {
10146            PackageParser.Package childPkg = pkg.childPackages.get(i);
10147            ps = (PackageSetting) childPkg.mExtras;
10148            if (ps != null) {
10149                removePackageLI(ps, chatty);
10150            }
10151        }
10152    }
10153
10154    void removePackageLI(PackageSetting ps, boolean chatty) {
10155        if (DEBUG_INSTALL) {
10156            if (chatty)
10157                Log.d(TAG, "Removing package " + ps.name);
10158        }
10159
10160        // writer
10161        synchronized (mPackages) {
10162            mPackages.remove(ps.name);
10163            final PackageParser.Package pkg = ps.pkg;
10164            if (pkg != null) {
10165                cleanPackageDataStructuresLILPw(pkg, chatty);
10166            }
10167        }
10168    }
10169
10170    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10171        if (DEBUG_INSTALL) {
10172            if (chatty)
10173                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10174        }
10175
10176        // writer
10177        synchronized (mPackages) {
10178            // Remove the parent package
10179            mPackages.remove(pkg.applicationInfo.packageName);
10180            cleanPackageDataStructuresLILPw(pkg, chatty);
10181
10182            // Remove the child packages
10183            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10184            for (int i = 0; i < childCount; i++) {
10185                PackageParser.Package childPkg = pkg.childPackages.get(i);
10186                mPackages.remove(childPkg.applicationInfo.packageName);
10187                cleanPackageDataStructuresLILPw(childPkg, chatty);
10188            }
10189        }
10190    }
10191
10192    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10193        int N = pkg.providers.size();
10194        StringBuilder r = null;
10195        int i;
10196        for (i=0; i<N; i++) {
10197            PackageParser.Provider p = pkg.providers.get(i);
10198            mProviders.removeProvider(p);
10199            if (p.info.authority == null) {
10200
10201                /* There was another ContentProvider with this authority when
10202                 * this app was installed so this authority is null,
10203                 * Ignore it as we don't have to unregister the provider.
10204                 */
10205                continue;
10206            }
10207            String names[] = p.info.authority.split(";");
10208            for (int j = 0; j < names.length; j++) {
10209                if (mProvidersByAuthority.get(names[j]) == p) {
10210                    mProvidersByAuthority.remove(names[j]);
10211                    if (DEBUG_REMOVE) {
10212                        if (chatty)
10213                            Log.d(TAG, "Unregistered content provider: " + names[j]
10214                                    + ", className = " + p.info.name + ", isSyncable = "
10215                                    + p.info.isSyncable);
10216                    }
10217                }
10218            }
10219            if (DEBUG_REMOVE && chatty) {
10220                if (r == null) {
10221                    r = new StringBuilder(256);
10222                } else {
10223                    r.append(' ');
10224                }
10225                r.append(p.info.name);
10226            }
10227        }
10228        if (r != null) {
10229            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10230        }
10231
10232        N = pkg.services.size();
10233        r = null;
10234        for (i=0; i<N; i++) {
10235            PackageParser.Service s = pkg.services.get(i);
10236            mServices.removeService(s);
10237            if (chatty) {
10238                if (r == null) {
10239                    r = new StringBuilder(256);
10240                } else {
10241                    r.append(' ');
10242                }
10243                r.append(s.info.name);
10244            }
10245        }
10246        if (r != null) {
10247            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10248        }
10249
10250        N = pkg.receivers.size();
10251        r = null;
10252        for (i=0; i<N; i++) {
10253            PackageParser.Activity a = pkg.receivers.get(i);
10254            mReceivers.removeActivity(a, "receiver");
10255            if (DEBUG_REMOVE && chatty) {
10256                if (r == null) {
10257                    r = new StringBuilder(256);
10258                } else {
10259                    r.append(' ');
10260                }
10261                r.append(a.info.name);
10262            }
10263        }
10264        if (r != null) {
10265            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10266        }
10267
10268        N = pkg.activities.size();
10269        r = null;
10270        for (i=0; i<N; i++) {
10271            PackageParser.Activity a = pkg.activities.get(i);
10272            mActivities.removeActivity(a, "activity");
10273            if (DEBUG_REMOVE && chatty) {
10274                if (r == null) {
10275                    r = new StringBuilder(256);
10276                } else {
10277                    r.append(' ');
10278                }
10279                r.append(a.info.name);
10280            }
10281        }
10282        if (r != null) {
10283            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10284        }
10285
10286        N = pkg.permissions.size();
10287        r = null;
10288        for (i=0; i<N; i++) {
10289            PackageParser.Permission p = pkg.permissions.get(i);
10290            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10291            if (bp == null) {
10292                bp = mSettings.mPermissionTrees.get(p.info.name);
10293            }
10294            if (bp != null && bp.perm == p) {
10295                bp.perm = null;
10296                if (DEBUG_REMOVE && chatty) {
10297                    if (r == null) {
10298                        r = new StringBuilder(256);
10299                    } else {
10300                        r.append(' ');
10301                    }
10302                    r.append(p.info.name);
10303                }
10304            }
10305            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10306                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10307                if (appOpPkgs != null) {
10308                    appOpPkgs.remove(pkg.packageName);
10309                }
10310            }
10311        }
10312        if (r != null) {
10313            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10314        }
10315
10316        N = pkg.requestedPermissions.size();
10317        r = null;
10318        for (i=0; i<N; i++) {
10319            String perm = pkg.requestedPermissions.get(i);
10320            BasePermission bp = mSettings.mPermissions.get(perm);
10321            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10322                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10323                if (appOpPkgs != null) {
10324                    appOpPkgs.remove(pkg.packageName);
10325                    if (appOpPkgs.isEmpty()) {
10326                        mAppOpPermissionPackages.remove(perm);
10327                    }
10328                }
10329            }
10330        }
10331        if (r != null) {
10332            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10333        }
10334
10335        N = pkg.instrumentation.size();
10336        r = null;
10337        for (i=0; i<N; i++) {
10338            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10339            mInstrumentation.remove(a.getComponentName());
10340            if (DEBUG_REMOVE && chatty) {
10341                if (r == null) {
10342                    r = new StringBuilder(256);
10343                } else {
10344                    r.append(' ');
10345                }
10346                r.append(a.info.name);
10347            }
10348        }
10349        if (r != null) {
10350            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10351        }
10352
10353        r = null;
10354        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10355            // Only system apps can hold shared libraries.
10356            if (pkg.libraryNames != null) {
10357                for (i=0; i<pkg.libraryNames.size(); i++) {
10358                    String name = pkg.libraryNames.get(i);
10359                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10360                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10361                        mSharedLibraries.remove(name);
10362                        if (DEBUG_REMOVE && chatty) {
10363                            if (r == null) {
10364                                r = new StringBuilder(256);
10365                            } else {
10366                                r.append(' ');
10367                            }
10368                            r.append(name);
10369                        }
10370                    }
10371                }
10372            }
10373        }
10374        if (r != null) {
10375            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10376        }
10377    }
10378
10379    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10380        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10381            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10382                return true;
10383            }
10384        }
10385        return false;
10386    }
10387
10388    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10389    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10390    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10391
10392    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10393        // Update the parent permissions
10394        updatePermissionsLPw(pkg.packageName, pkg, flags);
10395        // Update the child permissions
10396        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10397        for (int i = 0; i < childCount; i++) {
10398            PackageParser.Package childPkg = pkg.childPackages.get(i);
10399            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10400        }
10401    }
10402
10403    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10404            int flags) {
10405        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10406        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10407    }
10408
10409    private void updatePermissionsLPw(String changingPkg,
10410            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10411        // Make sure there are no dangling permission trees.
10412        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10413        while (it.hasNext()) {
10414            final BasePermission bp = it.next();
10415            if (bp.packageSetting == null) {
10416                // We may not yet have parsed the package, so just see if
10417                // we still know about its settings.
10418                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10419            }
10420            if (bp.packageSetting == null) {
10421                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10422                        + " from package " + bp.sourcePackage);
10423                it.remove();
10424            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10425                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10426                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10427                            + " from package " + bp.sourcePackage);
10428                    flags |= UPDATE_PERMISSIONS_ALL;
10429                    it.remove();
10430                }
10431            }
10432        }
10433
10434        // Make sure all dynamic permissions have been assigned to a package,
10435        // and make sure there are no dangling permissions.
10436        it = mSettings.mPermissions.values().iterator();
10437        while (it.hasNext()) {
10438            final BasePermission bp = it.next();
10439            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10440                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10441                        + bp.name + " pkg=" + bp.sourcePackage
10442                        + " info=" + bp.pendingInfo);
10443                if (bp.packageSetting == null && bp.pendingInfo != null) {
10444                    final BasePermission tree = findPermissionTreeLP(bp.name);
10445                    if (tree != null && tree.perm != null) {
10446                        bp.packageSetting = tree.packageSetting;
10447                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10448                                new PermissionInfo(bp.pendingInfo));
10449                        bp.perm.info.packageName = tree.perm.info.packageName;
10450                        bp.perm.info.name = bp.name;
10451                        bp.uid = tree.uid;
10452                    }
10453                }
10454            }
10455            if (bp.packageSetting == null) {
10456                // We may not yet have parsed the package, so just see if
10457                // we still know about its settings.
10458                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10459            }
10460            if (bp.packageSetting == null) {
10461                Slog.w(TAG, "Removing dangling permission: " + bp.name
10462                        + " from package " + bp.sourcePackage);
10463                it.remove();
10464            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10465                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10466                    Slog.i(TAG, "Removing old permission: " + bp.name
10467                            + " from package " + bp.sourcePackage);
10468                    flags |= UPDATE_PERMISSIONS_ALL;
10469                    it.remove();
10470                }
10471            }
10472        }
10473
10474        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10475        // Now update the permissions for all packages, in particular
10476        // replace the granted permissions of the system packages.
10477        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10478            for (PackageParser.Package pkg : mPackages.values()) {
10479                if (pkg != pkgInfo) {
10480                    // Only replace for packages on requested volume
10481                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10482                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10483                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10484                    grantPermissionsLPw(pkg, replace, changingPkg);
10485                }
10486            }
10487        }
10488
10489        if (pkgInfo != null) {
10490            // Only replace for packages on requested volume
10491            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10492            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10493                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10494            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10495        }
10496        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10497    }
10498
10499    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10500            String packageOfInterest) {
10501        // IMPORTANT: There are two types of permissions: install and runtime.
10502        // Install time permissions are granted when the app is installed to
10503        // all device users and users added in the future. Runtime permissions
10504        // are granted at runtime explicitly to specific users. Normal and signature
10505        // protected permissions are install time permissions. Dangerous permissions
10506        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10507        // otherwise they are runtime permissions. This function does not manage
10508        // runtime permissions except for the case an app targeting Lollipop MR1
10509        // being upgraded to target a newer SDK, in which case dangerous permissions
10510        // are transformed from install time to runtime ones.
10511
10512        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10513        if (ps == null) {
10514            return;
10515        }
10516
10517        PermissionsState permissionsState = ps.getPermissionsState();
10518        PermissionsState origPermissions = permissionsState;
10519
10520        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10521
10522        boolean runtimePermissionsRevoked = false;
10523        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10524
10525        boolean changedInstallPermission = false;
10526
10527        if (replace) {
10528            ps.installPermissionsFixed = false;
10529            if (!ps.isSharedUser()) {
10530                origPermissions = new PermissionsState(permissionsState);
10531                permissionsState.reset();
10532            } else {
10533                // We need to know only about runtime permission changes since the
10534                // calling code always writes the install permissions state but
10535                // the runtime ones are written only if changed. The only cases of
10536                // changed runtime permissions here are promotion of an install to
10537                // runtime and revocation of a runtime from a shared user.
10538                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10539                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10540                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10541                    runtimePermissionsRevoked = true;
10542                }
10543            }
10544        }
10545
10546        permissionsState.setGlobalGids(mGlobalGids);
10547
10548        final int N = pkg.requestedPermissions.size();
10549        for (int i=0; i<N; i++) {
10550            final String name = pkg.requestedPermissions.get(i);
10551            final BasePermission bp = mSettings.mPermissions.get(name);
10552
10553            if (DEBUG_INSTALL) {
10554                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10555            }
10556
10557            if (bp == null || bp.packageSetting == null) {
10558                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10559                    Slog.w(TAG, "Unknown permission " + name
10560                            + " in package " + pkg.packageName);
10561                }
10562                continue;
10563            }
10564
10565
10566            // Limit ephemeral apps to ephemeral allowed permissions.
10567            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10568                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10569                        + pkg.packageName);
10570                continue;
10571            }
10572
10573            final String perm = bp.name;
10574            boolean allowedSig = false;
10575            int grant = GRANT_DENIED;
10576
10577            // Keep track of app op permissions.
10578            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10579                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10580                if (pkgs == null) {
10581                    pkgs = new ArraySet<>();
10582                    mAppOpPermissionPackages.put(bp.name, pkgs);
10583                }
10584                pkgs.add(pkg.packageName);
10585            }
10586
10587            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10588            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10589                    >= Build.VERSION_CODES.M;
10590            switch (level) {
10591                case PermissionInfo.PROTECTION_NORMAL: {
10592                    // For all apps normal permissions are install time ones.
10593                    grant = GRANT_INSTALL;
10594                } break;
10595
10596                case PermissionInfo.PROTECTION_DANGEROUS: {
10597                    // If a permission review is required for legacy apps we represent
10598                    // their permissions as always granted runtime ones since we need
10599                    // to keep the review required permission flag per user while an
10600                    // install permission's state is shared across all users.
10601                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10602                        // For legacy apps dangerous permissions are install time ones.
10603                        grant = GRANT_INSTALL;
10604                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10605                        // For legacy apps that became modern, install becomes runtime.
10606                        grant = GRANT_UPGRADE;
10607                    } else if (mPromoteSystemApps
10608                            && isSystemApp(ps)
10609                            && mExistingSystemPackages.contains(ps.name)) {
10610                        // For legacy system apps, install becomes runtime.
10611                        // We cannot check hasInstallPermission() for system apps since those
10612                        // permissions were granted implicitly and not persisted pre-M.
10613                        grant = GRANT_UPGRADE;
10614                    } else {
10615                        // For modern apps keep runtime permissions unchanged.
10616                        grant = GRANT_RUNTIME;
10617                    }
10618                } break;
10619
10620                case PermissionInfo.PROTECTION_SIGNATURE: {
10621                    // For all apps signature permissions are install time ones.
10622                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10623                    if (allowedSig) {
10624                        grant = GRANT_INSTALL;
10625                    }
10626                } break;
10627            }
10628
10629            if (DEBUG_INSTALL) {
10630                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10631            }
10632
10633            if (grant != GRANT_DENIED) {
10634                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10635                    // If this is an existing, non-system package, then
10636                    // we can't add any new permissions to it.
10637                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10638                        // Except...  if this is a permission that was added
10639                        // to the platform (note: need to only do this when
10640                        // updating the platform).
10641                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10642                            grant = GRANT_DENIED;
10643                        }
10644                    }
10645                }
10646
10647                switch (grant) {
10648                    case GRANT_INSTALL: {
10649                        // Revoke this as runtime permission to handle the case of
10650                        // a runtime permission being downgraded to an install one.
10651                        // Also in permission review mode we keep dangerous permissions
10652                        // for legacy apps
10653                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10654                            if (origPermissions.getRuntimePermissionState(
10655                                    bp.name, userId) != null) {
10656                                // Revoke the runtime permission and clear the flags.
10657                                origPermissions.revokeRuntimePermission(bp, userId);
10658                                origPermissions.updatePermissionFlags(bp, userId,
10659                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10660                                // If we revoked a permission permission, we have to write.
10661                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10662                                        changedRuntimePermissionUserIds, userId);
10663                            }
10664                        }
10665                        // Grant an install permission.
10666                        if (permissionsState.grantInstallPermission(bp) !=
10667                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10668                            changedInstallPermission = true;
10669                        }
10670                    } break;
10671
10672                    case GRANT_RUNTIME: {
10673                        // Grant previously granted runtime permissions.
10674                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10675                            PermissionState permissionState = origPermissions
10676                                    .getRuntimePermissionState(bp.name, userId);
10677                            int flags = permissionState != null
10678                                    ? permissionState.getFlags() : 0;
10679                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10680                                // Don't propagate the permission in a permission review mode if
10681                                // the former was revoked, i.e. marked to not propagate on upgrade.
10682                                // Note that in a permission review mode install permissions are
10683                                // represented as constantly granted runtime ones since we need to
10684                                // keep a per user state associated with the permission. Also the
10685                                // revoke on upgrade flag is no longer applicable and is reset.
10686                                final boolean revokeOnUpgrade = (flags & PackageManager
10687                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10688                                if (revokeOnUpgrade) {
10689                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10690                                    // Since we changed the flags, we have to write.
10691                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10692                                            changedRuntimePermissionUserIds, userId);
10693                                }
10694                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10695                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
10696                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
10697                                        // If we cannot put the permission as it was,
10698                                        // we have to write.
10699                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10700                                                changedRuntimePermissionUserIds, userId);
10701                                    }
10702                                }
10703
10704                                // If the app supports runtime permissions no need for a review.
10705                                if (mPermissionReviewRequired
10706                                        && appSupportsRuntimePermissions
10707                                        && (flags & PackageManager
10708                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10709                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10710                                    // Since we changed the flags, we have to write.
10711                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10712                                            changedRuntimePermissionUserIds, userId);
10713                                }
10714                            } else if (mPermissionReviewRequired
10715                                    && !appSupportsRuntimePermissions) {
10716                                // For legacy apps that need a permission review, every new
10717                                // runtime permission is granted but it is pending a review.
10718                                // We also need to review only platform defined runtime
10719                                // permissions as these are the only ones the platform knows
10720                                // how to disable the API to simulate revocation as legacy
10721                                // apps don't expect to run with revoked permissions.
10722                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10723                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10724                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10725                                        // We changed the flags, hence have to write.
10726                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10727                                                changedRuntimePermissionUserIds, userId);
10728                                    }
10729                                }
10730                                if (permissionsState.grantRuntimePermission(bp, userId)
10731                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10732                                    // We changed the permission, hence have to write.
10733                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10734                                            changedRuntimePermissionUserIds, userId);
10735                                }
10736                            }
10737                            // Propagate the permission flags.
10738                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10739                        }
10740                    } break;
10741
10742                    case GRANT_UPGRADE: {
10743                        // Grant runtime permissions for a previously held install permission.
10744                        PermissionState permissionState = origPermissions
10745                                .getInstallPermissionState(bp.name);
10746                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10747
10748                        if (origPermissions.revokeInstallPermission(bp)
10749                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10750                            // We will be transferring the permission flags, so clear them.
10751                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10752                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10753                            changedInstallPermission = true;
10754                        }
10755
10756                        // If the permission is not to be promoted to runtime we ignore it and
10757                        // also its other flags as they are not applicable to install permissions.
10758                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10759                            for (int userId : currentUserIds) {
10760                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10761                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10762                                    // Transfer the permission flags.
10763                                    permissionsState.updatePermissionFlags(bp, userId,
10764                                            flags, flags);
10765                                    // If we granted the permission, we have to write.
10766                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10767                                            changedRuntimePermissionUserIds, userId);
10768                                }
10769                            }
10770                        }
10771                    } break;
10772
10773                    default: {
10774                        if (packageOfInterest == null
10775                                || packageOfInterest.equals(pkg.packageName)) {
10776                            Slog.w(TAG, "Not granting permission " + perm
10777                                    + " to package " + pkg.packageName
10778                                    + " because it was previously installed without");
10779                        }
10780                    } break;
10781                }
10782            } else {
10783                if (permissionsState.revokeInstallPermission(bp) !=
10784                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10785                    // Also drop the permission flags.
10786                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10787                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10788                    changedInstallPermission = true;
10789                    Slog.i(TAG, "Un-granting permission " + perm
10790                            + " from package " + pkg.packageName
10791                            + " (protectionLevel=" + bp.protectionLevel
10792                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10793                            + ")");
10794                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10795                    // Don't print warning for app op permissions, since it is fine for them
10796                    // not to be granted, there is a UI for the user to decide.
10797                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10798                        Slog.w(TAG, "Not granting permission " + perm
10799                                + " to package " + pkg.packageName
10800                                + " (protectionLevel=" + bp.protectionLevel
10801                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10802                                + ")");
10803                    }
10804                }
10805            }
10806        }
10807
10808        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10809                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10810            // This is the first that we have heard about this package, so the
10811            // permissions we have now selected are fixed until explicitly
10812            // changed.
10813            ps.installPermissionsFixed = true;
10814        }
10815
10816        // Persist the runtime permissions state for users with changes. If permissions
10817        // were revoked because no app in the shared user declares them we have to
10818        // write synchronously to avoid losing runtime permissions state.
10819        for (int userId : changedRuntimePermissionUserIds) {
10820            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10821        }
10822    }
10823
10824    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10825        boolean allowed = false;
10826        final int NP = PackageParser.NEW_PERMISSIONS.length;
10827        for (int ip=0; ip<NP; ip++) {
10828            final PackageParser.NewPermissionInfo npi
10829                    = PackageParser.NEW_PERMISSIONS[ip];
10830            if (npi.name.equals(perm)
10831                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10832                allowed = true;
10833                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10834                        + pkg.packageName);
10835                break;
10836            }
10837        }
10838        return allowed;
10839    }
10840
10841    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10842            BasePermission bp, PermissionsState origPermissions) {
10843        boolean privilegedPermission = (bp.protectionLevel
10844                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10845        boolean privappPermissionsDisable =
10846                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10847        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10848        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10849        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10850                && !platformPackage && platformPermission) {
10851            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10852                    .getPrivAppPermissions(pkg.packageName);
10853            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10854            if (!whitelisted) {
10855                Slog.w(TAG, "Privileged permission " + perm + " for package "
10856                        + pkg.packageName + " - not in privapp-permissions whitelist");
10857                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10858                    return false;
10859                }
10860            }
10861        }
10862        boolean allowed = (compareSignatures(
10863                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10864                        == PackageManager.SIGNATURE_MATCH)
10865                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10866                        == PackageManager.SIGNATURE_MATCH);
10867        if (!allowed && privilegedPermission) {
10868            if (isSystemApp(pkg)) {
10869                // For updated system applications, a system permission
10870                // is granted only if it had been defined by the original application.
10871                if (pkg.isUpdatedSystemApp()) {
10872                    final PackageSetting sysPs = mSettings
10873                            .getDisabledSystemPkgLPr(pkg.packageName);
10874                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10875                        // If the original was granted this permission, we take
10876                        // that grant decision as read and propagate it to the
10877                        // update.
10878                        if (sysPs.isPrivileged()) {
10879                            allowed = true;
10880                        }
10881                    } else {
10882                        // The system apk may have been updated with an older
10883                        // version of the one on the data partition, but which
10884                        // granted a new system permission that it didn't have
10885                        // before.  In this case we do want to allow the app to
10886                        // now get the new permission if the ancestral apk is
10887                        // privileged to get it.
10888                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10889                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10890                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10891                                    allowed = true;
10892                                    break;
10893                                }
10894                            }
10895                        }
10896                        // Also if a privileged parent package on the system image or any of
10897                        // its children requested a privileged permission, the updated child
10898                        // packages can also get the permission.
10899                        if (pkg.parentPackage != null) {
10900                            final PackageSetting disabledSysParentPs = mSettings
10901                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10902                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10903                                    && disabledSysParentPs.isPrivileged()) {
10904                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10905                                    allowed = true;
10906                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10907                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10908                                    for (int i = 0; i < count; i++) {
10909                                        PackageParser.Package disabledSysChildPkg =
10910                                                disabledSysParentPs.pkg.childPackages.get(i);
10911                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10912                                                perm)) {
10913                                            allowed = true;
10914                                            break;
10915                                        }
10916                                    }
10917                                }
10918                            }
10919                        }
10920                    }
10921                } else {
10922                    allowed = isPrivilegedApp(pkg);
10923                }
10924            }
10925        }
10926        if (!allowed) {
10927            if (!allowed && (bp.protectionLevel
10928                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10929                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10930                // If this was a previously normal/dangerous permission that got moved
10931                // to a system permission as part of the runtime permission redesign, then
10932                // we still want to blindly grant it to old apps.
10933                allowed = true;
10934            }
10935            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10936                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10937                // If this permission is to be granted to the system installer and
10938                // this app is an installer, then it gets the permission.
10939                allowed = true;
10940            }
10941            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10942                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10943                // If this permission is to be granted to the system verifier and
10944                // this app is a verifier, then it gets the permission.
10945                allowed = true;
10946            }
10947            if (!allowed && (bp.protectionLevel
10948                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10949                    && isSystemApp(pkg)) {
10950                // Any pre-installed system app is allowed to get this permission.
10951                allowed = true;
10952            }
10953            if (!allowed && (bp.protectionLevel
10954                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10955                // For development permissions, a development permission
10956                // is granted only if it was already granted.
10957                allowed = origPermissions.hasInstallPermission(perm);
10958            }
10959            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10960                    && pkg.packageName.equals(mSetupWizardPackage)) {
10961                // If this permission is to be granted to the system setup wizard and
10962                // this app is a setup wizard, then it gets the permission.
10963                allowed = true;
10964            }
10965        }
10966        return allowed;
10967    }
10968
10969    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10970        final int permCount = pkg.requestedPermissions.size();
10971        for (int j = 0; j < permCount; j++) {
10972            String requestedPermission = pkg.requestedPermissions.get(j);
10973            if (permission.equals(requestedPermission)) {
10974                return true;
10975            }
10976        }
10977        return false;
10978    }
10979
10980    final class ActivityIntentResolver
10981            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10982        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10983                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10984            if (!sUserManager.exists(userId)) return null;
10985            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10986                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10987                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10988            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10989                    isEphemeral, userId);
10990        }
10991
10992        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10993                int userId) {
10994            if (!sUserManager.exists(userId)) return null;
10995            mFlags = flags;
10996            return super.queryIntent(intent, resolvedType,
10997                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10998                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10999                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11000        }
11001
11002        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11003                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11004            if (!sUserManager.exists(userId)) return null;
11005            if (packageActivities == null) {
11006                return null;
11007            }
11008            mFlags = flags;
11009            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11010            final boolean vislbleToEphemeral =
11011                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11012            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11013            final int N = packageActivities.size();
11014            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11015                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11016
11017            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11018            for (int i = 0; i < N; ++i) {
11019                intentFilters = packageActivities.get(i).intents;
11020                if (intentFilters != null && intentFilters.size() > 0) {
11021                    PackageParser.ActivityIntentInfo[] array =
11022                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11023                    intentFilters.toArray(array);
11024                    listCut.add(array);
11025                }
11026            }
11027            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11028                    vislbleToEphemeral, isEphemeral, listCut, userId);
11029        }
11030
11031        /**
11032         * Finds a privileged activity that matches the specified activity names.
11033         */
11034        private PackageParser.Activity findMatchingActivity(
11035                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11036            for (PackageParser.Activity sysActivity : activityList) {
11037                if (sysActivity.info.name.equals(activityInfo.name)) {
11038                    return sysActivity;
11039                }
11040                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11041                    return sysActivity;
11042                }
11043                if (sysActivity.info.targetActivity != null) {
11044                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11045                        return sysActivity;
11046                    }
11047                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11048                        return sysActivity;
11049                    }
11050                }
11051            }
11052            return null;
11053        }
11054
11055        public class IterGenerator<E> {
11056            public Iterator<E> generate(ActivityIntentInfo info) {
11057                return null;
11058            }
11059        }
11060
11061        public class ActionIterGenerator extends IterGenerator<String> {
11062            @Override
11063            public Iterator<String> generate(ActivityIntentInfo info) {
11064                return info.actionsIterator();
11065            }
11066        }
11067
11068        public class CategoriesIterGenerator extends IterGenerator<String> {
11069            @Override
11070            public Iterator<String> generate(ActivityIntentInfo info) {
11071                return info.categoriesIterator();
11072            }
11073        }
11074
11075        public class SchemesIterGenerator extends IterGenerator<String> {
11076            @Override
11077            public Iterator<String> generate(ActivityIntentInfo info) {
11078                return info.schemesIterator();
11079            }
11080        }
11081
11082        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11083            @Override
11084            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11085                return info.authoritiesIterator();
11086            }
11087        }
11088
11089        /**
11090         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11091         * MODIFIED. Do not pass in a list that should not be changed.
11092         */
11093        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11094                IterGenerator<T> generator, Iterator<T> searchIterator) {
11095            // loop through the set of actions; every one must be found in the intent filter
11096            while (searchIterator.hasNext()) {
11097                // we must have at least one filter in the list to consider a match
11098                if (intentList.size() == 0) {
11099                    break;
11100                }
11101
11102                final T searchAction = searchIterator.next();
11103
11104                // loop through the set of intent filters
11105                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11106                while (intentIter.hasNext()) {
11107                    final ActivityIntentInfo intentInfo = intentIter.next();
11108                    boolean selectionFound = false;
11109
11110                    // loop through the intent filter's selection criteria; at least one
11111                    // of them must match the searched criteria
11112                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11113                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11114                        final T intentSelection = intentSelectionIter.next();
11115                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11116                            selectionFound = true;
11117                            break;
11118                        }
11119                    }
11120
11121                    // the selection criteria wasn't found in this filter's set; this filter
11122                    // is not a potential match
11123                    if (!selectionFound) {
11124                        intentIter.remove();
11125                    }
11126                }
11127            }
11128        }
11129
11130        private boolean isProtectedAction(ActivityIntentInfo filter) {
11131            final Iterator<String> actionsIter = filter.actionsIterator();
11132            while (actionsIter != null && actionsIter.hasNext()) {
11133                final String filterAction = actionsIter.next();
11134                if (PROTECTED_ACTIONS.contains(filterAction)) {
11135                    return true;
11136                }
11137            }
11138            return false;
11139        }
11140
11141        /**
11142         * Adjusts the priority of the given intent filter according to policy.
11143         * <p>
11144         * <ul>
11145         * <li>The priority for non privileged applications is capped to '0'</li>
11146         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11147         * <li>The priority for unbundled updates to privileged applications is capped to the
11148         *      priority defined on the system partition</li>
11149         * </ul>
11150         * <p>
11151         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11152         * allowed to obtain any priority on any action.
11153         */
11154        private void adjustPriority(
11155                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11156            // nothing to do; priority is fine as-is
11157            if (intent.getPriority() <= 0) {
11158                return;
11159            }
11160
11161            final ActivityInfo activityInfo = intent.activity.info;
11162            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11163
11164            final boolean privilegedApp =
11165                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11166            if (!privilegedApp) {
11167                // non-privileged applications can never define a priority >0
11168                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11169                        + " package: " + applicationInfo.packageName
11170                        + " activity: " + intent.activity.className
11171                        + " origPrio: " + intent.getPriority());
11172                intent.setPriority(0);
11173                return;
11174            }
11175
11176            if (systemActivities == null) {
11177                // the system package is not disabled; we're parsing the system partition
11178                if (isProtectedAction(intent)) {
11179                    if (mDeferProtectedFilters) {
11180                        // We can't deal with these just yet. No component should ever obtain a
11181                        // >0 priority for a protected actions, with ONE exception -- the setup
11182                        // wizard. The setup wizard, however, cannot be known until we're able to
11183                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11184                        // until all intent filters have been processed. Chicken, meet egg.
11185                        // Let the filter temporarily have a high priority and rectify the
11186                        // priorities after all system packages have been scanned.
11187                        mProtectedFilters.add(intent);
11188                        if (DEBUG_FILTERS) {
11189                            Slog.i(TAG, "Protected action; save for later;"
11190                                    + " package: " + applicationInfo.packageName
11191                                    + " activity: " + intent.activity.className
11192                                    + " origPrio: " + intent.getPriority());
11193                        }
11194                        return;
11195                    } else {
11196                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11197                            Slog.i(TAG, "No setup wizard;"
11198                                + " All protected intents capped to priority 0");
11199                        }
11200                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11201                            if (DEBUG_FILTERS) {
11202                                Slog.i(TAG, "Found setup wizard;"
11203                                    + " allow priority " + intent.getPriority() + ";"
11204                                    + " package: " + intent.activity.info.packageName
11205                                    + " activity: " + intent.activity.className
11206                                    + " priority: " + intent.getPriority());
11207                            }
11208                            // setup wizard gets whatever it wants
11209                            return;
11210                        }
11211                        Slog.w(TAG, "Protected action; cap priority to 0;"
11212                                + " package: " + intent.activity.info.packageName
11213                                + " activity: " + intent.activity.className
11214                                + " origPrio: " + intent.getPriority());
11215                        intent.setPriority(0);
11216                        return;
11217                    }
11218                }
11219                // privileged apps on the system image get whatever priority they request
11220                return;
11221            }
11222
11223            // privileged app unbundled update ... try to find the same activity
11224            final PackageParser.Activity foundActivity =
11225                    findMatchingActivity(systemActivities, activityInfo);
11226            if (foundActivity == null) {
11227                // this is a new activity; it cannot obtain >0 priority
11228                if (DEBUG_FILTERS) {
11229                    Slog.i(TAG, "New activity; cap priority to 0;"
11230                            + " package: " + applicationInfo.packageName
11231                            + " activity: " + intent.activity.className
11232                            + " origPrio: " + intent.getPriority());
11233                }
11234                intent.setPriority(0);
11235                return;
11236            }
11237
11238            // found activity, now check for filter equivalence
11239
11240            // a shallow copy is enough; we modify the list, not its contents
11241            final List<ActivityIntentInfo> intentListCopy =
11242                    new ArrayList<>(foundActivity.intents);
11243            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11244
11245            // find matching action subsets
11246            final Iterator<String> actionsIterator = intent.actionsIterator();
11247            if (actionsIterator != null) {
11248                getIntentListSubset(
11249                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11250                if (intentListCopy.size() == 0) {
11251                    // no more intents to match; we're not equivalent
11252                    if (DEBUG_FILTERS) {
11253                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11254                                + " package: " + applicationInfo.packageName
11255                                + " activity: " + intent.activity.className
11256                                + " origPrio: " + intent.getPriority());
11257                    }
11258                    intent.setPriority(0);
11259                    return;
11260                }
11261            }
11262
11263            // find matching category subsets
11264            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11265            if (categoriesIterator != null) {
11266                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11267                        categoriesIterator);
11268                if (intentListCopy.size() == 0) {
11269                    // no more intents to match; we're not equivalent
11270                    if (DEBUG_FILTERS) {
11271                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11272                                + " package: " + applicationInfo.packageName
11273                                + " activity: " + intent.activity.className
11274                                + " origPrio: " + intent.getPriority());
11275                    }
11276                    intent.setPriority(0);
11277                    return;
11278                }
11279            }
11280
11281            // find matching schemes subsets
11282            final Iterator<String> schemesIterator = intent.schemesIterator();
11283            if (schemesIterator != null) {
11284                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11285                        schemesIterator);
11286                if (intentListCopy.size() == 0) {
11287                    // no more intents to match; we're not equivalent
11288                    if (DEBUG_FILTERS) {
11289                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11290                                + " package: " + applicationInfo.packageName
11291                                + " activity: " + intent.activity.className
11292                                + " origPrio: " + intent.getPriority());
11293                    }
11294                    intent.setPriority(0);
11295                    return;
11296                }
11297            }
11298
11299            // find matching authorities subsets
11300            final Iterator<IntentFilter.AuthorityEntry>
11301                    authoritiesIterator = intent.authoritiesIterator();
11302            if (authoritiesIterator != null) {
11303                getIntentListSubset(intentListCopy,
11304                        new AuthoritiesIterGenerator(),
11305                        authoritiesIterator);
11306                if (intentListCopy.size() == 0) {
11307                    // no more intents to match; we're not equivalent
11308                    if (DEBUG_FILTERS) {
11309                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11310                                + " package: " + applicationInfo.packageName
11311                                + " activity: " + intent.activity.className
11312                                + " origPrio: " + intent.getPriority());
11313                    }
11314                    intent.setPriority(0);
11315                    return;
11316                }
11317            }
11318
11319            // we found matching filter(s); app gets the max priority of all intents
11320            int cappedPriority = 0;
11321            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11322                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11323            }
11324            if (intent.getPriority() > cappedPriority) {
11325                if (DEBUG_FILTERS) {
11326                    Slog.i(TAG, "Found matching filter(s);"
11327                            + " cap priority to " + cappedPriority + ";"
11328                            + " package: " + applicationInfo.packageName
11329                            + " activity: " + intent.activity.className
11330                            + " origPrio: " + intent.getPriority());
11331                }
11332                intent.setPriority(cappedPriority);
11333                return;
11334            }
11335            // all this for nothing; the requested priority was <= what was on the system
11336        }
11337
11338        public final void addActivity(PackageParser.Activity a, String type) {
11339            mActivities.put(a.getComponentName(), a);
11340            if (DEBUG_SHOW_INFO)
11341                Log.v(
11342                TAG, "  " + type + " " +
11343                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11344            if (DEBUG_SHOW_INFO)
11345                Log.v(TAG, "    Class=" + a.info.name);
11346            final int NI = a.intents.size();
11347            for (int j=0; j<NI; j++) {
11348                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11349                if ("activity".equals(type)) {
11350                    final PackageSetting ps =
11351                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11352                    final List<PackageParser.Activity> systemActivities =
11353                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11354                    adjustPriority(systemActivities, intent);
11355                }
11356                if (DEBUG_SHOW_INFO) {
11357                    Log.v(TAG, "    IntentFilter:");
11358                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11359                }
11360                if (!intent.debugCheck()) {
11361                    Log.w(TAG, "==> For Activity " + a.info.name);
11362                }
11363                addFilter(intent);
11364            }
11365        }
11366
11367        public final void removeActivity(PackageParser.Activity a, String type) {
11368            mActivities.remove(a.getComponentName());
11369            if (DEBUG_SHOW_INFO) {
11370                Log.v(TAG, "  " + type + " "
11371                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11372                                : a.info.name) + ":");
11373                Log.v(TAG, "    Class=" + a.info.name);
11374            }
11375            final int NI = a.intents.size();
11376            for (int j=0; j<NI; j++) {
11377                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11378                if (DEBUG_SHOW_INFO) {
11379                    Log.v(TAG, "    IntentFilter:");
11380                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11381                }
11382                removeFilter(intent);
11383            }
11384        }
11385
11386        @Override
11387        protected boolean allowFilterResult(
11388                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11389            ActivityInfo filterAi = filter.activity.info;
11390            for (int i=dest.size()-1; i>=0; i--) {
11391                ActivityInfo destAi = dest.get(i).activityInfo;
11392                if (destAi.name == filterAi.name
11393                        && destAi.packageName == filterAi.packageName) {
11394                    return false;
11395                }
11396            }
11397            return true;
11398        }
11399
11400        @Override
11401        protected ActivityIntentInfo[] newArray(int size) {
11402            return new ActivityIntentInfo[size];
11403        }
11404
11405        @Override
11406        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11407            if (!sUserManager.exists(userId)) return true;
11408            PackageParser.Package p = filter.activity.owner;
11409            if (p != null) {
11410                PackageSetting ps = (PackageSetting)p.mExtras;
11411                if (ps != null) {
11412                    // System apps are never considered stopped for purposes of
11413                    // filtering, because there may be no way for the user to
11414                    // actually re-launch them.
11415                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11416                            && ps.getStopped(userId);
11417                }
11418            }
11419            return false;
11420        }
11421
11422        @Override
11423        protected boolean isPackageForFilter(String packageName,
11424                PackageParser.ActivityIntentInfo info) {
11425            return packageName.equals(info.activity.owner.packageName);
11426        }
11427
11428        @Override
11429        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11430                int match, int userId) {
11431            if (!sUserManager.exists(userId)) return null;
11432            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11433                return null;
11434            }
11435            final PackageParser.Activity activity = info.activity;
11436            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11437            if (ps == null) {
11438                return null;
11439            }
11440            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11441                    ps.readUserState(userId), userId);
11442            if (ai == null) {
11443                return null;
11444            }
11445            final ResolveInfo res = new ResolveInfo();
11446            res.activityInfo = ai;
11447            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11448                res.filter = info;
11449            }
11450            if (info != null) {
11451                res.handleAllWebDataURI = info.handleAllWebDataURI();
11452            }
11453            res.priority = info.getPriority();
11454            res.preferredOrder = activity.owner.mPreferredOrder;
11455            //System.out.println("Result: " + res.activityInfo.className +
11456            //                   " = " + res.priority);
11457            res.match = match;
11458            res.isDefault = info.hasDefault;
11459            res.labelRes = info.labelRes;
11460            res.nonLocalizedLabel = info.nonLocalizedLabel;
11461            if (userNeedsBadging(userId)) {
11462                res.noResourceId = true;
11463            } else {
11464                res.icon = info.icon;
11465            }
11466            res.iconResourceId = info.icon;
11467            res.system = res.activityInfo.applicationInfo.isSystemApp();
11468            return res;
11469        }
11470
11471        @Override
11472        protected void sortResults(List<ResolveInfo> results) {
11473            Collections.sort(results, mResolvePrioritySorter);
11474        }
11475
11476        @Override
11477        protected void dumpFilter(PrintWriter out, String prefix,
11478                PackageParser.ActivityIntentInfo filter) {
11479            out.print(prefix); out.print(
11480                    Integer.toHexString(System.identityHashCode(filter.activity)));
11481                    out.print(' ');
11482                    filter.activity.printComponentShortName(out);
11483                    out.print(" filter ");
11484                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11485        }
11486
11487        @Override
11488        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11489            return filter.activity;
11490        }
11491
11492        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11493            PackageParser.Activity activity = (PackageParser.Activity)label;
11494            out.print(prefix); out.print(
11495                    Integer.toHexString(System.identityHashCode(activity)));
11496                    out.print(' ');
11497                    activity.printComponentShortName(out);
11498            if (count > 1) {
11499                out.print(" ("); out.print(count); out.print(" filters)");
11500            }
11501            out.println();
11502        }
11503
11504        // Keys are String (activity class name), values are Activity.
11505        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11506                = new ArrayMap<ComponentName, PackageParser.Activity>();
11507        private int mFlags;
11508    }
11509
11510    private final class ServiceIntentResolver
11511            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11512        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11513                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11514            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11515            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11516                    isEphemeral, userId);
11517        }
11518
11519        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11520                int userId) {
11521            if (!sUserManager.exists(userId)) return null;
11522            mFlags = flags;
11523            return super.queryIntent(intent, resolvedType,
11524                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11525                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11526                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11527        }
11528
11529        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11530                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11531            if (!sUserManager.exists(userId)) return null;
11532            if (packageServices == null) {
11533                return null;
11534            }
11535            mFlags = flags;
11536            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11537            final boolean vislbleToEphemeral =
11538                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11539            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11540            final int N = packageServices.size();
11541            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11542                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11543
11544            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11545            for (int i = 0; i < N; ++i) {
11546                intentFilters = packageServices.get(i).intents;
11547                if (intentFilters != null && intentFilters.size() > 0) {
11548                    PackageParser.ServiceIntentInfo[] array =
11549                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11550                    intentFilters.toArray(array);
11551                    listCut.add(array);
11552                }
11553            }
11554            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11555                    vislbleToEphemeral, isEphemeral, listCut, userId);
11556        }
11557
11558        public final void addService(PackageParser.Service s) {
11559            mServices.put(s.getComponentName(), s);
11560            if (DEBUG_SHOW_INFO) {
11561                Log.v(TAG, "  "
11562                        + (s.info.nonLocalizedLabel != null
11563                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11564                Log.v(TAG, "    Class=" + s.info.name);
11565            }
11566            final int NI = s.intents.size();
11567            int j;
11568            for (j=0; j<NI; j++) {
11569                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11570                if (DEBUG_SHOW_INFO) {
11571                    Log.v(TAG, "    IntentFilter:");
11572                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11573                }
11574                if (!intent.debugCheck()) {
11575                    Log.w(TAG, "==> For Service " + s.info.name);
11576                }
11577                addFilter(intent);
11578            }
11579        }
11580
11581        public final void removeService(PackageParser.Service s) {
11582            mServices.remove(s.getComponentName());
11583            if (DEBUG_SHOW_INFO) {
11584                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11585                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11586                Log.v(TAG, "    Class=" + s.info.name);
11587            }
11588            final int NI = s.intents.size();
11589            int j;
11590            for (j=0; j<NI; j++) {
11591                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11592                if (DEBUG_SHOW_INFO) {
11593                    Log.v(TAG, "    IntentFilter:");
11594                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11595                }
11596                removeFilter(intent);
11597            }
11598        }
11599
11600        @Override
11601        protected boolean allowFilterResult(
11602                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11603            ServiceInfo filterSi = filter.service.info;
11604            for (int i=dest.size()-1; i>=0; i--) {
11605                ServiceInfo destAi = dest.get(i).serviceInfo;
11606                if (destAi.name == filterSi.name
11607                        && destAi.packageName == filterSi.packageName) {
11608                    return false;
11609                }
11610            }
11611            return true;
11612        }
11613
11614        @Override
11615        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11616            return new PackageParser.ServiceIntentInfo[size];
11617        }
11618
11619        @Override
11620        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11621            if (!sUserManager.exists(userId)) return true;
11622            PackageParser.Package p = filter.service.owner;
11623            if (p != null) {
11624                PackageSetting ps = (PackageSetting)p.mExtras;
11625                if (ps != null) {
11626                    // System apps are never considered stopped for purposes of
11627                    // filtering, because there may be no way for the user to
11628                    // actually re-launch them.
11629                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11630                            && ps.getStopped(userId);
11631                }
11632            }
11633            return false;
11634        }
11635
11636        @Override
11637        protected boolean isPackageForFilter(String packageName,
11638                PackageParser.ServiceIntentInfo info) {
11639            return packageName.equals(info.service.owner.packageName);
11640        }
11641
11642        @Override
11643        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11644                int match, int userId) {
11645            if (!sUserManager.exists(userId)) return null;
11646            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11647            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11648                return null;
11649            }
11650            final PackageParser.Service service = info.service;
11651            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11652            if (ps == null) {
11653                return null;
11654            }
11655            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11656                    ps.readUserState(userId), userId);
11657            if (si == null) {
11658                return null;
11659            }
11660            final ResolveInfo res = new ResolveInfo();
11661            res.serviceInfo = si;
11662            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11663                res.filter = filter;
11664            }
11665            res.priority = info.getPriority();
11666            res.preferredOrder = service.owner.mPreferredOrder;
11667            res.match = match;
11668            res.isDefault = info.hasDefault;
11669            res.labelRes = info.labelRes;
11670            res.nonLocalizedLabel = info.nonLocalizedLabel;
11671            res.icon = info.icon;
11672            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11673            return res;
11674        }
11675
11676        @Override
11677        protected void sortResults(List<ResolveInfo> results) {
11678            Collections.sort(results, mResolvePrioritySorter);
11679        }
11680
11681        @Override
11682        protected void dumpFilter(PrintWriter out, String prefix,
11683                PackageParser.ServiceIntentInfo filter) {
11684            out.print(prefix); out.print(
11685                    Integer.toHexString(System.identityHashCode(filter.service)));
11686                    out.print(' ');
11687                    filter.service.printComponentShortName(out);
11688                    out.print(" filter ");
11689                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11690        }
11691
11692        @Override
11693        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11694            return filter.service;
11695        }
11696
11697        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11698            PackageParser.Service service = (PackageParser.Service)label;
11699            out.print(prefix); out.print(
11700                    Integer.toHexString(System.identityHashCode(service)));
11701                    out.print(' ');
11702                    service.printComponentShortName(out);
11703            if (count > 1) {
11704                out.print(" ("); out.print(count); out.print(" filters)");
11705            }
11706            out.println();
11707        }
11708
11709//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11710//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11711//            final List<ResolveInfo> retList = Lists.newArrayList();
11712//            while (i.hasNext()) {
11713//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11714//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11715//                    retList.add(resolveInfo);
11716//                }
11717//            }
11718//            return retList;
11719//        }
11720
11721        // Keys are String (activity class name), values are Activity.
11722        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11723                = new ArrayMap<ComponentName, PackageParser.Service>();
11724        private int mFlags;
11725    }
11726
11727    private final class ProviderIntentResolver
11728            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11729        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11730                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11731            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11732            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11733                    isEphemeral, userId);
11734        }
11735
11736        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11737                int userId) {
11738            if (!sUserManager.exists(userId))
11739                return null;
11740            mFlags = flags;
11741            return super.queryIntent(intent, resolvedType,
11742                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11743                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11744                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11745        }
11746
11747        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11748                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11749            if (!sUserManager.exists(userId))
11750                return null;
11751            if (packageProviders == null) {
11752                return null;
11753            }
11754            mFlags = flags;
11755            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11756            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11757            final boolean vislbleToEphemeral =
11758                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11759            final int N = packageProviders.size();
11760            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11761                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11762
11763            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11764            for (int i = 0; i < N; ++i) {
11765                intentFilters = packageProviders.get(i).intents;
11766                if (intentFilters != null && intentFilters.size() > 0) {
11767                    PackageParser.ProviderIntentInfo[] array =
11768                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11769                    intentFilters.toArray(array);
11770                    listCut.add(array);
11771                }
11772            }
11773            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11774                    vislbleToEphemeral, isEphemeral, listCut, userId);
11775        }
11776
11777        public final void addProvider(PackageParser.Provider p) {
11778            if (mProviders.containsKey(p.getComponentName())) {
11779                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11780                return;
11781            }
11782
11783            mProviders.put(p.getComponentName(), p);
11784            if (DEBUG_SHOW_INFO) {
11785                Log.v(TAG, "  "
11786                        + (p.info.nonLocalizedLabel != null
11787                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11788                Log.v(TAG, "    Class=" + p.info.name);
11789            }
11790            final int NI = p.intents.size();
11791            int j;
11792            for (j = 0; j < NI; j++) {
11793                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11794                if (DEBUG_SHOW_INFO) {
11795                    Log.v(TAG, "    IntentFilter:");
11796                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11797                }
11798                if (!intent.debugCheck()) {
11799                    Log.w(TAG, "==> For Provider " + p.info.name);
11800                }
11801                addFilter(intent);
11802            }
11803        }
11804
11805        public final void removeProvider(PackageParser.Provider p) {
11806            mProviders.remove(p.getComponentName());
11807            if (DEBUG_SHOW_INFO) {
11808                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11809                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11810                Log.v(TAG, "    Class=" + p.info.name);
11811            }
11812            final int NI = p.intents.size();
11813            int j;
11814            for (j = 0; j < NI; j++) {
11815                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11816                if (DEBUG_SHOW_INFO) {
11817                    Log.v(TAG, "    IntentFilter:");
11818                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11819                }
11820                removeFilter(intent);
11821            }
11822        }
11823
11824        @Override
11825        protected boolean allowFilterResult(
11826                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11827            ProviderInfo filterPi = filter.provider.info;
11828            for (int i = dest.size() - 1; i >= 0; i--) {
11829                ProviderInfo destPi = dest.get(i).providerInfo;
11830                if (destPi.name == filterPi.name
11831                        && destPi.packageName == filterPi.packageName) {
11832                    return false;
11833                }
11834            }
11835            return true;
11836        }
11837
11838        @Override
11839        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11840            return new PackageParser.ProviderIntentInfo[size];
11841        }
11842
11843        @Override
11844        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11845            if (!sUserManager.exists(userId))
11846                return true;
11847            PackageParser.Package p = filter.provider.owner;
11848            if (p != null) {
11849                PackageSetting ps = (PackageSetting) p.mExtras;
11850                if (ps != null) {
11851                    // System apps are never considered stopped for purposes of
11852                    // filtering, because there may be no way for the user to
11853                    // actually re-launch them.
11854                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11855                            && ps.getStopped(userId);
11856                }
11857            }
11858            return false;
11859        }
11860
11861        @Override
11862        protected boolean isPackageForFilter(String packageName,
11863                PackageParser.ProviderIntentInfo info) {
11864            return packageName.equals(info.provider.owner.packageName);
11865        }
11866
11867        @Override
11868        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11869                int match, int userId) {
11870            if (!sUserManager.exists(userId))
11871                return null;
11872            final PackageParser.ProviderIntentInfo info = filter;
11873            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11874                return null;
11875            }
11876            final PackageParser.Provider provider = info.provider;
11877            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11878            if (ps == null) {
11879                return null;
11880            }
11881            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11882                    ps.readUserState(userId), userId);
11883            if (pi == null) {
11884                return null;
11885            }
11886            final ResolveInfo res = new ResolveInfo();
11887            res.providerInfo = pi;
11888            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11889                res.filter = filter;
11890            }
11891            res.priority = info.getPriority();
11892            res.preferredOrder = provider.owner.mPreferredOrder;
11893            res.match = match;
11894            res.isDefault = info.hasDefault;
11895            res.labelRes = info.labelRes;
11896            res.nonLocalizedLabel = info.nonLocalizedLabel;
11897            res.icon = info.icon;
11898            res.system = res.providerInfo.applicationInfo.isSystemApp();
11899            return res;
11900        }
11901
11902        @Override
11903        protected void sortResults(List<ResolveInfo> results) {
11904            Collections.sort(results, mResolvePrioritySorter);
11905        }
11906
11907        @Override
11908        protected void dumpFilter(PrintWriter out, String prefix,
11909                PackageParser.ProviderIntentInfo filter) {
11910            out.print(prefix);
11911            out.print(
11912                    Integer.toHexString(System.identityHashCode(filter.provider)));
11913            out.print(' ');
11914            filter.provider.printComponentShortName(out);
11915            out.print(" filter ");
11916            out.println(Integer.toHexString(System.identityHashCode(filter)));
11917        }
11918
11919        @Override
11920        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11921            return filter.provider;
11922        }
11923
11924        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11925            PackageParser.Provider provider = (PackageParser.Provider)label;
11926            out.print(prefix); out.print(
11927                    Integer.toHexString(System.identityHashCode(provider)));
11928                    out.print(' ');
11929                    provider.printComponentShortName(out);
11930            if (count > 1) {
11931                out.print(" ("); out.print(count); out.print(" filters)");
11932            }
11933            out.println();
11934        }
11935
11936        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11937                = new ArrayMap<ComponentName, PackageParser.Provider>();
11938        private int mFlags;
11939    }
11940
11941    static final class EphemeralIntentResolver
11942            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11943        /**
11944         * The result that has the highest defined order. Ordering applies on a
11945         * per-package basis. Mapping is from package name to Pair of order and
11946         * EphemeralResolveInfo.
11947         * <p>
11948         * NOTE: This is implemented as a field variable for convenience and efficiency.
11949         * By having a field variable, we're able to track filter ordering as soon as
11950         * a non-zero order is defined. Otherwise, multiple loops across the result set
11951         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11952         * this needs to be contained entirely within {@link #filterResults()}.
11953         */
11954        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11955
11956        @Override
11957        protected EphemeralResponse[] newArray(int size) {
11958            return new EphemeralResponse[size];
11959        }
11960
11961        @Override
11962        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11963            return true;
11964        }
11965
11966        @Override
11967        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11968                int userId) {
11969            if (!sUserManager.exists(userId)) {
11970                return null;
11971            }
11972            final String packageName = responseObj.resolveInfo.getPackageName();
11973            final Integer order = responseObj.getOrder();
11974            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11975                    mOrderResult.get(packageName);
11976            // ordering is enabled and this item's order isn't high enough
11977            if (lastOrderResult != null && lastOrderResult.first >= order) {
11978                return null;
11979            }
11980            final EphemeralResolveInfo res = responseObj.resolveInfo;
11981            if (order > 0) {
11982                // non-zero order, enable ordering
11983                mOrderResult.put(packageName, new Pair<>(order, res));
11984            }
11985            return responseObj;
11986        }
11987
11988        @Override
11989        protected void filterResults(List<EphemeralResponse> results) {
11990            // only do work if ordering is enabled [most of the time it won't be]
11991            if (mOrderResult.size() == 0) {
11992                return;
11993            }
11994            int resultSize = results.size();
11995            for (int i = 0; i < resultSize; i++) {
11996                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11997                final String packageName = info.getPackageName();
11998                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11999                if (savedInfo == null) {
12000                    // package doesn't having ordering
12001                    continue;
12002                }
12003                if (savedInfo.second == info) {
12004                    // circled back to the highest ordered item; remove from order list
12005                    mOrderResult.remove(savedInfo);
12006                    if (mOrderResult.size() == 0) {
12007                        // no more ordered items
12008                        break;
12009                    }
12010                    continue;
12011                }
12012                // item has a worse order, remove it from the result list
12013                results.remove(i);
12014                resultSize--;
12015                i--;
12016            }
12017        }
12018    }
12019
12020    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12021            new Comparator<ResolveInfo>() {
12022        public int compare(ResolveInfo r1, ResolveInfo r2) {
12023            int v1 = r1.priority;
12024            int v2 = r2.priority;
12025            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12026            if (v1 != v2) {
12027                return (v1 > v2) ? -1 : 1;
12028            }
12029            v1 = r1.preferredOrder;
12030            v2 = r2.preferredOrder;
12031            if (v1 != v2) {
12032                return (v1 > v2) ? -1 : 1;
12033            }
12034            if (r1.isDefault != r2.isDefault) {
12035                return r1.isDefault ? -1 : 1;
12036            }
12037            v1 = r1.match;
12038            v2 = r2.match;
12039            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12040            if (v1 != v2) {
12041                return (v1 > v2) ? -1 : 1;
12042            }
12043            if (r1.system != r2.system) {
12044                return r1.system ? -1 : 1;
12045            }
12046            if (r1.activityInfo != null) {
12047                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12048            }
12049            if (r1.serviceInfo != null) {
12050                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12051            }
12052            if (r1.providerInfo != null) {
12053                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12054            }
12055            return 0;
12056        }
12057    };
12058
12059    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12060            new Comparator<ProviderInfo>() {
12061        public int compare(ProviderInfo p1, ProviderInfo p2) {
12062            final int v1 = p1.initOrder;
12063            final int v2 = p2.initOrder;
12064            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12065        }
12066    };
12067
12068    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12069            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12070            final int[] userIds) {
12071        mHandler.post(new Runnable() {
12072            @Override
12073            public void run() {
12074                try {
12075                    final IActivityManager am = ActivityManager.getService();
12076                    if (am == null) return;
12077                    final int[] resolvedUserIds;
12078                    if (userIds == null) {
12079                        resolvedUserIds = am.getRunningUserIds();
12080                    } else {
12081                        resolvedUserIds = userIds;
12082                    }
12083                    for (int id : resolvedUserIds) {
12084                        final Intent intent = new Intent(action,
12085                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12086                        if (extras != null) {
12087                            intent.putExtras(extras);
12088                        }
12089                        if (targetPkg != null) {
12090                            intent.setPackage(targetPkg);
12091                        }
12092                        // Modify the UID when posting to other users
12093                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12094                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12095                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12096                            intent.putExtra(Intent.EXTRA_UID, uid);
12097                        }
12098                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12099                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12100                        if (DEBUG_BROADCASTS) {
12101                            RuntimeException here = new RuntimeException("here");
12102                            here.fillInStackTrace();
12103                            Slog.d(TAG, "Sending to user " + id + ": "
12104                                    + intent.toShortString(false, true, false, false)
12105                                    + " " + intent.getExtras(), here);
12106                        }
12107                        am.broadcastIntent(null, intent, null, finishedReceiver,
12108                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12109                                null, finishedReceiver != null, false, id);
12110                    }
12111                } catch (RemoteException ex) {
12112                }
12113            }
12114        });
12115    }
12116
12117    /**
12118     * Check if the external storage media is available. This is true if there
12119     * is a mounted external storage medium or if the external storage is
12120     * emulated.
12121     */
12122    private boolean isExternalMediaAvailable() {
12123        return mMediaMounted || Environment.isExternalStorageEmulated();
12124    }
12125
12126    @Override
12127    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12128        // writer
12129        synchronized (mPackages) {
12130            if (!isExternalMediaAvailable()) {
12131                // If the external storage is no longer mounted at this point,
12132                // the caller may not have been able to delete all of this
12133                // packages files and can not delete any more.  Bail.
12134                return null;
12135            }
12136            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12137            if (lastPackage != null) {
12138                pkgs.remove(lastPackage);
12139            }
12140            if (pkgs.size() > 0) {
12141                return pkgs.get(0);
12142            }
12143        }
12144        return null;
12145    }
12146
12147    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12148        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12149                userId, andCode ? 1 : 0, packageName);
12150        if (mSystemReady) {
12151            msg.sendToTarget();
12152        } else {
12153            if (mPostSystemReadyMessages == null) {
12154                mPostSystemReadyMessages = new ArrayList<>();
12155            }
12156            mPostSystemReadyMessages.add(msg);
12157        }
12158    }
12159
12160    void startCleaningPackages() {
12161        // reader
12162        if (!isExternalMediaAvailable()) {
12163            return;
12164        }
12165        synchronized (mPackages) {
12166            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12167                return;
12168            }
12169        }
12170        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12171        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12172        IActivityManager am = ActivityManager.getService();
12173        if (am != null) {
12174            try {
12175                am.startService(null, intent, null, mContext.getOpPackageName(),
12176                        UserHandle.USER_SYSTEM);
12177            } catch (RemoteException e) {
12178            }
12179        }
12180    }
12181
12182    @Override
12183    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12184            int installFlags, String installerPackageName, int userId) {
12185        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12186
12187        final int callingUid = Binder.getCallingUid();
12188        enforceCrossUserPermission(callingUid, userId,
12189                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12190
12191        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12192            try {
12193                if (observer != null) {
12194                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12195                }
12196            } catch (RemoteException re) {
12197            }
12198            return;
12199        }
12200
12201        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12202            installFlags |= PackageManager.INSTALL_FROM_ADB;
12203
12204        } else {
12205            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12206            // about installerPackageName.
12207
12208            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12209            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12210        }
12211
12212        UserHandle user;
12213        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12214            user = UserHandle.ALL;
12215        } else {
12216            user = new UserHandle(userId);
12217        }
12218
12219        // Only system components can circumvent runtime permissions when installing.
12220        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12221                && mContext.checkCallingOrSelfPermission(Manifest.permission
12222                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12223            throw new SecurityException("You need the "
12224                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12225                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12226        }
12227
12228        final File originFile = new File(originPath);
12229        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12230
12231        final Message msg = mHandler.obtainMessage(INIT_COPY);
12232        final VerificationInfo verificationInfo = new VerificationInfo(
12233                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12234        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12235                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12236                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12237                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12238        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12239        msg.obj = params;
12240
12241        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12242                System.identityHashCode(msg.obj));
12243        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12244                System.identityHashCode(msg.obj));
12245
12246        mHandler.sendMessage(msg);
12247    }
12248
12249
12250    /**
12251     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12252     * it is acting on behalf on an enterprise or the user).
12253     *
12254     * Note that the ordering of the conditionals in this method is important. The checks we perform
12255     * are as follows, in this order:
12256     *
12257     * 1) If the install is being performed by a system app, we can trust the app to have set the
12258     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12259     *    what it is.
12260     * 2) If the install is being performed by a device or profile owner app, the install reason
12261     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12262     *    set the install reason correctly. If the app targets an older SDK version where install
12263     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12264     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12265     * 3) In all other cases, the install is being performed by a regular app that is neither part
12266     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12267     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12268     *    set to enterprise policy and if so, change it to unknown instead.
12269     */
12270    private int fixUpInstallReason(String installerPackageName, int installerUid,
12271            int installReason) {
12272        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12273                == PERMISSION_GRANTED) {
12274            // If the install is being performed by a system app, we trust that app to have set the
12275            // install reason correctly.
12276            return installReason;
12277        }
12278
12279        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12280            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12281        if (dpm != null) {
12282            ComponentName owner = null;
12283            try {
12284                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12285                if (owner == null) {
12286                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12287                }
12288            } catch (RemoteException e) {
12289            }
12290            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12291                // If the install is being performed by a device or profile owner, the install
12292                // reason should be enterprise policy.
12293                return PackageManager.INSTALL_REASON_POLICY;
12294            }
12295        }
12296
12297        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12298            // If the install is being performed by a regular app (i.e. neither system app nor
12299            // device or profile owner), we have no reason to believe that the app is acting on
12300            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12301            // change it to unknown instead.
12302            return PackageManager.INSTALL_REASON_UNKNOWN;
12303        }
12304
12305        // If the install is being performed by a regular app and the install reason was set to any
12306        // value but enterprise policy, leave the install reason unchanged.
12307        return installReason;
12308    }
12309
12310    void installStage(String packageName, File stagedDir, String stagedCid,
12311            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12312            String installerPackageName, int installerUid, UserHandle user,
12313            Certificate[][] certificates) {
12314        if (DEBUG_EPHEMERAL) {
12315            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12316                Slog.d(TAG, "Ephemeral install of " + packageName);
12317            }
12318        }
12319        final VerificationInfo verificationInfo = new VerificationInfo(
12320                sessionParams.originatingUri, sessionParams.referrerUri,
12321                sessionParams.originatingUid, installerUid);
12322
12323        final OriginInfo origin;
12324        if (stagedDir != null) {
12325            origin = OriginInfo.fromStagedFile(stagedDir);
12326        } else {
12327            origin = OriginInfo.fromStagedContainer(stagedCid);
12328        }
12329
12330        final Message msg = mHandler.obtainMessage(INIT_COPY);
12331        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
12332                sessionParams.installReason);
12333        final InstallParams params = new InstallParams(origin, null, observer,
12334                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12335                verificationInfo, user, sessionParams.abiOverride,
12336                sessionParams.grantedRuntimePermissions, certificates, installReason);
12337        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12338        msg.obj = params;
12339
12340        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12341                System.identityHashCode(msg.obj));
12342        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12343                System.identityHashCode(msg.obj));
12344
12345        mHandler.sendMessage(msg);
12346    }
12347
12348    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12349            int userId) {
12350        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12351        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12352    }
12353
12354    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12355            int appId, int... userIds) {
12356        if (ArrayUtils.isEmpty(userIds)) {
12357            return;
12358        }
12359        Bundle extras = new Bundle(1);
12360        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12361        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12362
12363        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12364                packageName, extras, 0, null, null, userIds);
12365        if (isSystem) {
12366            mHandler.post(() -> {
12367                        for (int userId : userIds) {
12368                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12369                        }
12370                    }
12371            );
12372        }
12373    }
12374
12375    /**
12376     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12377     * automatically without needing an explicit launch.
12378     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12379     */
12380    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12381        // If user is not running, the app didn't miss any broadcast
12382        if (!mUserManagerInternal.isUserRunning(userId)) {
12383            return;
12384        }
12385        final IActivityManager am = ActivityManager.getService();
12386        try {
12387            // Deliver LOCKED_BOOT_COMPLETED first
12388            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12389                    .setPackage(packageName);
12390            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12391            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12392                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12393
12394            // Deliver BOOT_COMPLETED only if user is unlocked
12395            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12396                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12397                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12398                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12399            }
12400        } catch (RemoteException e) {
12401            throw e.rethrowFromSystemServer();
12402        }
12403    }
12404
12405    @Override
12406    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12407            int userId) {
12408        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12409        PackageSetting pkgSetting;
12410        final int uid = Binder.getCallingUid();
12411        enforceCrossUserPermission(uid, userId,
12412                true /* requireFullPermission */, true /* checkShell */,
12413                "setApplicationHiddenSetting for user " + userId);
12414
12415        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12416            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12417            return false;
12418        }
12419
12420        long callingId = Binder.clearCallingIdentity();
12421        try {
12422            boolean sendAdded = false;
12423            boolean sendRemoved = false;
12424            // writer
12425            synchronized (mPackages) {
12426                pkgSetting = mSettings.mPackages.get(packageName);
12427                if (pkgSetting == null) {
12428                    return false;
12429                }
12430                // Do not allow "android" is being disabled
12431                if ("android".equals(packageName)) {
12432                    Slog.w(TAG, "Cannot hide package: android");
12433                    return false;
12434                }
12435                // Only allow protected packages to hide themselves.
12436                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12437                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12438                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12439                    return false;
12440                }
12441
12442                if (pkgSetting.getHidden(userId) != hidden) {
12443                    pkgSetting.setHidden(hidden, userId);
12444                    mSettings.writePackageRestrictionsLPr(userId);
12445                    if (hidden) {
12446                        sendRemoved = true;
12447                    } else {
12448                        sendAdded = true;
12449                    }
12450                }
12451            }
12452            if (sendAdded) {
12453                sendPackageAddedForUser(packageName, pkgSetting, userId);
12454                return true;
12455            }
12456            if (sendRemoved) {
12457                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12458                        "hiding pkg");
12459                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12460                return true;
12461            }
12462        } finally {
12463            Binder.restoreCallingIdentity(callingId);
12464        }
12465        return false;
12466    }
12467
12468    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12469            int userId) {
12470        final PackageRemovedInfo info = new PackageRemovedInfo();
12471        info.removedPackage = packageName;
12472        info.removedUsers = new int[] {userId};
12473        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12474        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12475    }
12476
12477    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12478        if (pkgList.length > 0) {
12479            Bundle extras = new Bundle(1);
12480            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12481
12482            sendPackageBroadcast(
12483                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12484                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12485                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12486                    new int[] {userId});
12487        }
12488    }
12489
12490    /**
12491     * Returns true if application is not found or there was an error. Otherwise it returns
12492     * the hidden state of the package for the given user.
12493     */
12494    @Override
12495    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12496        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12497        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12498                true /* requireFullPermission */, false /* checkShell */,
12499                "getApplicationHidden for user " + userId);
12500        PackageSetting pkgSetting;
12501        long callingId = Binder.clearCallingIdentity();
12502        try {
12503            // writer
12504            synchronized (mPackages) {
12505                pkgSetting = mSettings.mPackages.get(packageName);
12506                if (pkgSetting == null) {
12507                    return true;
12508                }
12509                return pkgSetting.getHidden(userId);
12510            }
12511        } finally {
12512            Binder.restoreCallingIdentity(callingId);
12513        }
12514    }
12515
12516    /**
12517     * @hide
12518     */
12519    @Override
12520    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
12521        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12522                null);
12523        PackageSetting pkgSetting;
12524        final int uid = Binder.getCallingUid();
12525        enforceCrossUserPermission(uid, userId,
12526                true /* requireFullPermission */, true /* checkShell */,
12527                "installExistingPackage for user " + userId);
12528        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12529            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12530        }
12531
12532        long callingId = Binder.clearCallingIdentity();
12533        try {
12534            boolean installed = false;
12535
12536            // writer
12537            synchronized (mPackages) {
12538                pkgSetting = mSettings.mPackages.get(packageName);
12539                if (pkgSetting == null) {
12540                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12541                }
12542                if (!pkgSetting.getInstalled(userId)) {
12543                    pkgSetting.setInstalled(true, userId);
12544                    pkgSetting.setHidden(false, userId);
12545                    pkgSetting.setInstallReason(installReason, userId);
12546                    mSettings.writePackageRestrictionsLPr(userId);
12547                    installed = true;
12548                }
12549            }
12550
12551            if (installed) {
12552                if (pkgSetting.pkg != null) {
12553                    synchronized (mInstallLock) {
12554                        // We don't need to freeze for a brand new install
12555                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12556                    }
12557                }
12558                sendPackageAddedForUser(packageName, pkgSetting, userId);
12559            }
12560        } finally {
12561            Binder.restoreCallingIdentity(callingId);
12562        }
12563
12564        return PackageManager.INSTALL_SUCCEEDED;
12565    }
12566
12567    boolean isUserRestricted(int userId, String restrictionKey) {
12568        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12569        if (restrictions.getBoolean(restrictionKey, false)) {
12570            Log.w(TAG, "User is restricted: " + restrictionKey);
12571            return true;
12572        }
12573        return false;
12574    }
12575
12576    @Override
12577    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12578            int userId) {
12579        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12581                true /* requireFullPermission */, true /* checkShell */,
12582                "setPackagesSuspended for user " + userId);
12583
12584        if (ArrayUtils.isEmpty(packageNames)) {
12585            return packageNames;
12586        }
12587
12588        // List of package names for whom the suspended state has changed.
12589        List<String> changedPackages = new ArrayList<>(packageNames.length);
12590        // List of package names for whom the suspended state is not set as requested in this
12591        // method.
12592        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12593        long callingId = Binder.clearCallingIdentity();
12594        try {
12595            for (int i = 0; i < packageNames.length; i++) {
12596                String packageName = packageNames[i];
12597                boolean changed = false;
12598                final int appId;
12599                synchronized (mPackages) {
12600                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12601                    if (pkgSetting == null) {
12602                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12603                                + "\". Skipping suspending/un-suspending.");
12604                        unactionedPackages.add(packageName);
12605                        continue;
12606                    }
12607                    appId = pkgSetting.appId;
12608                    if (pkgSetting.getSuspended(userId) != suspended) {
12609                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12610                            unactionedPackages.add(packageName);
12611                            continue;
12612                        }
12613                        pkgSetting.setSuspended(suspended, userId);
12614                        mSettings.writePackageRestrictionsLPr(userId);
12615                        changed = true;
12616                        changedPackages.add(packageName);
12617                    }
12618                }
12619
12620                if (changed && suspended) {
12621                    killApplication(packageName, UserHandle.getUid(userId, appId),
12622                            "suspending package");
12623                }
12624            }
12625        } finally {
12626            Binder.restoreCallingIdentity(callingId);
12627        }
12628
12629        if (!changedPackages.isEmpty()) {
12630            sendPackagesSuspendedForUser(changedPackages.toArray(
12631                    new String[changedPackages.size()]), userId, suspended);
12632        }
12633
12634        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12635    }
12636
12637    @Override
12638    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12639        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12640                true /* requireFullPermission */, false /* checkShell */,
12641                "isPackageSuspendedForUser for user " + userId);
12642        synchronized (mPackages) {
12643            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12644            if (pkgSetting == null) {
12645                throw new IllegalArgumentException("Unknown target package: " + packageName);
12646            }
12647            return pkgSetting.getSuspended(userId);
12648        }
12649    }
12650
12651    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12652        if (isPackageDeviceAdmin(packageName, userId)) {
12653            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12654                    + "\": has an active device admin");
12655            return false;
12656        }
12657
12658        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12659        if (packageName.equals(activeLauncherPackageName)) {
12660            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12661                    + "\": contains the active launcher");
12662            return false;
12663        }
12664
12665        if (packageName.equals(mRequiredInstallerPackage)) {
12666            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12667                    + "\": required for package installation");
12668            return false;
12669        }
12670
12671        if (packageName.equals(mRequiredUninstallerPackage)) {
12672            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12673                    + "\": required for package uninstallation");
12674            return false;
12675        }
12676
12677        if (packageName.equals(mRequiredVerifierPackage)) {
12678            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12679                    + "\": required for package verification");
12680            return false;
12681        }
12682
12683        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12684            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12685                    + "\": is the default dialer");
12686            return false;
12687        }
12688
12689        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12690            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12691                    + "\": protected package");
12692            return false;
12693        }
12694
12695        return true;
12696    }
12697
12698    private String getActiveLauncherPackageName(int userId) {
12699        Intent intent = new Intent(Intent.ACTION_MAIN);
12700        intent.addCategory(Intent.CATEGORY_HOME);
12701        ResolveInfo resolveInfo = resolveIntent(
12702                intent,
12703                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12704                PackageManager.MATCH_DEFAULT_ONLY,
12705                userId);
12706
12707        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12708    }
12709
12710    private String getDefaultDialerPackageName(int userId) {
12711        synchronized (mPackages) {
12712            return mSettings.getDefaultDialerPackageNameLPw(userId);
12713        }
12714    }
12715
12716    @Override
12717    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12718        mContext.enforceCallingOrSelfPermission(
12719                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12720                "Only package verification agents can verify applications");
12721
12722        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12723        final PackageVerificationResponse response = new PackageVerificationResponse(
12724                verificationCode, Binder.getCallingUid());
12725        msg.arg1 = id;
12726        msg.obj = response;
12727        mHandler.sendMessage(msg);
12728    }
12729
12730    @Override
12731    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12732            long millisecondsToDelay) {
12733        mContext.enforceCallingOrSelfPermission(
12734                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12735                "Only package verification agents can extend verification timeouts");
12736
12737        final PackageVerificationState state = mPendingVerification.get(id);
12738        final PackageVerificationResponse response = new PackageVerificationResponse(
12739                verificationCodeAtTimeout, Binder.getCallingUid());
12740
12741        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12742            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12743        }
12744        if (millisecondsToDelay < 0) {
12745            millisecondsToDelay = 0;
12746        }
12747        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12748                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12749            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12750        }
12751
12752        if ((state != null) && !state.timeoutExtended()) {
12753            state.extendTimeout();
12754
12755            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12756            msg.arg1 = id;
12757            msg.obj = response;
12758            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12759        }
12760    }
12761
12762    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12763            int verificationCode, UserHandle user) {
12764        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12765        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12766        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12767        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12768        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12769
12770        mContext.sendBroadcastAsUser(intent, user,
12771                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12772    }
12773
12774    private ComponentName matchComponentForVerifier(String packageName,
12775            List<ResolveInfo> receivers) {
12776        ActivityInfo targetReceiver = null;
12777
12778        final int NR = receivers.size();
12779        for (int i = 0; i < NR; i++) {
12780            final ResolveInfo info = receivers.get(i);
12781            if (info.activityInfo == null) {
12782                continue;
12783            }
12784
12785            if (packageName.equals(info.activityInfo.packageName)) {
12786                targetReceiver = info.activityInfo;
12787                break;
12788            }
12789        }
12790
12791        if (targetReceiver == null) {
12792            return null;
12793        }
12794
12795        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12796    }
12797
12798    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12799            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12800        if (pkgInfo.verifiers.length == 0) {
12801            return null;
12802        }
12803
12804        final int N = pkgInfo.verifiers.length;
12805        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12806        for (int i = 0; i < N; i++) {
12807            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12808
12809            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12810                    receivers);
12811            if (comp == null) {
12812                continue;
12813            }
12814
12815            final int verifierUid = getUidForVerifier(verifierInfo);
12816            if (verifierUid == -1) {
12817                continue;
12818            }
12819
12820            if (DEBUG_VERIFY) {
12821                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12822                        + " with the correct signature");
12823            }
12824            sufficientVerifiers.add(comp);
12825            verificationState.addSufficientVerifier(verifierUid);
12826        }
12827
12828        return sufficientVerifiers;
12829    }
12830
12831    private int getUidForVerifier(VerifierInfo verifierInfo) {
12832        synchronized (mPackages) {
12833            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12834            if (pkg == null) {
12835                return -1;
12836            } else if (pkg.mSignatures.length != 1) {
12837                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12838                        + " has more than one signature; ignoring");
12839                return -1;
12840            }
12841
12842            /*
12843             * If the public key of the package's signature does not match
12844             * our expected public key, then this is a different package and
12845             * we should skip.
12846             */
12847
12848            final byte[] expectedPublicKey;
12849            try {
12850                final Signature verifierSig = pkg.mSignatures[0];
12851                final PublicKey publicKey = verifierSig.getPublicKey();
12852                expectedPublicKey = publicKey.getEncoded();
12853            } catch (CertificateException e) {
12854                return -1;
12855            }
12856
12857            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12858
12859            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12860                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12861                        + " does not have the expected public key; ignoring");
12862                return -1;
12863            }
12864
12865            return pkg.applicationInfo.uid;
12866        }
12867    }
12868
12869    @Override
12870    public void finishPackageInstall(int token, boolean didLaunch) {
12871        enforceSystemOrRoot("Only the system is allowed to finish installs");
12872
12873        if (DEBUG_INSTALL) {
12874            Slog.v(TAG, "BM finishing package install for " + token);
12875        }
12876        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12877
12878        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12879        mHandler.sendMessage(msg);
12880    }
12881
12882    /**
12883     * Get the verification agent timeout.
12884     *
12885     * @return verification timeout in milliseconds
12886     */
12887    private long getVerificationTimeout() {
12888        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12889                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12890                DEFAULT_VERIFICATION_TIMEOUT);
12891    }
12892
12893    /**
12894     * Get the default verification agent response code.
12895     *
12896     * @return default verification response code
12897     */
12898    private int getDefaultVerificationResponse() {
12899        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12900                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12901                DEFAULT_VERIFICATION_RESPONSE);
12902    }
12903
12904    /**
12905     * Check whether or not package verification has been enabled.
12906     *
12907     * @return true if verification should be performed
12908     */
12909    private boolean isVerificationEnabled(int userId, int installFlags) {
12910        if (!DEFAULT_VERIFY_ENABLE) {
12911            return false;
12912        }
12913        // Ephemeral apps don't get the full verification treatment
12914        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12915            if (DEBUG_EPHEMERAL) {
12916                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12917            }
12918            return false;
12919        }
12920
12921        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12922
12923        // Check if installing from ADB
12924        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12925            // Do not run verification in a test harness environment
12926            if (ActivityManager.isRunningInTestHarness()) {
12927                return false;
12928            }
12929            if (ensureVerifyAppsEnabled) {
12930                return true;
12931            }
12932            // Check if the developer does not want package verification for ADB installs
12933            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12934                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12935                return false;
12936            }
12937        }
12938
12939        if (ensureVerifyAppsEnabled) {
12940            return true;
12941        }
12942
12943        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12944                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12945    }
12946
12947    @Override
12948    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12949            throws RemoteException {
12950        mContext.enforceCallingOrSelfPermission(
12951                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12952                "Only intentfilter verification agents can verify applications");
12953
12954        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12955        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12956                Binder.getCallingUid(), verificationCode, failedDomains);
12957        msg.arg1 = id;
12958        msg.obj = response;
12959        mHandler.sendMessage(msg);
12960    }
12961
12962    @Override
12963    public int getIntentVerificationStatus(String packageName, int userId) {
12964        synchronized (mPackages) {
12965            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12966        }
12967    }
12968
12969    @Override
12970    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12971        mContext.enforceCallingOrSelfPermission(
12972                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12973
12974        boolean result = false;
12975        synchronized (mPackages) {
12976            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12977        }
12978        if (result) {
12979            scheduleWritePackageRestrictionsLocked(userId);
12980        }
12981        return result;
12982    }
12983
12984    @Override
12985    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12986            String packageName) {
12987        synchronized (mPackages) {
12988            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12989        }
12990    }
12991
12992    @Override
12993    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12994        if (TextUtils.isEmpty(packageName)) {
12995            return ParceledListSlice.emptyList();
12996        }
12997        synchronized (mPackages) {
12998            PackageParser.Package pkg = mPackages.get(packageName);
12999            if (pkg == null || pkg.activities == null) {
13000                return ParceledListSlice.emptyList();
13001            }
13002            final int count = pkg.activities.size();
13003            ArrayList<IntentFilter> result = new ArrayList<>();
13004            for (int n=0; n<count; n++) {
13005                PackageParser.Activity activity = pkg.activities.get(n);
13006                if (activity.intents != null && activity.intents.size() > 0) {
13007                    result.addAll(activity.intents);
13008                }
13009            }
13010            return new ParceledListSlice<>(result);
13011        }
13012    }
13013
13014    @Override
13015    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13016        mContext.enforceCallingOrSelfPermission(
13017                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13018
13019        synchronized (mPackages) {
13020            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13021            if (packageName != null) {
13022                result |= updateIntentVerificationStatus(packageName,
13023                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13024                        userId);
13025                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13026                        packageName, userId);
13027            }
13028            return result;
13029        }
13030    }
13031
13032    @Override
13033    public String getDefaultBrowserPackageName(int userId) {
13034        synchronized (mPackages) {
13035            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13036        }
13037    }
13038
13039    /**
13040     * Get the "allow unknown sources" setting.
13041     *
13042     * @return the current "allow unknown sources" setting
13043     */
13044    private int getUnknownSourcesSettings() {
13045        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13046                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13047                -1);
13048    }
13049
13050    @Override
13051    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13052        final int uid = Binder.getCallingUid();
13053        // writer
13054        synchronized (mPackages) {
13055            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13056            if (targetPackageSetting == null) {
13057                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13058            }
13059
13060            PackageSetting installerPackageSetting;
13061            if (installerPackageName != null) {
13062                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13063                if (installerPackageSetting == null) {
13064                    throw new IllegalArgumentException("Unknown installer package: "
13065                            + installerPackageName);
13066                }
13067            } else {
13068                installerPackageSetting = null;
13069            }
13070
13071            Signature[] callerSignature;
13072            Object obj = mSettings.getUserIdLPr(uid);
13073            if (obj != null) {
13074                if (obj instanceof SharedUserSetting) {
13075                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13076                } else if (obj instanceof PackageSetting) {
13077                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13078                } else {
13079                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13080                }
13081            } else {
13082                throw new SecurityException("Unknown calling UID: " + uid);
13083            }
13084
13085            // Verify: can't set installerPackageName to a package that is
13086            // not signed with the same cert as the caller.
13087            if (installerPackageSetting != null) {
13088                if (compareSignatures(callerSignature,
13089                        installerPackageSetting.signatures.mSignatures)
13090                        != PackageManager.SIGNATURE_MATCH) {
13091                    throw new SecurityException(
13092                            "Caller does not have same cert as new installer package "
13093                            + installerPackageName);
13094                }
13095            }
13096
13097            // Verify: if target already has an installer package, it must
13098            // be signed with the same cert as the caller.
13099            if (targetPackageSetting.installerPackageName != null) {
13100                PackageSetting setting = mSettings.mPackages.get(
13101                        targetPackageSetting.installerPackageName);
13102                // If the currently set package isn't valid, then it's always
13103                // okay to change it.
13104                if (setting != null) {
13105                    if (compareSignatures(callerSignature,
13106                            setting.signatures.mSignatures)
13107                            != PackageManager.SIGNATURE_MATCH) {
13108                        throw new SecurityException(
13109                                "Caller does not have same cert as old installer package "
13110                                + targetPackageSetting.installerPackageName);
13111                    }
13112                }
13113            }
13114
13115            // Okay!
13116            targetPackageSetting.installerPackageName = installerPackageName;
13117            if (installerPackageName != null) {
13118                mSettings.mInstallerPackages.add(installerPackageName);
13119            }
13120            scheduleWriteSettingsLocked();
13121        }
13122    }
13123
13124    @Override
13125    public void setApplicationCategoryHint(String packageName, int categoryHint,
13126            String callerPackageName) {
13127        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13128                callerPackageName);
13129        synchronized (mPackages) {
13130            PackageSetting ps = mSettings.mPackages.get(packageName);
13131            if (ps == null) {
13132                throw new IllegalArgumentException("Unknown target package " + packageName);
13133            }
13134
13135            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13136                throw new IllegalArgumentException("Calling package " + callerPackageName
13137                        + " is not installer for " + packageName);
13138            }
13139
13140            if (ps.categoryHint != categoryHint) {
13141                ps.categoryHint = categoryHint;
13142                scheduleWriteSettingsLocked();
13143            }
13144        }
13145    }
13146
13147    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13148        // Queue up an async operation since the package installation may take a little while.
13149        mHandler.post(new Runnable() {
13150            public void run() {
13151                mHandler.removeCallbacks(this);
13152                 // Result object to be returned
13153                PackageInstalledInfo res = new PackageInstalledInfo();
13154                res.setReturnCode(currentStatus);
13155                res.uid = -1;
13156                res.pkg = null;
13157                res.removedInfo = null;
13158                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13159                    args.doPreInstall(res.returnCode);
13160                    synchronized (mInstallLock) {
13161                        installPackageTracedLI(args, res);
13162                    }
13163                    args.doPostInstall(res.returnCode, res.uid);
13164                }
13165
13166                // A restore should be performed at this point if (a) the install
13167                // succeeded, (b) the operation is not an update, and (c) the new
13168                // package has not opted out of backup participation.
13169                final boolean update = res.removedInfo != null
13170                        && res.removedInfo.removedPackage != null;
13171                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13172                boolean doRestore = !update
13173                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13174
13175                // Set up the post-install work request bookkeeping.  This will be used
13176                // and cleaned up by the post-install event handling regardless of whether
13177                // there's a restore pass performed.  Token values are >= 1.
13178                int token;
13179                if (mNextInstallToken < 0) mNextInstallToken = 1;
13180                token = mNextInstallToken++;
13181
13182                PostInstallData data = new PostInstallData(args, res);
13183                mRunningInstalls.put(token, data);
13184                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13185
13186                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13187                    // Pass responsibility to the Backup Manager.  It will perform a
13188                    // restore if appropriate, then pass responsibility back to the
13189                    // Package Manager to run the post-install observer callbacks
13190                    // and broadcasts.
13191                    IBackupManager bm = IBackupManager.Stub.asInterface(
13192                            ServiceManager.getService(Context.BACKUP_SERVICE));
13193                    if (bm != null) {
13194                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13195                                + " to BM for possible restore");
13196                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13197                        try {
13198                            // TODO: http://b/22388012
13199                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13200                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13201                            } else {
13202                                doRestore = false;
13203                            }
13204                        } catch (RemoteException e) {
13205                            // can't happen; the backup manager is local
13206                        } catch (Exception e) {
13207                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13208                            doRestore = false;
13209                        }
13210                    } else {
13211                        Slog.e(TAG, "Backup Manager not found!");
13212                        doRestore = false;
13213                    }
13214                }
13215
13216                if (!doRestore) {
13217                    // No restore possible, or the Backup Manager was mysteriously not
13218                    // available -- just fire the post-install work request directly.
13219                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13220
13221                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13222
13223                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13224                    mHandler.sendMessage(msg);
13225                }
13226            }
13227        });
13228    }
13229
13230    /**
13231     * Callback from PackageSettings whenever an app is first transitioned out of the
13232     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13233     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13234     * here whether the app is the target of an ongoing install, and only send the
13235     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13236     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13237     * handling.
13238     */
13239    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13240        // Serialize this with the rest of the install-process message chain.  In the
13241        // restore-at-install case, this Runnable will necessarily run before the
13242        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13243        // are coherent.  In the non-restore case, the app has already completed install
13244        // and been launched through some other means, so it is not in a problematic
13245        // state for observers to see the FIRST_LAUNCH signal.
13246        mHandler.post(new Runnable() {
13247            @Override
13248            public void run() {
13249                for (int i = 0; i < mRunningInstalls.size(); i++) {
13250                    final PostInstallData data = mRunningInstalls.valueAt(i);
13251                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13252                        continue;
13253                    }
13254                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13255                        // right package; but is it for the right user?
13256                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13257                            if (userId == data.res.newUsers[uIndex]) {
13258                                if (DEBUG_BACKUP) {
13259                                    Slog.i(TAG, "Package " + pkgName
13260                                            + " being restored so deferring FIRST_LAUNCH");
13261                                }
13262                                return;
13263                            }
13264                        }
13265                    }
13266                }
13267                // didn't find it, so not being restored
13268                if (DEBUG_BACKUP) {
13269                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13270                }
13271                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13272            }
13273        });
13274    }
13275
13276    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13277        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13278                installerPkg, null, userIds);
13279    }
13280
13281    private abstract class HandlerParams {
13282        private static final int MAX_RETRIES = 4;
13283
13284        /**
13285         * Number of times startCopy() has been attempted and had a non-fatal
13286         * error.
13287         */
13288        private int mRetries = 0;
13289
13290        /** User handle for the user requesting the information or installation. */
13291        private final UserHandle mUser;
13292        String traceMethod;
13293        int traceCookie;
13294
13295        HandlerParams(UserHandle user) {
13296            mUser = user;
13297        }
13298
13299        UserHandle getUser() {
13300            return mUser;
13301        }
13302
13303        HandlerParams setTraceMethod(String traceMethod) {
13304            this.traceMethod = traceMethod;
13305            return this;
13306        }
13307
13308        HandlerParams setTraceCookie(int traceCookie) {
13309            this.traceCookie = traceCookie;
13310            return this;
13311        }
13312
13313        final boolean startCopy() {
13314            boolean res;
13315            try {
13316                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13317
13318                if (++mRetries > MAX_RETRIES) {
13319                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13320                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13321                    handleServiceError();
13322                    return false;
13323                } else {
13324                    handleStartCopy();
13325                    res = true;
13326                }
13327            } catch (RemoteException e) {
13328                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13329                mHandler.sendEmptyMessage(MCS_RECONNECT);
13330                res = false;
13331            }
13332            handleReturnCode();
13333            return res;
13334        }
13335
13336        final void serviceError() {
13337            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13338            handleServiceError();
13339            handleReturnCode();
13340        }
13341
13342        abstract void handleStartCopy() throws RemoteException;
13343        abstract void handleServiceError();
13344        abstract void handleReturnCode();
13345    }
13346
13347    class MeasureParams extends HandlerParams {
13348        private final PackageStats mStats;
13349        private boolean mSuccess;
13350
13351        private final IPackageStatsObserver mObserver;
13352
13353        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13354            super(new UserHandle(stats.userHandle));
13355            mObserver = observer;
13356            mStats = stats;
13357        }
13358
13359        @Override
13360        public String toString() {
13361            return "MeasureParams{"
13362                + Integer.toHexString(System.identityHashCode(this))
13363                + " " + mStats.packageName + "}";
13364        }
13365
13366        @Override
13367        void handleStartCopy() throws RemoteException {
13368            synchronized (mInstallLock) {
13369                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13370            }
13371
13372            if (mSuccess) {
13373                boolean mounted = false;
13374                try {
13375                    final String status = Environment.getExternalStorageState();
13376                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13377                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13378                } catch (Exception e) {
13379                }
13380
13381                if (mounted) {
13382                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13383
13384                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13385                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13386
13387                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13388                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13389
13390                    // Always subtract cache size, since it's a subdirectory
13391                    mStats.externalDataSize -= mStats.externalCacheSize;
13392
13393                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13394                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13395
13396                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13397                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13398                }
13399            }
13400        }
13401
13402        @Override
13403        void handleReturnCode() {
13404            if (mObserver != null) {
13405                try {
13406                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13407                } catch (RemoteException e) {
13408                    Slog.i(TAG, "Observer no longer exists.");
13409                }
13410            }
13411        }
13412
13413        @Override
13414        void handleServiceError() {
13415            Slog.e(TAG, "Could not measure application " + mStats.packageName
13416                            + " external storage");
13417        }
13418    }
13419
13420    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13421            throws RemoteException {
13422        long result = 0;
13423        for (File path : paths) {
13424            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13425        }
13426        return result;
13427    }
13428
13429    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13430        for (File path : paths) {
13431            try {
13432                mcs.clearDirectory(path.getAbsolutePath());
13433            } catch (RemoteException e) {
13434            }
13435        }
13436    }
13437
13438    static class OriginInfo {
13439        /**
13440         * Location where install is coming from, before it has been
13441         * copied/renamed into place. This could be a single monolithic APK
13442         * file, or a cluster directory. This location may be untrusted.
13443         */
13444        final File file;
13445        final String cid;
13446
13447        /**
13448         * Flag indicating that {@link #file} or {@link #cid} has already been
13449         * staged, meaning downstream users don't need to defensively copy the
13450         * contents.
13451         */
13452        final boolean staged;
13453
13454        /**
13455         * Flag indicating that {@link #file} or {@link #cid} is an already
13456         * installed app that is being moved.
13457         */
13458        final boolean existing;
13459
13460        final String resolvedPath;
13461        final File resolvedFile;
13462
13463        static OriginInfo fromNothing() {
13464            return new OriginInfo(null, null, false, false);
13465        }
13466
13467        static OriginInfo fromUntrustedFile(File file) {
13468            return new OriginInfo(file, null, false, false);
13469        }
13470
13471        static OriginInfo fromExistingFile(File file) {
13472            return new OriginInfo(file, null, false, true);
13473        }
13474
13475        static OriginInfo fromStagedFile(File file) {
13476            return new OriginInfo(file, null, true, false);
13477        }
13478
13479        static OriginInfo fromStagedContainer(String cid) {
13480            return new OriginInfo(null, cid, true, false);
13481        }
13482
13483        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13484            this.file = file;
13485            this.cid = cid;
13486            this.staged = staged;
13487            this.existing = existing;
13488
13489            if (cid != null) {
13490                resolvedPath = PackageHelper.getSdDir(cid);
13491                resolvedFile = new File(resolvedPath);
13492            } else if (file != null) {
13493                resolvedPath = file.getAbsolutePath();
13494                resolvedFile = file;
13495            } else {
13496                resolvedPath = null;
13497                resolvedFile = null;
13498            }
13499        }
13500    }
13501
13502    static class MoveInfo {
13503        final int moveId;
13504        final String fromUuid;
13505        final String toUuid;
13506        final String packageName;
13507        final String dataAppName;
13508        final int appId;
13509        final String seinfo;
13510        final int targetSdkVersion;
13511
13512        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13513                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13514            this.moveId = moveId;
13515            this.fromUuid = fromUuid;
13516            this.toUuid = toUuid;
13517            this.packageName = packageName;
13518            this.dataAppName = dataAppName;
13519            this.appId = appId;
13520            this.seinfo = seinfo;
13521            this.targetSdkVersion = targetSdkVersion;
13522        }
13523    }
13524
13525    static class VerificationInfo {
13526        /** A constant used to indicate that a uid value is not present. */
13527        public static final int NO_UID = -1;
13528
13529        /** URI referencing where the package was downloaded from. */
13530        final Uri originatingUri;
13531
13532        /** HTTP referrer URI associated with the originatingURI. */
13533        final Uri referrer;
13534
13535        /** UID of the application that the install request originated from. */
13536        final int originatingUid;
13537
13538        /** UID of application requesting the install */
13539        final int installerUid;
13540
13541        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13542            this.originatingUri = originatingUri;
13543            this.referrer = referrer;
13544            this.originatingUid = originatingUid;
13545            this.installerUid = installerUid;
13546        }
13547    }
13548
13549    class InstallParams extends HandlerParams {
13550        final OriginInfo origin;
13551        final MoveInfo move;
13552        final IPackageInstallObserver2 observer;
13553        int installFlags;
13554        final String installerPackageName;
13555        final String volumeUuid;
13556        private InstallArgs mArgs;
13557        private int mRet;
13558        final String packageAbiOverride;
13559        final String[] grantedRuntimePermissions;
13560        final VerificationInfo verificationInfo;
13561        final Certificate[][] certificates;
13562        final int installReason;
13563
13564        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13565                int installFlags, String installerPackageName, String volumeUuid,
13566                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13567                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
13568            super(user);
13569            this.origin = origin;
13570            this.move = move;
13571            this.observer = observer;
13572            this.installFlags = installFlags;
13573            this.installerPackageName = installerPackageName;
13574            this.volumeUuid = volumeUuid;
13575            this.verificationInfo = verificationInfo;
13576            this.packageAbiOverride = packageAbiOverride;
13577            this.grantedRuntimePermissions = grantedPermissions;
13578            this.certificates = certificates;
13579            this.installReason = installReason;
13580        }
13581
13582        @Override
13583        public String toString() {
13584            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13585                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13586        }
13587
13588        private int installLocationPolicy(PackageInfoLite pkgLite) {
13589            String packageName = pkgLite.packageName;
13590            int installLocation = pkgLite.installLocation;
13591            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13592            // reader
13593            synchronized (mPackages) {
13594                // Currently installed package which the new package is attempting to replace or
13595                // null if no such package is installed.
13596                PackageParser.Package installedPkg = mPackages.get(packageName);
13597                // Package which currently owns the data which the new package will own if installed.
13598                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13599                // will be null whereas dataOwnerPkg will contain information about the package
13600                // which was uninstalled while keeping its data.
13601                PackageParser.Package dataOwnerPkg = installedPkg;
13602                if (dataOwnerPkg  == null) {
13603                    PackageSetting ps = mSettings.mPackages.get(packageName);
13604                    if (ps != null) {
13605                        dataOwnerPkg = ps.pkg;
13606                    }
13607                }
13608
13609                if (dataOwnerPkg != null) {
13610                    // If installed, the package will get access to data left on the device by its
13611                    // predecessor. As a security measure, this is permited only if this is not a
13612                    // version downgrade or if the predecessor package is marked as debuggable and
13613                    // a downgrade is explicitly requested.
13614                    //
13615                    // On debuggable platform builds, downgrades are permitted even for
13616                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13617                    // not offer security guarantees and thus it's OK to disable some security
13618                    // mechanisms to make debugging/testing easier on those builds. However, even on
13619                    // debuggable builds downgrades of packages are permitted only if requested via
13620                    // installFlags. This is because we aim to keep the behavior of debuggable
13621                    // platform builds as close as possible to the behavior of non-debuggable
13622                    // platform builds.
13623                    final boolean downgradeRequested =
13624                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13625                    final boolean packageDebuggable =
13626                                (dataOwnerPkg.applicationInfo.flags
13627                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13628                    final boolean downgradePermitted =
13629                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13630                    if (!downgradePermitted) {
13631                        try {
13632                            checkDowngrade(dataOwnerPkg, pkgLite);
13633                        } catch (PackageManagerException e) {
13634                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13635                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13636                        }
13637                    }
13638                }
13639
13640                if (installedPkg != null) {
13641                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13642                        // Check for updated system application.
13643                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13644                            if (onSd) {
13645                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13646                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13647                            }
13648                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13649                        } else {
13650                            if (onSd) {
13651                                // Install flag overrides everything.
13652                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13653                            }
13654                            // If current upgrade specifies particular preference
13655                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13656                                // Application explicitly specified internal.
13657                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13658                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13659                                // App explictly prefers external. Let policy decide
13660                            } else {
13661                                // Prefer previous location
13662                                if (isExternal(installedPkg)) {
13663                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13664                                }
13665                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13666                            }
13667                        }
13668                    } else {
13669                        // Invalid install. Return error code
13670                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13671                    }
13672                }
13673            }
13674            // All the special cases have been taken care of.
13675            // Return result based on recommended install location.
13676            if (onSd) {
13677                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13678            }
13679            return pkgLite.recommendedInstallLocation;
13680        }
13681
13682        /*
13683         * Invoke remote method to get package information and install
13684         * location values. Override install location based on default
13685         * policy if needed and then create install arguments based
13686         * on the install location.
13687         */
13688        public void handleStartCopy() throws RemoteException {
13689            int ret = PackageManager.INSTALL_SUCCEEDED;
13690
13691            // If we're already staged, we've firmly committed to an install location
13692            if (origin.staged) {
13693                if (origin.file != null) {
13694                    installFlags |= PackageManager.INSTALL_INTERNAL;
13695                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13696                } else if (origin.cid != null) {
13697                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13698                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13699                } else {
13700                    throw new IllegalStateException("Invalid stage location");
13701                }
13702            }
13703
13704            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13705            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13706            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13707            PackageInfoLite pkgLite = null;
13708
13709            if (onInt && onSd) {
13710                // Check if both bits are set.
13711                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13712                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13713            } else if (onSd && ephemeral) {
13714                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13715                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13716            } else {
13717                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13718                        packageAbiOverride);
13719
13720                if (DEBUG_EPHEMERAL && ephemeral) {
13721                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13722                }
13723
13724                /*
13725                 * If we have too little free space, try to free cache
13726                 * before giving up.
13727                 */
13728                if (!origin.staged && pkgLite.recommendedInstallLocation
13729                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13730                    // TODO: focus freeing disk space on the target device
13731                    final StorageManager storage = StorageManager.from(mContext);
13732                    final long lowThreshold = storage.getStorageLowBytes(
13733                            Environment.getDataDirectory());
13734
13735                    final long sizeBytes = mContainerService.calculateInstalledSize(
13736                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13737
13738                    try {
13739                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13740                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13741                                installFlags, packageAbiOverride);
13742                    } catch (InstallerException e) {
13743                        Slog.w(TAG, "Failed to free cache", e);
13744                    }
13745
13746                    /*
13747                     * The cache free must have deleted the file we
13748                     * downloaded to install.
13749                     *
13750                     * TODO: fix the "freeCache" call to not delete
13751                     *       the file we care about.
13752                     */
13753                    if (pkgLite.recommendedInstallLocation
13754                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13755                        pkgLite.recommendedInstallLocation
13756                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13757                    }
13758                }
13759            }
13760
13761            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13762                int loc = pkgLite.recommendedInstallLocation;
13763                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13764                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13765                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13766                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13767                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13768                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13769                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13770                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13771                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13772                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13773                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13774                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13775                } else {
13776                    // Override with defaults if needed.
13777                    loc = installLocationPolicy(pkgLite);
13778                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13779                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13780                    } else if (!onSd && !onInt) {
13781                        // Override install location with flags
13782                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13783                            // Set the flag to install on external media.
13784                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13785                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13786                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13787                            if (DEBUG_EPHEMERAL) {
13788                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13789                            }
13790                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13791                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13792                                    |PackageManager.INSTALL_INTERNAL);
13793                        } else {
13794                            // Make sure the flag for installing on external
13795                            // media is unset
13796                            installFlags |= PackageManager.INSTALL_INTERNAL;
13797                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13798                        }
13799                    }
13800                }
13801            }
13802
13803            final InstallArgs args = createInstallArgs(this);
13804            mArgs = args;
13805
13806            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13807                // TODO: http://b/22976637
13808                // Apps installed for "all" users use the device owner to verify the app
13809                UserHandle verifierUser = getUser();
13810                if (verifierUser == UserHandle.ALL) {
13811                    verifierUser = UserHandle.SYSTEM;
13812                }
13813
13814                /*
13815                 * Determine if we have any installed package verifiers. If we
13816                 * do, then we'll defer to them to verify the packages.
13817                 */
13818                final int requiredUid = mRequiredVerifierPackage == null ? -1
13819                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13820                                verifierUser.getIdentifier());
13821                if (!origin.existing && requiredUid != -1
13822                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13823                    final Intent verification = new Intent(
13824                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13825                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13826                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13827                            PACKAGE_MIME_TYPE);
13828                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13829
13830                    // Query all live verifiers based on current user state
13831                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13832                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13833
13834                    if (DEBUG_VERIFY) {
13835                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13836                                + verification.toString() + " with " + pkgLite.verifiers.length
13837                                + " optional verifiers");
13838                    }
13839
13840                    final int verificationId = mPendingVerificationToken++;
13841
13842                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13843
13844                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13845                            installerPackageName);
13846
13847                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13848                            installFlags);
13849
13850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13851                            pkgLite.packageName);
13852
13853                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13854                            pkgLite.versionCode);
13855
13856                    if (verificationInfo != null) {
13857                        if (verificationInfo.originatingUri != null) {
13858                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13859                                    verificationInfo.originatingUri);
13860                        }
13861                        if (verificationInfo.referrer != null) {
13862                            verification.putExtra(Intent.EXTRA_REFERRER,
13863                                    verificationInfo.referrer);
13864                        }
13865                        if (verificationInfo.originatingUid >= 0) {
13866                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13867                                    verificationInfo.originatingUid);
13868                        }
13869                        if (verificationInfo.installerUid >= 0) {
13870                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13871                                    verificationInfo.installerUid);
13872                        }
13873                    }
13874
13875                    final PackageVerificationState verificationState = new PackageVerificationState(
13876                            requiredUid, args);
13877
13878                    mPendingVerification.append(verificationId, verificationState);
13879
13880                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13881                            receivers, verificationState);
13882
13883                    /*
13884                     * If any sufficient verifiers were listed in the package
13885                     * manifest, attempt to ask them.
13886                     */
13887                    if (sufficientVerifiers != null) {
13888                        final int N = sufficientVerifiers.size();
13889                        if (N == 0) {
13890                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13891                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13892                        } else {
13893                            for (int i = 0; i < N; i++) {
13894                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13895
13896                                final Intent sufficientIntent = new Intent(verification);
13897                                sufficientIntent.setComponent(verifierComponent);
13898                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13899                            }
13900                        }
13901                    }
13902
13903                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13904                            mRequiredVerifierPackage, receivers);
13905                    if (ret == PackageManager.INSTALL_SUCCEEDED
13906                            && mRequiredVerifierPackage != null) {
13907                        Trace.asyncTraceBegin(
13908                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13909                        /*
13910                         * Send the intent to the required verification agent,
13911                         * but only start the verification timeout after the
13912                         * target BroadcastReceivers have run.
13913                         */
13914                        verification.setComponent(requiredVerifierComponent);
13915                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13916                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13917                                new BroadcastReceiver() {
13918                                    @Override
13919                                    public void onReceive(Context context, Intent intent) {
13920                                        final Message msg = mHandler
13921                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13922                                        msg.arg1 = verificationId;
13923                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13924                                    }
13925                                }, null, 0, null, null);
13926
13927                        /*
13928                         * We don't want the copy to proceed until verification
13929                         * succeeds, so null out this field.
13930                         */
13931                        mArgs = null;
13932                    }
13933                } else {
13934                    /*
13935                     * No package verification is enabled, so immediately start
13936                     * the remote call to initiate copy using temporary file.
13937                     */
13938                    ret = args.copyApk(mContainerService, true);
13939                }
13940            }
13941
13942            mRet = ret;
13943        }
13944
13945        @Override
13946        void handleReturnCode() {
13947            // If mArgs is null, then MCS couldn't be reached. When it
13948            // reconnects, it will try again to install. At that point, this
13949            // will succeed.
13950            if (mArgs != null) {
13951                processPendingInstall(mArgs, mRet);
13952            }
13953        }
13954
13955        @Override
13956        void handleServiceError() {
13957            mArgs = createInstallArgs(this);
13958            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13959        }
13960
13961        public boolean isForwardLocked() {
13962            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13963        }
13964    }
13965
13966    /**
13967     * Used during creation of InstallArgs
13968     *
13969     * @param installFlags package installation flags
13970     * @return true if should be installed on external storage
13971     */
13972    private static boolean installOnExternalAsec(int installFlags) {
13973        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13974            return false;
13975        }
13976        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13977            return true;
13978        }
13979        return false;
13980    }
13981
13982    /**
13983     * Used during creation of InstallArgs
13984     *
13985     * @param installFlags package installation flags
13986     * @return true if should be installed as forward locked
13987     */
13988    private static boolean installForwardLocked(int installFlags) {
13989        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13990    }
13991
13992    private InstallArgs createInstallArgs(InstallParams params) {
13993        if (params.move != null) {
13994            return new MoveInstallArgs(params);
13995        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13996            return new AsecInstallArgs(params);
13997        } else {
13998            return new FileInstallArgs(params);
13999        }
14000    }
14001
14002    /**
14003     * Create args that describe an existing installed package. Typically used
14004     * when cleaning up old installs, or used as a move source.
14005     */
14006    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14007            String resourcePath, String[] instructionSets) {
14008        final boolean isInAsec;
14009        if (installOnExternalAsec(installFlags)) {
14010            /* Apps on SD card are always in ASEC containers. */
14011            isInAsec = true;
14012        } else if (installForwardLocked(installFlags)
14013                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14014            /*
14015             * Forward-locked apps are only in ASEC containers if they're the
14016             * new style
14017             */
14018            isInAsec = true;
14019        } else {
14020            isInAsec = false;
14021        }
14022
14023        if (isInAsec) {
14024            return new AsecInstallArgs(codePath, instructionSets,
14025                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14026        } else {
14027            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14028        }
14029    }
14030
14031    static abstract class InstallArgs {
14032        /** @see InstallParams#origin */
14033        final OriginInfo origin;
14034        /** @see InstallParams#move */
14035        final MoveInfo move;
14036
14037        final IPackageInstallObserver2 observer;
14038        // Always refers to PackageManager flags only
14039        final int installFlags;
14040        final String installerPackageName;
14041        final String volumeUuid;
14042        final UserHandle user;
14043        final String abiOverride;
14044        final String[] installGrantPermissions;
14045        /** If non-null, drop an async trace when the install completes */
14046        final String traceMethod;
14047        final int traceCookie;
14048        final Certificate[][] certificates;
14049        final int installReason;
14050
14051        // The list of instruction sets supported by this app. This is currently
14052        // only used during the rmdex() phase to clean up resources. We can get rid of this
14053        // if we move dex files under the common app path.
14054        /* nullable */ String[] instructionSets;
14055
14056        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14057                int installFlags, String installerPackageName, String volumeUuid,
14058                UserHandle user, String[] instructionSets,
14059                String abiOverride, String[] installGrantPermissions,
14060                String traceMethod, int traceCookie, Certificate[][] certificates,
14061                int installReason) {
14062            this.origin = origin;
14063            this.move = move;
14064            this.installFlags = installFlags;
14065            this.observer = observer;
14066            this.installerPackageName = installerPackageName;
14067            this.volumeUuid = volumeUuid;
14068            this.user = user;
14069            this.instructionSets = instructionSets;
14070            this.abiOverride = abiOverride;
14071            this.installGrantPermissions = installGrantPermissions;
14072            this.traceMethod = traceMethod;
14073            this.traceCookie = traceCookie;
14074            this.certificates = certificates;
14075            this.installReason = installReason;
14076        }
14077
14078        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14079        abstract int doPreInstall(int status);
14080
14081        /**
14082         * Rename package into final resting place. All paths on the given
14083         * scanned package should be updated to reflect the rename.
14084         */
14085        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14086        abstract int doPostInstall(int status, int uid);
14087
14088        /** @see PackageSettingBase#codePathString */
14089        abstract String getCodePath();
14090        /** @see PackageSettingBase#resourcePathString */
14091        abstract String getResourcePath();
14092
14093        // Need installer lock especially for dex file removal.
14094        abstract void cleanUpResourcesLI();
14095        abstract boolean doPostDeleteLI(boolean delete);
14096
14097        /**
14098         * Called before the source arguments are copied. This is used mostly
14099         * for MoveParams when it needs to read the source file to put it in the
14100         * destination.
14101         */
14102        int doPreCopy() {
14103            return PackageManager.INSTALL_SUCCEEDED;
14104        }
14105
14106        /**
14107         * Called after the source arguments are copied. This is used mostly for
14108         * MoveParams when it needs to read the source file to put it in the
14109         * destination.
14110         */
14111        int doPostCopy(int uid) {
14112            return PackageManager.INSTALL_SUCCEEDED;
14113        }
14114
14115        protected boolean isFwdLocked() {
14116            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14117        }
14118
14119        protected boolean isExternalAsec() {
14120            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14121        }
14122
14123        protected boolean isEphemeral() {
14124            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14125        }
14126
14127        UserHandle getUser() {
14128            return user;
14129        }
14130    }
14131
14132    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14133        if (!allCodePaths.isEmpty()) {
14134            if (instructionSets == null) {
14135                throw new IllegalStateException("instructionSet == null");
14136            }
14137            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14138            for (String codePath : allCodePaths) {
14139                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14140                    try {
14141                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14142                    } catch (InstallerException ignored) {
14143                    }
14144                }
14145            }
14146        }
14147    }
14148
14149    /**
14150     * Logic to handle installation of non-ASEC applications, including copying
14151     * and renaming logic.
14152     */
14153    class FileInstallArgs extends InstallArgs {
14154        private File codeFile;
14155        private File resourceFile;
14156
14157        // Example topology:
14158        // /data/app/com.example/base.apk
14159        // /data/app/com.example/split_foo.apk
14160        // /data/app/com.example/lib/arm/libfoo.so
14161        // /data/app/com.example/lib/arm64/libfoo.so
14162        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14163
14164        /** New install */
14165        FileInstallArgs(InstallParams params) {
14166            super(params.origin, params.move, params.observer, params.installFlags,
14167                    params.installerPackageName, params.volumeUuid,
14168                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14169                    params.grantedRuntimePermissions,
14170                    params.traceMethod, params.traceCookie, params.certificates,
14171                    params.installReason);
14172            if (isFwdLocked()) {
14173                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14174            }
14175        }
14176
14177        /** Existing install */
14178        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14179            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14180                    null, null, null, 0, null /*certificates*/,
14181                    PackageManager.INSTALL_REASON_UNKNOWN);
14182            this.codeFile = (codePath != null) ? new File(codePath) : null;
14183            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14184        }
14185
14186        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14187            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14188            try {
14189                return doCopyApk(imcs, temp);
14190            } finally {
14191                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14192            }
14193        }
14194
14195        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14196            if (origin.staged) {
14197                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14198                codeFile = origin.file;
14199                resourceFile = origin.file;
14200                return PackageManager.INSTALL_SUCCEEDED;
14201            }
14202
14203            try {
14204                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14205                final File tempDir =
14206                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14207                codeFile = tempDir;
14208                resourceFile = tempDir;
14209            } catch (IOException e) {
14210                Slog.w(TAG, "Failed to create copy file: " + e);
14211                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14212            }
14213
14214            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14215                @Override
14216                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14217                    if (!FileUtils.isValidExtFilename(name)) {
14218                        throw new IllegalArgumentException("Invalid filename: " + name);
14219                    }
14220                    try {
14221                        final File file = new File(codeFile, name);
14222                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14223                                O_RDWR | O_CREAT, 0644);
14224                        Os.chmod(file.getAbsolutePath(), 0644);
14225                        return new ParcelFileDescriptor(fd);
14226                    } catch (ErrnoException e) {
14227                        throw new RemoteException("Failed to open: " + e.getMessage());
14228                    }
14229                }
14230            };
14231
14232            int ret = PackageManager.INSTALL_SUCCEEDED;
14233            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14234            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14235                Slog.e(TAG, "Failed to copy package");
14236                return ret;
14237            }
14238
14239            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14240            NativeLibraryHelper.Handle handle = null;
14241            try {
14242                handle = NativeLibraryHelper.Handle.create(codeFile);
14243                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14244                        abiOverride);
14245            } catch (IOException e) {
14246                Slog.e(TAG, "Copying native libraries failed", e);
14247                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14248            } finally {
14249                IoUtils.closeQuietly(handle);
14250            }
14251
14252            return ret;
14253        }
14254
14255        int doPreInstall(int status) {
14256            if (status != PackageManager.INSTALL_SUCCEEDED) {
14257                cleanUp();
14258            }
14259            return status;
14260        }
14261
14262        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14263            if (status != PackageManager.INSTALL_SUCCEEDED) {
14264                cleanUp();
14265                return false;
14266            }
14267
14268            final File targetDir = codeFile.getParentFile();
14269            final File beforeCodeFile = codeFile;
14270            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14271
14272            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14273            try {
14274                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14275            } catch (ErrnoException e) {
14276                Slog.w(TAG, "Failed to rename", e);
14277                return false;
14278            }
14279
14280            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14281                Slog.w(TAG, "Failed to restorecon");
14282                return false;
14283            }
14284
14285            // Reflect the rename internally
14286            codeFile = afterCodeFile;
14287            resourceFile = afterCodeFile;
14288
14289            // Reflect the rename in scanned details
14290            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14291            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14292                    afterCodeFile, pkg.baseCodePath));
14293            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14294                    afterCodeFile, pkg.splitCodePaths));
14295
14296            // Reflect the rename in app info
14297            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14298            pkg.setApplicationInfoCodePath(pkg.codePath);
14299            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14300            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14301            pkg.setApplicationInfoResourcePath(pkg.codePath);
14302            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14303            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14304
14305            return true;
14306        }
14307
14308        int doPostInstall(int status, int uid) {
14309            if (status != PackageManager.INSTALL_SUCCEEDED) {
14310                cleanUp();
14311            }
14312            return status;
14313        }
14314
14315        @Override
14316        String getCodePath() {
14317            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14318        }
14319
14320        @Override
14321        String getResourcePath() {
14322            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14323        }
14324
14325        private boolean cleanUp() {
14326            if (codeFile == null || !codeFile.exists()) {
14327                return false;
14328            }
14329
14330            removeCodePathLI(codeFile);
14331
14332            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14333                resourceFile.delete();
14334            }
14335
14336            return true;
14337        }
14338
14339        void cleanUpResourcesLI() {
14340            // Try enumerating all code paths before deleting
14341            List<String> allCodePaths = Collections.EMPTY_LIST;
14342            if (codeFile != null && codeFile.exists()) {
14343                try {
14344                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14345                    allCodePaths = pkg.getAllCodePaths();
14346                } catch (PackageParserException e) {
14347                    // Ignored; we tried our best
14348                }
14349            }
14350
14351            cleanUp();
14352            removeDexFiles(allCodePaths, instructionSets);
14353        }
14354
14355        boolean doPostDeleteLI(boolean delete) {
14356            // XXX err, shouldn't we respect the delete flag?
14357            cleanUpResourcesLI();
14358            return true;
14359        }
14360    }
14361
14362    private boolean isAsecExternal(String cid) {
14363        final String asecPath = PackageHelper.getSdFilesystem(cid);
14364        return !asecPath.startsWith(mAsecInternalPath);
14365    }
14366
14367    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14368            PackageManagerException {
14369        if (copyRet < 0) {
14370            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14371                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14372                throw new PackageManagerException(copyRet, message);
14373            }
14374        }
14375    }
14376
14377    /**
14378     * Extract the StorageManagerService "container ID" from the full code path of an
14379     * .apk.
14380     */
14381    static String cidFromCodePath(String fullCodePath) {
14382        int eidx = fullCodePath.lastIndexOf("/");
14383        String subStr1 = fullCodePath.substring(0, eidx);
14384        int sidx = subStr1.lastIndexOf("/");
14385        return subStr1.substring(sidx+1, eidx);
14386    }
14387
14388    /**
14389     * Logic to handle installation of ASEC applications, including copying and
14390     * renaming logic.
14391     */
14392    class AsecInstallArgs extends InstallArgs {
14393        static final String RES_FILE_NAME = "pkg.apk";
14394        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14395
14396        String cid;
14397        String packagePath;
14398        String resourcePath;
14399
14400        /** New install */
14401        AsecInstallArgs(InstallParams params) {
14402            super(params.origin, params.move, params.observer, params.installFlags,
14403                    params.installerPackageName, params.volumeUuid,
14404                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14405                    params.grantedRuntimePermissions,
14406                    params.traceMethod, params.traceCookie, params.certificates,
14407                    params.installReason);
14408        }
14409
14410        /** Existing install */
14411        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14412                        boolean isExternal, boolean isForwardLocked) {
14413            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14414                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14415                    instructionSets, null, null, null, 0, null /*certificates*/,
14416                    PackageManager.INSTALL_REASON_UNKNOWN);
14417            // Hackily pretend we're still looking at a full code path
14418            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14419                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14420            }
14421
14422            // Extract cid from fullCodePath
14423            int eidx = fullCodePath.lastIndexOf("/");
14424            String subStr1 = fullCodePath.substring(0, eidx);
14425            int sidx = subStr1.lastIndexOf("/");
14426            cid = subStr1.substring(sidx+1, eidx);
14427            setMountPath(subStr1);
14428        }
14429
14430        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14431            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14432                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14433                    instructionSets, null, null, null, 0, null /*certificates*/,
14434                    PackageManager.INSTALL_REASON_UNKNOWN);
14435            this.cid = cid;
14436            setMountPath(PackageHelper.getSdDir(cid));
14437        }
14438
14439        void createCopyFile() {
14440            cid = mInstallerService.allocateExternalStageCidLegacy();
14441        }
14442
14443        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14444            if (origin.staged && origin.cid != null) {
14445                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14446                cid = origin.cid;
14447                setMountPath(PackageHelper.getSdDir(cid));
14448                return PackageManager.INSTALL_SUCCEEDED;
14449            }
14450
14451            if (temp) {
14452                createCopyFile();
14453            } else {
14454                /*
14455                 * Pre-emptively destroy the container since it's destroyed if
14456                 * copying fails due to it existing anyway.
14457                 */
14458                PackageHelper.destroySdDir(cid);
14459            }
14460
14461            final String newMountPath = imcs.copyPackageToContainer(
14462                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14463                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14464
14465            if (newMountPath != null) {
14466                setMountPath(newMountPath);
14467                return PackageManager.INSTALL_SUCCEEDED;
14468            } else {
14469                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14470            }
14471        }
14472
14473        @Override
14474        String getCodePath() {
14475            return packagePath;
14476        }
14477
14478        @Override
14479        String getResourcePath() {
14480            return resourcePath;
14481        }
14482
14483        int doPreInstall(int status) {
14484            if (status != PackageManager.INSTALL_SUCCEEDED) {
14485                // Destroy container
14486                PackageHelper.destroySdDir(cid);
14487            } else {
14488                boolean mounted = PackageHelper.isContainerMounted(cid);
14489                if (!mounted) {
14490                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14491                            Process.SYSTEM_UID);
14492                    if (newMountPath != null) {
14493                        setMountPath(newMountPath);
14494                    } else {
14495                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14496                    }
14497                }
14498            }
14499            return status;
14500        }
14501
14502        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14503            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14504            String newMountPath = null;
14505            if (PackageHelper.isContainerMounted(cid)) {
14506                // Unmount the container
14507                if (!PackageHelper.unMountSdDir(cid)) {
14508                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14509                    return false;
14510                }
14511            }
14512            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14513                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14514                        " which might be stale. Will try to clean up.");
14515                // Clean up the stale container and proceed to recreate.
14516                if (!PackageHelper.destroySdDir(newCacheId)) {
14517                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14518                    return false;
14519                }
14520                // Successfully cleaned up stale container. Try to rename again.
14521                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14522                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14523                            + " inspite of cleaning it up.");
14524                    return false;
14525                }
14526            }
14527            if (!PackageHelper.isContainerMounted(newCacheId)) {
14528                Slog.w(TAG, "Mounting container " + newCacheId);
14529                newMountPath = PackageHelper.mountSdDir(newCacheId,
14530                        getEncryptKey(), Process.SYSTEM_UID);
14531            } else {
14532                newMountPath = PackageHelper.getSdDir(newCacheId);
14533            }
14534            if (newMountPath == null) {
14535                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14536                return false;
14537            }
14538            Log.i(TAG, "Succesfully renamed " + cid +
14539                    " to " + newCacheId +
14540                    " at new path: " + newMountPath);
14541            cid = newCacheId;
14542
14543            final File beforeCodeFile = new File(packagePath);
14544            setMountPath(newMountPath);
14545            final File afterCodeFile = new File(packagePath);
14546
14547            // Reflect the rename in scanned details
14548            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14549            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14550                    afterCodeFile, pkg.baseCodePath));
14551            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14552                    afterCodeFile, pkg.splitCodePaths));
14553
14554            // Reflect the rename in app info
14555            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14556            pkg.setApplicationInfoCodePath(pkg.codePath);
14557            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14558            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14559            pkg.setApplicationInfoResourcePath(pkg.codePath);
14560            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14561            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14562
14563            return true;
14564        }
14565
14566        private void setMountPath(String mountPath) {
14567            final File mountFile = new File(mountPath);
14568
14569            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14570            if (monolithicFile.exists()) {
14571                packagePath = monolithicFile.getAbsolutePath();
14572                if (isFwdLocked()) {
14573                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14574                } else {
14575                    resourcePath = packagePath;
14576                }
14577            } else {
14578                packagePath = mountFile.getAbsolutePath();
14579                resourcePath = packagePath;
14580            }
14581        }
14582
14583        int doPostInstall(int status, int uid) {
14584            if (status != PackageManager.INSTALL_SUCCEEDED) {
14585                cleanUp();
14586            } else {
14587                final int groupOwner;
14588                final String protectedFile;
14589                if (isFwdLocked()) {
14590                    groupOwner = UserHandle.getSharedAppGid(uid);
14591                    protectedFile = RES_FILE_NAME;
14592                } else {
14593                    groupOwner = -1;
14594                    protectedFile = null;
14595                }
14596
14597                if (uid < Process.FIRST_APPLICATION_UID
14598                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14599                    Slog.e(TAG, "Failed to finalize " + cid);
14600                    PackageHelper.destroySdDir(cid);
14601                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14602                }
14603
14604                boolean mounted = PackageHelper.isContainerMounted(cid);
14605                if (!mounted) {
14606                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14607                }
14608            }
14609            return status;
14610        }
14611
14612        private void cleanUp() {
14613            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14614
14615            // Destroy secure container
14616            PackageHelper.destroySdDir(cid);
14617        }
14618
14619        private List<String> getAllCodePaths() {
14620            final File codeFile = new File(getCodePath());
14621            if (codeFile != null && codeFile.exists()) {
14622                try {
14623                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14624                    return pkg.getAllCodePaths();
14625                } catch (PackageParserException e) {
14626                    // Ignored; we tried our best
14627                }
14628            }
14629            return Collections.EMPTY_LIST;
14630        }
14631
14632        void cleanUpResourcesLI() {
14633            // Enumerate all code paths before deleting
14634            cleanUpResourcesLI(getAllCodePaths());
14635        }
14636
14637        private void cleanUpResourcesLI(List<String> allCodePaths) {
14638            cleanUp();
14639            removeDexFiles(allCodePaths, instructionSets);
14640        }
14641
14642        String getPackageName() {
14643            return getAsecPackageName(cid);
14644        }
14645
14646        boolean doPostDeleteLI(boolean delete) {
14647            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14648            final List<String> allCodePaths = getAllCodePaths();
14649            boolean mounted = PackageHelper.isContainerMounted(cid);
14650            if (mounted) {
14651                // Unmount first
14652                if (PackageHelper.unMountSdDir(cid)) {
14653                    mounted = false;
14654                }
14655            }
14656            if (!mounted && delete) {
14657                cleanUpResourcesLI(allCodePaths);
14658            }
14659            return !mounted;
14660        }
14661
14662        @Override
14663        int doPreCopy() {
14664            if (isFwdLocked()) {
14665                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14666                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14667                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14668                }
14669            }
14670
14671            return PackageManager.INSTALL_SUCCEEDED;
14672        }
14673
14674        @Override
14675        int doPostCopy(int uid) {
14676            if (isFwdLocked()) {
14677                if (uid < Process.FIRST_APPLICATION_UID
14678                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14679                                RES_FILE_NAME)) {
14680                    Slog.e(TAG, "Failed to finalize " + cid);
14681                    PackageHelper.destroySdDir(cid);
14682                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14683                }
14684            }
14685
14686            return PackageManager.INSTALL_SUCCEEDED;
14687        }
14688    }
14689
14690    /**
14691     * Logic to handle movement of existing installed applications.
14692     */
14693    class MoveInstallArgs extends InstallArgs {
14694        private File codeFile;
14695        private File resourceFile;
14696
14697        /** New install */
14698        MoveInstallArgs(InstallParams params) {
14699            super(params.origin, params.move, params.observer, params.installFlags,
14700                    params.installerPackageName, params.volumeUuid,
14701                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14702                    params.grantedRuntimePermissions,
14703                    params.traceMethod, params.traceCookie, params.certificates,
14704                    params.installReason);
14705        }
14706
14707        int copyApk(IMediaContainerService imcs, boolean temp) {
14708            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14709                    + move.fromUuid + " to " + move.toUuid);
14710            synchronized (mInstaller) {
14711                try {
14712                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14713                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14714                } catch (InstallerException e) {
14715                    Slog.w(TAG, "Failed to move app", e);
14716                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14717                }
14718            }
14719
14720            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14721            resourceFile = codeFile;
14722            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14723
14724            return PackageManager.INSTALL_SUCCEEDED;
14725        }
14726
14727        int doPreInstall(int status) {
14728            if (status != PackageManager.INSTALL_SUCCEEDED) {
14729                cleanUp(move.toUuid);
14730            }
14731            return status;
14732        }
14733
14734        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14735            if (status != PackageManager.INSTALL_SUCCEEDED) {
14736                cleanUp(move.toUuid);
14737                return false;
14738            }
14739
14740            // Reflect the move in app info
14741            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14742            pkg.setApplicationInfoCodePath(pkg.codePath);
14743            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14744            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14745            pkg.setApplicationInfoResourcePath(pkg.codePath);
14746            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14747            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14748
14749            return true;
14750        }
14751
14752        int doPostInstall(int status, int uid) {
14753            if (status == PackageManager.INSTALL_SUCCEEDED) {
14754                cleanUp(move.fromUuid);
14755            } else {
14756                cleanUp(move.toUuid);
14757            }
14758            return status;
14759        }
14760
14761        @Override
14762        String getCodePath() {
14763            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14764        }
14765
14766        @Override
14767        String getResourcePath() {
14768            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14769        }
14770
14771        private boolean cleanUp(String volumeUuid) {
14772            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14773                    move.dataAppName);
14774            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14775            final int[] userIds = sUserManager.getUserIds();
14776            synchronized (mInstallLock) {
14777                // Clean up both app data and code
14778                // All package moves are frozen until finished
14779                for (int userId : userIds) {
14780                    try {
14781                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14782                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14783                    } catch (InstallerException e) {
14784                        Slog.w(TAG, String.valueOf(e));
14785                    }
14786                }
14787                removeCodePathLI(codeFile);
14788            }
14789            return true;
14790        }
14791
14792        void cleanUpResourcesLI() {
14793            throw new UnsupportedOperationException();
14794        }
14795
14796        boolean doPostDeleteLI(boolean delete) {
14797            throw new UnsupportedOperationException();
14798        }
14799    }
14800
14801    static String getAsecPackageName(String packageCid) {
14802        int idx = packageCid.lastIndexOf("-");
14803        if (idx == -1) {
14804            return packageCid;
14805        }
14806        return packageCid.substring(0, idx);
14807    }
14808
14809    // Utility method used to create code paths based on package name and available index.
14810    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14811        String idxStr = "";
14812        int idx = 1;
14813        // Fall back to default value of idx=1 if prefix is not
14814        // part of oldCodePath
14815        if (oldCodePath != null) {
14816            String subStr = oldCodePath;
14817            // Drop the suffix right away
14818            if (suffix != null && subStr.endsWith(suffix)) {
14819                subStr = subStr.substring(0, subStr.length() - suffix.length());
14820            }
14821            // If oldCodePath already contains prefix find out the
14822            // ending index to either increment or decrement.
14823            int sidx = subStr.lastIndexOf(prefix);
14824            if (sidx != -1) {
14825                subStr = subStr.substring(sidx + prefix.length());
14826                if (subStr != null) {
14827                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14828                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14829                    }
14830                    try {
14831                        idx = Integer.parseInt(subStr);
14832                        if (idx <= 1) {
14833                            idx++;
14834                        } else {
14835                            idx--;
14836                        }
14837                    } catch(NumberFormatException e) {
14838                    }
14839                }
14840            }
14841        }
14842        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14843        return prefix + idxStr;
14844    }
14845
14846    private File getNextCodePath(File targetDir, String packageName) {
14847        File result;
14848        SecureRandom random = new SecureRandom();
14849        byte[] bytes = new byte[16];
14850        do {
14851            random.nextBytes(bytes);
14852            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14853            result = new File(targetDir, packageName + "-" + suffix);
14854        } while (result.exists());
14855        return result;
14856    }
14857
14858    // Utility method that returns the relative package path with respect
14859    // to the installation directory. Like say for /data/data/com.test-1.apk
14860    // string com.test-1 is returned.
14861    static String deriveCodePathName(String codePath) {
14862        if (codePath == null) {
14863            return null;
14864        }
14865        final File codeFile = new File(codePath);
14866        final String name = codeFile.getName();
14867        if (codeFile.isDirectory()) {
14868            return name;
14869        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14870            final int lastDot = name.lastIndexOf('.');
14871            return name.substring(0, lastDot);
14872        } else {
14873            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14874            return null;
14875        }
14876    }
14877
14878    static class PackageInstalledInfo {
14879        String name;
14880        int uid;
14881        // The set of users that originally had this package installed.
14882        int[] origUsers;
14883        // The set of users that now have this package installed.
14884        int[] newUsers;
14885        PackageParser.Package pkg;
14886        int returnCode;
14887        String returnMsg;
14888        PackageRemovedInfo removedInfo;
14889        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14890
14891        public void setError(int code, String msg) {
14892            setReturnCode(code);
14893            setReturnMessage(msg);
14894            Slog.w(TAG, msg);
14895        }
14896
14897        public void setError(String msg, PackageParserException e) {
14898            setReturnCode(e.error);
14899            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14900            Slog.w(TAG, msg, e);
14901        }
14902
14903        public void setError(String msg, PackageManagerException e) {
14904            returnCode = e.error;
14905            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14906            Slog.w(TAG, msg, e);
14907        }
14908
14909        public void setReturnCode(int returnCode) {
14910            this.returnCode = returnCode;
14911            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14912            for (int i = 0; i < childCount; i++) {
14913                addedChildPackages.valueAt(i).returnCode = returnCode;
14914            }
14915        }
14916
14917        private void setReturnMessage(String returnMsg) {
14918            this.returnMsg = returnMsg;
14919            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14920            for (int i = 0; i < childCount; i++) {
14921                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14922            }
14923        }
14924
14925        // In some error cases we want to convey more info back to the observer
14926        String origPackage;
14927        String origPermission;
14928    }
14929
14930    /*
14931     * Install a non-existing package.
14932     */
14933    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14934            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14935            PackageInstalledInfo res, int installReason) {
14936        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14937
14938        // Remember this for later, in case we need to rollback this install
14939        String pkgName = pkg.packageName;
14940
14941        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14942
14943        synchronized(mPackages) {
14944            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14945            if (renamedPackage != null) {
14946                // A package with the same name is already installed, though
14947                // it has been renamed to an older name.  The package we
14948                // are trying to install should be installed as an update to
14949                // the existing one, but that has not been requested, so bail.
14950                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14951                        + " without first uninstalling package running as "
14952                        + renamedPackage);
14953                return;
14954            }
14955            if (mPackages.containsKey(pkgName)) {
14956                // Don't allow installation over an existing package with the same name.
14957                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14958                        + " without first uninstalling.");
14959                return;
14960            }
14961        }
14962
14963        try {
14964            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14965                    System.currentTimeMillis(), user);
14966
14967            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
14968
14969            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14970                prepareAppDataAfterInstallLIF(newPackage);
14971
14972            } else {
14973                // Remove package from internal structures, but keep around any
14974                // data that might have already existed
14975                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14976                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14977            }
14978        } catch (PackageManagerException e) {
14979            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14980        }
14981
14982        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14983    }
14984
14985    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14986        // Can't rotate keys during boot or if sharedUser.
14987        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14988                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14989            return false;
14990        }
14991        // app is using upgradeKeySets; make sure all are valid
14992        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14993        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14994        for (int i = 0; i < upgradeKeySets.length; i++) {
14995            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14996                Slog.wtf(TAG, "Package "
14997                         + (oldPs.name != null ? oldPs.name : "<null>")
14998                         + " contains upgrade-key-set reference to unknown key-set: "
14999                         + upgradeKeySets[i]
15000                         + " reverting to signatures check.");
15001                return false;
15002            }
15003        }
15004        return true;
15005    }
15006
15007    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15008        // Upgrade keysets are being used.  Determine if new package has a superset of the
15009        // required keys.
15010        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15011        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15012        for (int i = 0; i < upgradeKeySets.length; i++) {
15013            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15014            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15015                return true;
15016            }
15017        }
15018        return false;
15019    }
15020
15021    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15022        try (DigestInputStream digestStream =
15023                new DigestInputStream(new FileInputStream(file), digest)) {
15024            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15025        }
15026    }
15027
15028    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15029            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15030            int installReason) {
15031        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15032
15033        final PackageParser.Package oldPackage;
15034        final String pkgName = pkg.packageName;
15035        final int[] allUsers;
15036        final int[] installedUsers;
15037
15038        synchronized(mPackages) {
15039            oldPackage = mPackages.get(pkgName);
15040            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15041
15042            // don't allow upgrade to target a release SDK from a pre-release SDK
15043            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15044                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15045            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15046                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15047            if (oldTargetsPreRelease
15048                    && !newTargetsPreRelease
15049                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15050                Slog.w(TAG, "Can't install package targeting released sdk");
15051                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15052                return;
15053            }
15054
15055            // don't allow an upgrade from full to ephemeral
15056            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
15057            if (isEphemeral && !oldIsEphemeral) {
15058                // can't downgrade from full to ephemeral
15059                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15060                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15061                return;
15062            }
15063
15064            // verify signatures are valid
15065            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15066            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15067                if (!checkUpgradeKeySetLP(ps, pkg)) {
15068                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15069                            "New package not signed by keys specified by upgrade-keysets: "
15070                                    + pkgName);
15071                    return;
15072                }
15073            } else {
15074                // default to original signature matching
15075                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15076                        != PackageManager.SIGNATURE_MATCH) {
15077                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15078                            "New package has a different signature: " + pkgName);
15079                    return;
15080                }
15081            }
15082
15083            // don't allow a system upgrade unless the upgrade hash matches
15084            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15085                byte[] digestBytes = null;
15086                try {
15087                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15088                    updateDigest(digest, new File(pkg.baseCodePath));
15089                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15090                        for (String path : pkg.splitCodePaths) {
15091                            updateDigest(digest, new File(path));
15092                        }
15093                    }
15094                    digestBytes = digest.digest();
15095                } catch (NoSuchAlgorithmException | IOException e) {
15096                    res.setError(INSTALL_FAILED_INVALID_APK,
15097                            "Could not compute hash: " + pkgName);
15098                    return;
15099                }
15100                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15101                    res.setError(INSTALL_FAILED_INVALID_APK,
15102                            "New package fails restrict-update check: " + pkgName);
15103                    return;
15104                }
15105                // retain upgrade restriction
15106                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15107            }
15108
15109            // Check for shared user id changes
15110            String invalidPackageName =
15111                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15112            if (invalidPackageName != null) {
15113                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15114                        "Package " + invalidPackageName + " tried to change user "
15115                                + oldPackage.mSharedUserId);
15116                return;
15117            }
15118
15119            // In case of rollback, remember per-user/profile install state
15120            allUsers = sUserManager.getUserIds();
15121            installedUsers = ps.queryInstalledUsers(allUsers, true);
15122        }
15123
15124        // Update what is removed
15125        res.removedInfo = new PackageRemovedInfo();
15126        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15127        res.removedInfo.removedPackage = oldPackage.packageName;
15128        res.removedInfo.isUpdate = true;
15129        res.removedInfo.origUsers = installedUsers;
15130        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15131        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15132        for (int i = 0; i < installedUsers.length; i++) {
15133            final int userId = installedUsers[i];
15134            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15135        }
15136
15137        final int childCount = (oldPackage.childPackages != null)
15138                ? oldPackage.childPackages.size() : 0;
15139        for (int i = 0; i < childCount; i++) {
15140            boolean childPackageUpdated = false;
15141            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15142            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15143            if (res.addedChildPackages != null) {
15144                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15145                if (childRes != null) {
15146                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15147                    childRes.removedInfo.removedPackage = childPkg.packageName;
15148                    childRes.removedInfo.isUpdate = true;
15149                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15150                    childPackageUpdated = true;
15151                }
15152            }
15153            if (!childPackageUpdated) {
15154                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15155                childRemovedRes.removedPackage = childPkg.packageName;
15156                childRemovedRes.isUpdate = false;
15157                childRemovedRes.dataRemoved = true;
15158                synchronized (mPackages) {
15159                    if (childPs != null) {
15160                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15161                    }
15162                }
15163                if (res.removedInfo.removedChildPackages == null) {
15164                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15165                }
15166                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15167            }
15168        }
15169
15170        boolean sysPkg = (isSystemApp(oldPackage));
15171        if (sysPkg) {
15172            // Set the system/privileged flags as needed
15173            final boolean privileged =
15174                    (oldPackage.applicationInfo.privateFlags
15175                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15176            final int systemPolicyFlags = policyFlags
15177                    | PackageParser.PARSE_IS_SYSTEM
15178                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15179
15180            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15181                    user, allUsers, installerPackageName, res, installReason);
15182        } else {
15183            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15184                    user, allUsers, installerPackageName, res, installReason);
15185        }
15186    }
15187
15188    public List<String> getPreviousCodePaths(String packageName) {
15189        final PackageSetting ps = mSettings.mPackages.get(packageName);
15190        final List<String> result = new ArrayList<String>();
15191        if (ps != null && ps.oldCodePaths != null) {
15192            result.addAll(ps.oldCodePaths);
15193        }
15194        return result;
15195    }
15196
15197    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15198            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15199            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15200            int installReason) {
15201        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15202                + deletedPackage);
15203
15204        String pkgName = deletedPackage.packageName;
15205        boolean deletedPkg = true;
15206        boolean addedPkg = false;
15207        boolean updatedSettings = false;
15208        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15209        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15210                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15211
15212        final long origUpdateTime = (pkg.mExtras != null)
15213                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15214
15215        // First delete the existing package while retaining the data directory
15216        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15217                res.removedInfo, true, pkg)) {
15218            // If the existing package wasn't successfully deleted
15219            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15220            deletedPkg = false;
15221        } else {
15222            // Successfully deleted the old package; proceed with replace.
15223
15224            // If deleted package lived in a container, give users a chance to
15225            // relinquish resources before killing.
15226            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15227                if (DEBUG_INSTALL) {
15228                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15229                }
15230                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15231                final ArrayList<String> pkgList = new ArrayList<String>(1);
15232                pkgList.add(deletedPackage.applicationInfo.packageName);
15233                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15234            }
15235
15236            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15237                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15238            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15239
15240            try {
15241                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15242                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15243                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15244                        installReason);
15245
15246                // Update the in-memory copy of the previous code paths.
15247                PackageSetting ps = mSettings.mPackages.get(pkgName);
15248                if (!killApp) {
15249                    if (ps.oldCodePaths == null) {
15250                        ps.oldCodePaths = new ArraySet<>();
15251                    }
15252                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15253                    if (deletedPackage.splitCodePaths != null) {
15254                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15255                    }
15256                } else {
15257                    ps.oldCodePaths = null;
15258                }
15259                if (ps.childPackageNames != null) {
15260                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15261                        final String childPkgName = ps.childPackageNames.get(i);
15262                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15263                        childPs.oldCodePaths = ps.oldCodePaths;
15264                    }
15265                }
15266                prepareAppDataAfterInstallLIF(newPackage);
15267                addedPkg = true;
15268            } catch (PackageManagerException e) {
15269                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15270            }
15271        }
15272
15273        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15274            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15275
15276            // Revert all internal state mutations and added folders for the failed install
15277            if (addedPkg) {
15278                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15279                        res.removedInfo, true, null);
15280            }
15281
15282            // Restore the old package
15283            if (deletedPkg) {
15284                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15285                File restoreFile = new File(deletedPackage.codePath);
15286                // Parse old package
15287                boolean oldExternal = isExternal(deletedPackage);
15288                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15289                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15290                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15291                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15292                try {
15293                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15294                            null);
15295                } catch (PackageManagerException e) {
15296                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15297                            + e.getMessage());
15298                    return;
15299                }
15300
15301                synchronized (mPackages) {
15302                    // Ensure the installer package name up to date
15303                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15304
15305                    // Update permissions for restored package
15306                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15307
15308                    mSettings.writeLPr();
15309                }
15310
15311                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15312            }
15313        } else {
15314            synchronized (mPackages) {
15315                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15316                if (ps != null) {
15317                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15318                    if (res.removedInfo.removedChildPackages != null) {
15319                        final int childCount = res.removedInfo.removedChildPackages.size();
15320                        // Iterate in reverse as we may modify the collection
15321                        for (int i = childCount - 1; i >= 0; i--) {
15322                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15323                            if (res.addedChildPackages.containsKey(childPackageName)) {
15324                                res.removedInfo.removedChildPackages.removeAt(i);
15325                            } else {
15326                                PackageRemovedInfo childInfo = res.removedInfo
15327                                        .removedChildPackages.valueAt(i);
15328                                childInfo.removedForAllUsers = mPackages.get(
15329                                        childInfo.removedPackage) == null;
15330                            }
15331                        }
15332                    }
15333                }
15334            }
15335        }
15336    }
15337
15338    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15339            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15340            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15341            int installReason) {
15342        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15343                + ", old=" + deletedPackage);
15344
15345        final boolean disabledSystem;
15346
15347        // Remove existing system package
15348        removePackageLI(deletedPackage, true);
15349
15350        synchronized (mPackages) {
15351            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15352        }
15353        if (!disabledSystem) {
15354            // We didn't need to disable the .apk as a current system package,
15355            // which means we are replacing another update that is already
15356            // installed.  We need to make sure to delete the older one's .apk.
15357            res.removedInfo.args = createInstallArgsForExisting(0,
15358                    deletedPackage.applicationInfo.getCodePath(),
15359                    deletedPackage.applicationInfo.getResourcePath(),
15360                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15361        } else {
15362            res.removedInfo.args = null;
15363        }
15364
15365        // Successfully disabled the old package. Now proceed with re-installation
15366        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15367                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15368        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15369
15370        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15371        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15372                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15373
15374        PackageParser.Package newPackage = null;
15375        try {
15376            // Add the package to the internal data structures
15377            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15378
15379            // Set the update and install times
15380            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15381            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15382                    System.currentTimeMillis());
15383
15384            // Update the package dynamic state if succeeded
15385            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15386                // Now that the install succeeded make sure we remove data
15387                // directories for any child package the update removed.
15388                final int deletedChildCount = (deletedPackage.childPackages != null)
15389                        ? deletedPackage.childPackages.size() : 0;
15390                final int newChildCount = (newPackage.childPackages != null)
15391                        ? newPackage.childPackages.size() : 0;
15392                for (int i = 0; i < deletedChildCount; i++) {
15393                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15394                    boolean childPackageDeleted = true;
15395                    for (int j = 0; j < newChildCount; j++) {
15396                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15397                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15398                            childPackageDeleted = false;
15399                            break;
15400                        }
15401                    }
15402                    if (childPackageDeleted) {
15403                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15404                                deletedChildPkg.packageName);
15405                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15406                            PackageRemovedInfo removedChildRes = res.removedInfo
15407                                    .removedChildPackages.get(deletedChildPkg.packageName);
15408                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15409                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15410                        }
15411                    }
15412                }
15413
15414                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15415                        installReason);
15416                prepareAppDataAfterInstallLIF(newPackage);
15417            }
15418        } catch (PackageManagerException e) {
15419            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15420            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15421        }
15422
15423        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15424            // Re installation failed. Restore old information
15425            // Remove new pkg information
15426            if (newPackage != null) {
15427                removeInstalledPackageLI(newPackage, true);
15428            }
15429            // Add back the old system package
15430            try {
15431                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15432            } catch (PackageManagerException e) {
15433                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15434            }
15435
15436            synchronized (mPackages) {
15437                if (disabledSystem) {
15438                    enableSystemPackageLPw(deletedPackage);
15439                }
15440
15441                // Ensure the installer package name up to date
15442                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15443
15444                // Update permissions for restored package
15445                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15446
15447                mSettings.writeLPr();
15448            }
15449
15450            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15451                    + " after failed upgrade");
15452        }
15453    }
15454
15455    /**
15456     * Checks whether the parent or any of the child packages have a change shared
15457     * user. For a package to be a valid update the shred users of the parent and
15458     * the children should match. We may later support changing child shared users.
15459     * @param oldPkg The updated package.
15460     * @param newPkg The update package.
15461     * @return The shared user that change between the versions.
15462     */
15463    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15464            PackageParser.Package newPkg) {
15465        // Check parent shared user
15466        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15467            return newPkg.packageName;
15468        }
15469        // Check child shared users
15470        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15471        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15472        for (int i = 0; i < newChildCount; i++) {
15473            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15474            // If this child was present, did it have the same shared user?
15475            for (int j = 0; j < oldChildCount; j++) {
15476                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15477                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15478                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15479                    return newChildPkg.packageName;
15480                }
15481            }
15482        }
15483        return null;
15484    }
15485
15486    private void removeNativeBinariesLI(PackageSetting ps) {
15487        // Remove the lib path for the parent package
15488        if (ps != null) {
15489            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15490            // Remove the lib path for the child packages
15491            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15492            for (int i = 0; i < childCount; i++) {
15493                PackageSetting childPs = null;
15494                synchronized (mPackages) {
15495                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15496                }
15497                if (childPs != null) {
15498                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15499                            .legacyNativeLibraryPathString);
15500                }
15501            }
15502        }
15503    }
15504
15505    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15506        // Enable the parent package
15507        mSettings.enableSystemPackageLPw(pkg.packageName);
15508        // Enable the child packages
15509        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15510        for (int i = 0; i < childCount; i++) {
15511            PackageParser.Package childPkg = pkg.childPackages.get(i);
15512            mSettings.enableSystemPackageLPw(childPkg.packageName);
15513        }
15514    }
15515
15516    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15517            PackageParser.Package newPkg) {
15518        // Disable the parent package (parent always replaced)
15519        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15520        // Disable the child packages
15521        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15522        for (int i = 0; i < childCount; i++) {
15523            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15524            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15525            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15526        }
15527        return disabled;
15528    }
15529
15530    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15531            String installerPackageName) {
15532        // Enable the parent package
15533        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15534        // Enable the child packages
15535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15536        for (int i = 0; i < childCount; i++) {
15537            PackageParser.Package childPkg = pkg.childPackages.get(i);
15538            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15539        }
15540    }
15541
15542    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15543        // Collect all used permissions in the UID
15544        ArraySet<String> usedPermissions = new ArraySet<>();
15545        final int packageCount = su.packages.size();
15546        for (int i = 0; i < packageCount; i++) {
15547            PackageSetting ps = su.packages.valueAt(i);
15548            if (ps.pkg == null) {
15549                continue;
15550            }
15551            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15552            for (int j = 0; j < requestedPermCount; j++) {
15553                String permission = ps.pkg.requestedPermissions.get(j);
15554                BasePermission bp = mSettings.mPermissions.get(permission);
15555                if (bp != null) {
15556                    usedPermissions.add(permission);
15557                }
15558            }
15559        }
15560
15561        PermissionsState permissionsState = su.getPermissionsState();
15562        // Prune install permissions
15563        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15564        final int installPermCount = installPermStates.size();
15565        for (int i = installPermCount - 1; i >= 0;  i--) {
15566            PermissionState permissionState = installPermStates.get(i);
15567            if (!usedPermissions.contains(permissionState.getName())) {
15568                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15569                if (bp != null) {
15570                    permissionsState.revokeInstallPermission(bp);
15571                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15572                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15573                }
15574            }
15575        }
15576
15577        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15578
15579        // Prune runtime permissions
15580        for (int userId : allUserIds) {
15581            List<PermissionState> runtimePermStates = permissionsState
15582                    .getRuntimePermissionStates(userId);
15583            final int runtimePermCount = runtimePermStates.size();
15584            for (int i = runtimePermCount - 1; i >= 0; i--) {
15585                PermissionState permissionState = runtimePermStates.get(i);
15586                if (!usedPermissions.contains(permissionState.getName())) {
15587                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15588                    if (bp != null) {
15589                        permissionsState.revokeRuntimePermission(bp, userId);
15590                        permissionsState.updatePermissionFlags(bp, userId,
15591                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15592                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15593                                runtimePermissionChangedUserIds, userId);
15594                    }
15595                }
15596            }
15597        }
15598
15599        return runtimePermissionChangedUserIds;
15600    }
15601
15602    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15603            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15604        // Update the parent package setting
15605        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15606                res, user, installReason);
15607        // Update the child packages setting
15608        final int childCount = (newPackage.childPackages != null)
15609                ? newPackage.childPackages.size() : 0;
15610        for (int i = 0; i < childCount; i++) {
15611            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15612            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15613            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15614                    childRes.origUsers, childRes, user, installReason);
15615        }
15616    }
15617
15618    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15619            String installerPackageName, int[] allUsers, int[] installedForUsers,
15620            PackageInstalledInfo res, UserHandle user, int installReason) {
15621        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15622
15623        String pkgName = newPackage.packageName;
15624        synchronized (mPackages) {
15625            //write settings. the installStatus will be incomplete at this stage.
15626            //note that the new package setting would have already been
15627            //added to mPackages. It hasn't been persisted yet.
15628            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15629            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15630            mSettings.writeLPr();
15631            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15632        }
15633
15634        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15635        synchronized (mPackages) {
15636            updatePermissionsLPw(newPackage.packageName, newPackage,
15637                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15638                            ? UPDATE_PERMISSIONS_ALL : 0));
15639            // For system-bundled packages, we assume that installing an upgraded version
15640            // of the package implies that the user actually wants to run that new code,
15641            // so we enable the package.
15642            PackageSetting ps = mSettings.mPackages.get(pkgName);
15643            final int userId = user.getIdentifier();
15644            if (ps != null) {
15645                if (isSystemApp(newPackage)) {
15646                    if (DEBUG_INSTALL) {
15647                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15648                    }
15649                    // Enable system package for requested users
15650                    if (res.origUsers != null) {
15651                        for (int origUserId : res.origUsers) {
15652                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15653                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15654                                        origUserId, installerPackageName);
15655                            }
15656                        }
15657                    }
15658                    // Also convey the prior install/uninstall state
15659                    if (allUsers != null && installedForUsers != null) {
15660                        for (int currentUserId : allUsers) {
15661                            final boolean installed = ArrayUtils.contains(
15662                                    installedForUsers, currentUserId);
15663                            if (DEBUG_INSTALL) {
15664                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15665                            }
15666                            ps.setInstalled(installed, currentUserId);
15667                        }
15668                        // these install state changes will be persisted in the
15669                        // upcoming call to mSettings.writeLPr().
15670                    }
15671                }
15672                // It's implied that when a user requests installation, they want the app to be
15673                // installed and enabled.
15674                if (userId != UserHandle.USER_ALL) {
15675                    ps.setInstalled(true, userId);
15676                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15677                }
15678
15679                // When replacing an existing package, preserve the original install reason for all
15680                // users that had the package installed before.
15681                final Set<Integer> previousUserIds = new ArraySet<>();
15682                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15683                    final int installReasonCount = res.removedInfo.installReasons.size();
15684                    for (int i = 0; i < installReasonCount; i++) {
15685                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15686                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15687                        ps.setInstallReason(previousInstallReason, previousUserId);
15688                        previousUserIds.add(previousUserId);
15689                    }
15690                }
15691
15692                // Set install reason for users that are having the package newly installed.
15693                if (userId == UserHandle.USER_ALL) {
15694                    for (int currentUserId : sUserManager.getUserIds()) {
15695                        if (!previousUserIds.contains(currentUserId)) {
15696                            ps.setInstallReason(installReason, currentUserId);
15697                        }
15698                    }
15699                } else if (!previousUserIds.contains(userId)) {
15700                    ps.setInstallReason(installReason, userId);
15701                }
15702            }
15703            res.name = pkgName;
15704            res.uid = newPackage.applicationInfo.uid;
15705            res.pkg = newPackage;
15706            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15707            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15708            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15709            //to update install status
15710            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15711            mSettings.writeLPr();
15712            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15713        }
15714
15715        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15716    }
15717
15718    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15719        try {
15720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15721            installPackageLI(args, res);
15722        } finally {
15723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15724        }
15725    }
15726
15727    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15728        final int installFlags = args.installFlags;
15729        final String installerPackageName = args.installerPackageName;
15730        final String volumeUuid = args.volumeUuid;
15731        final File tmpPackageFile = new File(args.getCodePath());
15732        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15733        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15734                || (args.volumeUuid != null));
15735        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15736        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15737        boolean replace = false;
15738        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15739        if (args.move != null) {
15740            // moving a complete application; perform an initial scan on the new install location
15741            scanFlags |= SCAN_INITIAL;
15742        }
15743        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15744            scanFlags |= SCAN_DONT_KILL_APP;
15745        }
15746
15747        // Result object to be returned
15748        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15749
15750        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15751
15752        // Sanity check
15753        if (ephemeral && (forwardLocked || onExternal)) {
15754            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15755                    + " external=" + onExternal);
15756            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15757            return;
15758        }
15759
15760        // Retrieve PackageSettings and parse package
15761        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15762                | PackageParser.PARSE_ENFORCE_CODE
15763                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15764                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15765                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15766                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15767        PackageParser pp = new PackageParser();
15768        pp.setSeparateProcesses(mSeparateProcesses);
15769        pp.setDisplayMetrics(mMetrics);
15770
15771        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15772        final PackageParser.Package pkg;
15773        try {
15774            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15775        } catch (PackageParserException e) {
15776            res.setError("Failed parse during installPackageLI", e);
15777            return;
15778        } finally {
15779            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15780        }
15781
15782        // Ephemeral apps must have target SDK >= O.
15783        // TODO: Update conditional and error message when O gets locked down
15784        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15785            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15786                    "Ephemeral apps must have target SDK version of at least O");
15787            return;
15788        }
15789
15790        // If we are installing a clustered package add results for the children
15791        if (pkg.childPackages != null) {
15792            synchronized (mPackages) {
15793                final int childCount = pkg.childPackages.size();
15794                for (int i = 0; i < childCount; i++) {
15795                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15796                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15797                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15798                    childRes.pkg = childPkg;
15799                    childRes.name = childPkg.packageName;
15800                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15801                    if (childPs != null) {
15802                        childRes.origUsers = childPs.queryInstalledUsers(
15803                                sUserManager.getUserIds(), true);
15804                    }
15805                    if ((mPackages.containsKey(childPkg.packageName))) {
15806                        childRes.removedInfo = new PackageRemovedInfo();
15807                        childRes.removedInfo.removedPackage = childPkg.packageName;
15808                    }
15809                    if (res.addedChildPackages == null) {
15810                        res.addedChildPackages = new ArrayMap<>();
15811                    }
15812                    res.addedChildPackages.put(childPkg.packageName, childRes);
15813                }
15814            }
15815        }
15816
15817        // If package doesn't declare API override, mark that we have an install
15818        // time CPU ABI override.
15819        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15820            pkg.cpuAbiOverride = args.abiOverride;
15821        }
15822
15823        String pkgName = res.name = pkg.packageName;
15824        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15825            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15826                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15827                return;
15828            }
15829        }
15830
15831        try {
15832            // either use what we've been given or parse directly from the APK
15833            if (args.certificates != null) {
15834                try {
15835                    PackageParser.populateCertificates(pkg, args.certificates);
15836                } catch (PackageParserException e) {
15837                    // there was something wrong with the certificates we were given;
15838                    // try to pull them from the APK
15839                    PackageParser.collectCertificates(pkg, parseFlags);
15840                }
15841            } else {
15842                PackageParser.collectCertificates(pkg, parseFlags);
15843            }
15844        } catch (PackageParserException e) {
15845            res.setError("Failed collect during installPackageLI", e);
15846            return;
15847        }
15848
15849        // Get rid of all references to package scan path via parser.
15850        pp = null;
15851        String oldCodePath = null;
15852        boolean systemApp = false;
15853        synchronized (mPackages) {
15854            // Check if installing already existing package
15855            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15856                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15857                if (pkg.mOriginalPackages != null
15858                        && pkg.mOriginalPackages.contains(oldName)
15859                        && mPackages.containsKey(oldName)) {
15860                    // This package is derived from an original package,
15861                    // and this device has been updating from that original
15862                    // name.  We must continue using the original name, so
15863                    // rename the new package here.
15864                    pkg.setPackageName(oldName);
15865                    pkgName = pkg.packageName;
15866                    replace = true;
15867                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15868                            + oldName + " pkgName=" + pkgName);
15869                } else if (mPackages.containsKey(pkgName)) {
15870                    // This package, under its official name, already exists
15871                    // on the device; we should replace it.
15872                    replace = true;
15873                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15874                }
15875
15876                // Child packages are installed through the parent package
15877                if (pkg.parentPackage != null) {
15878                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15879                            "Package " + pkg.packageName + " is child of package "
15880                                    + pkg.parentPackage.parentPackage + ". Child packages "
15881                                    + "can be updated only through the parent package.");
15882                    return;
15883                }
15884
15885                if (replace) {
15886                    // Prevent apps opting out from runtime permissions
15887                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15888                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15889                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15890                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15891                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15892                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15893                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15894                                        + " doesn't support runtime permissions but the old"
15895                                        + " target SDK " + oldTargetSdk + " does.");
15896                        return;
15897                    }
15898
15899                    // Prevent installing of child packages
15900                    if (oldPackage.parentPackage != null) {
15901                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15902                                "Package " + pkg.packageName + " is child of package "
15903                                        + oldPackage.parentPackage + ". Child packages "
15904                                        + "can be updated only through the parent package.");
15905                        return;
15906                    }
15907                }
15908            }
15909
15910            PackageSetting ps = mSettings.mPackages.get(pkgName);
15911            if (ps != null) {
15912                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15913
15914                // Quick sanity check that we're signed correctly if updating;
15915                // we'll check this again later when scanning, but we want to
15916                // bail early here before tripping over redefined permissions.
15917                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15918                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15919                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15920                                + pkg.packageName + " upgrade keys do not match the "
15921                                + "previously installed version");
15922                        return;
15923                    }
15924                } else {
15925                    try {
15926                        verifySignaturesLP(ps, pkg);
15927                    } catch (PackageManagerException e) {
15928                        res.setError(e.error, e.getMessage());
15929                        return;
15930                    }
15931                }
15932
15933                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15934                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15935                    systemApp = (ps.pkg.applicationInfo.flags &
15936                            ApplicationInfo.FLAG_SYSTEM) != 0;
15937                }
15938                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15939            }
15940
15941            // Check whether the newly-scanned package wants to define an already-defined perm
15942            int N = pkg.permissions.size();
15943            for (int i = N-1; i >= 0; i--) {
15944                PackageParser.Permission perm = pkg.permissions.get(i);
15945                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15946                if (bp != null) {
15947                    // If the defining package is signed with our cert, it's okay.  This
15948                    // also includes the "updating the same package" case, of course.
15949                    // "updating same package" could also involve key-rotation.
15950                    final boolean sigsOk;
15951                    if (bp.sourcePackage.equals(pkg.packageName)
15952                            && (bp.packageSetting instanceof PackageSetting)
15953                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15954                                    scanFlags))) {
15955                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15956                    } else {
15957                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15958                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15959                    }
15960                    if (!sigsOk) {
15961                        // If the owning package is the system itself, we log but allow
15962                        // install to proceed; we fail the install on all other permission
15963                        // redefinitions.
15964                        if (!bp.sourcePackage.equals("android")) {
15965                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15966                                    + pkg.packageName + " attempting to redeclare permission "
15967                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15968                            res.origPermission = perm.info.name;
15969                            res.origPackage = bp.sourcePackage;
15970                            return;
15971                        } else {
15972                            Slog.w(TAG, "Package " + pkg.packageName
15973                                    + " attempting to redeclare system permission "
15974                                    + perm.info.name + "; ignoring new declaration");
15975                            pkg.permissions.remove(i);
15976                        }
15977                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15978                        // Prevent apps to change protection level to dangerous from any other
15979                        // type as this would allow a privilege escalation where an app adds a
15980                        // normal/signature permission in other app's group and later redefines
15981                        // it as dangerous leading to the group auto-grant.
15982                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15983                                == PermissionInfo.PROTECTION_DANGEROUS) {
15984                            if (bp != null && !bp.isRuntime()) {
15985                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15986                                        + "non-runtime permission " + perm.info.name
15987                                        + " to runtime; keeping old protection level");
15988                                perm.info.protectionLevel = bp.protectionLevel;
15989                            }
15990                        }
15991                    }
15992                }
15993            }
15994        }
15995
15996        if (systemApp) {
15997            if (onExternal) {
15998                // Abort update; system app can't be replaced with app on sdcard
15999                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16000                        "Cannot install updates to system apps on sdcard");
16001                return;
16002            } else if (ephemeral) {
16003                // Abort update; system app can't be replaced with an ephemeral app
16004                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16005                        "Cannot update a system app with an ephemeral app");
16006                return;
16007            }
16008        }
16009
16010        if (args.move != null) {
16011            // We did an in-place move, so dex is ready to roll
16012            scanFlags |= SCAN_NO_DEX;
16013            scanFlags |= SCAN_MOVE;
16014
16015            synchronized (mPackages) {
16016                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16017                if (ps == null) {
16018                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16019                            "Missing settings for moved package " + pkgName);
16020                }
16021
16022                // We moved the entire application as-is, so bring over the
16023                // previously derived ABI information.
16024                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16025                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16026            }
16027
16028        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16029            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16030            scanFlags |= SCAN_NO_DEX;
16031
16032            try {
16033                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16034                    args.abiOverride : pkg.cpuAbiOverride);
16035                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16036                        true /*extractLibs*/, mAppLib32InstallDir);
16037            } catch (PackageManagerException pme) {
16038                Slog.e(TAG, "Error deriving application ABI", pme);
16039                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16040                return;
16041            }
16042
16043            // Shared libraries for the package need to be updated.
16044            synchronized (mPackages) {
16045                try {
16046                    updateSharedLibrariesLPr(pkg, null);
16047                } catch (PackageManagerException e) {
16048                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
16049                }
16050            }
16051            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16052            // Do not run PackageDexOptimizer through the local performDexOpt
16053            // method because `pkg` may not be in `mPackages` yet.
16054            //
16055            // Also, don't fail application installs if the dexopt step fails.
16056            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16057                    null /* instructionSets */, false /* checkProfiles */,
16058                    getCompilerFilterForReason(REASON_INSTALL),
16059                    getOrCreateCompilerPackageStats(pkg));
16060            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16061
16062            // Notify BackgroundDexOptService that the package has been changed.
16063            // If this is an update of a package which used to fail to compile,
16064            // BDOS will remove it from its blacklist.
16065            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16066        }
16067
16068        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16069            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16070            return;
16071        }
16072
16073        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16074
16075        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16076                "installPackageLI")) {
16077            if (replace) {
16078                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16079                        installerPackageName, res, args.installReason);
16080            } else {
16081                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16082                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16083            }
16084        }
16085        synchronized (mPackages) {
16086            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16087            if (ps != null) {
16088                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16089            }
16090
16091            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16092            for (int i = 0; i < childCount; i++) {
16093                PackageParser.Package childPkg = pkg.childPackages.get(i);
16094                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16095                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16096                if (childPs != null) {
16097                    childRes.newUsers = childPs.queryInstalledUsers(
16098                            sUserManager.getUserIds(), true);
16099                }
16100            }
16101        }
16102    }
16103
16104    private void startIntentFilterVerifications(int userId, boolean replacing,
16105            PackageParser.Package pkg) {
16106        if (mIntentFilterVerifierComponent == null) {
16107            Slog.w(TAG, "No IntentFilter verification will not be done as "
16108                    + "there is no IntentFilterVerifier available!");
16109            return;
16110        }
16111
16112        final int verifierUid = getPackageUid(
16113                mIntentFilterVerifierComponent.getPackageName(),
16114                MATCH_DEBUG_TRIAGED_MISSING,
16115                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16116
16117        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16118        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16119        mHandler.sendMessage(msg);
16120
16121        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16122        for (int i = 0; i < childCount; i++) {
16123            PackageParser.Package childPkg = pkg.childPackages.get(i);
16124            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16125            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16126            mHandler.sendMessage(msg);
16127        }
16128    }
16129
16130    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16131            PackageParser.Package pkg) {
16132        int size = pkg.activities.size();
16133        if (size == 0) {
16134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16135                    "No activity, so no need to verify any IntentFilter!");
16136            return;
16137        }
16138
16139        final boolean hasDomainURLs = hasDomainURLs(pkg);
16140        if (!hasDomainURLs) {
16141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16142                    "No domain URLs, so no need to verify any IntentFilter!");
16143            return;
16144        }
16145
16146        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16147                + " if any IntentFilter from the " + size
16148                + " Activities needs verification ...");
16149
16150        int count = 0;
16151        final String packageName = pkg.packageName;
16152
16153        synchronized (mPackages) {
16154            // If this is a new install and we see that we've already run verification for this
16155            // package, we have nothing to do: it means the state was restored from backup.
16156            if (!replacing) {
16157                IntentFilterVerificationInfo ivi =
16158                        mSettings.getIntentFilterVerificationLPr(packageName);
16159                if (ivi != null) {
16160                    if (DEBUG_DOMAIN_VERIFICATION) {
16161                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16162                                + ivi.getStatusString());
16163                    }
16164                    return;
16165                }
16166            }
16167
16168            // If any filters need to be verified, then all need to be.
16169            boolean needToVerify = false;
16170            for (PackageParser.Activity a : pkg.activities) {
16171                for (ActivityIntentInfo filter : a.intents) {
16172                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16173                        if (DEBUG_DOMAIN_VERIFICATION) {
16174                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16175                        }
16176                        needToVerify = true;
16177                        break;
16178                    }
16179                }
16180            }
16181
16182            if (needToVerify) {
16183                final int verificationId = mIntentFilterVerificationToken++;
16184                for (PackageParser.Activity a : pkg.activities) {
16185                    for (ActivityIntentInfo filter : a.intents) {
16186                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16187                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16188                                    "Verification needed for IntentFilter:" + filter.toString());
16189                            mIntentFilterVerifier.addOneIntentFilterVerification(
16190                                    verifierUid, userId, verificationId, filter, packageName);
16191                            count++;
16192                        }
16193                    }
16194                }
16195            }
16196        }
16197
16198        if (count > 0) {
16199            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16200                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16201                    +  " for userId:" + userId);
16202            mIntentFilterVerifier.startVerifications(userId);
16203        } else {
16204            if (DEBUG_DOMAIN_VERIFICATION) {
16205                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16206            }
16207        }
16208    }
16209
16210    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16211        final ComponentName cn  = filter.activity.getComponentName();
16212        final String packageName = cn.getPackageName();
16213
16214        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16215                packageName);
16216        if (ivi == null) {
16217            return true;
16218        }
16219        int status = ivi.getStatus();
16220        switch (status) {
16221            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16222            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16223                return true;
16224
16225            default:
16226                // Nothing to do
16227                return false;
16228        }
16229    }
16230
16231    private static boolean isMultiArch(ApplicationInfo info) {
16232        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16233    }
16234
16235    private static boolean isExternal(PackageParser.Package pkg) {
16236        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16237    }
16238
16239    private static boolean isExternal(PackageSetting ps) {
16240        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16241    }
16242
16243    private static boolean isEphemeral(PackageParser.Package pkg) {
16244        return pkg.applicationInfo.isEphemeralApp();
16245    }
16246
16247    private static boolean isEphemeral(PackageSetting ps) {
16248        return ps.pkg != null && isEphemeral(ps.pkg);
16249    }
16250
16251    private static boolean isSystemApp(PackageParser.Package pkg) {
16252        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16253    }
16254
16255    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16256        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16257    }
16258
16259    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16260        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16261    }
16262
16263    private static boolean isSystemApp(PackageSetting ps) {
16264        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16265    }
16266
16267    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16268        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16269    }
16270
16271    private int packageFlagsToInstallFlags(PackageSetting ps) {
16272        int installFlags = 0;
16273        if (isEphemeral(ps)) {
16274            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16275        }
16276        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16277            // This existing package was an external ASEC install when we have
16278            // the external flag without a UUID
16279            installFlags |= PackageManager.INSTALL_EXTERNAL;
16280        }
16281        if (ps.isForwardLocked()) {
16282            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16283        }
16284        return installFlags;
16285    }
16286
16287    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16288        if (isExternal(pkg)) {
16289            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16290                return StorageManager.UUID_PRIMARY_PHYSICAL;
16291            } else {
16292                return pkg.volumeUuid;
16293            }
16294        } else {
16295            return StorageManager.UUID_PRIVATE_INTERNAL;
16296        }
16297    }
16298
16299    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16300        if (isExternal(pkg)) {
16301            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16302                return mSettings.getExternalVersion();
16303            } else {
16304                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16305            }
16306        } else {
16307            return mSettings.getInternalVersion();
16308        }
16309    }
16310
16311    private void deleteTempPackageFiles() {
16312        final FilenameFilter filter = new FilenameFilter() {
16313            public boolean accept(File dir, String name) {
16314                return name.startsWith("vmdl") && name.endsWith(".tmp");
16315            }
16316        };
16317        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16318            file.delete();
16319        }
16320    }
16321
16322    @Override
16323    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16324            int flags) {
16325        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16326                flags);
16327    }
16328
16329    @Override
16330    public void deletePackage(final String packageName,
16331            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16332        mContext.enforceCallingOrSelfPermission(
16333                android.Manifest.permission.DELETE_PACKAGES, null);
16334        Preconditions.checkNotNull(packageName);
16335        Preconditions.checkNotNull(observer);
16336        final int uid = Binder.getCallingUid();
16337        if (!isOrphaned(packageName)
16338                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16339            try {
16340                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16341                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16342                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16343                observer.onUserActionRequired(intent);
16344            } catch (RemoteException re) {
16345            }
16346            return;
16347        }
16348        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16349        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16350        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16351            mContext.enforceCallingOrSelfPermission(
16352                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16353                    "deletePackage for user " + userId);
16354        }
16355
16356        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16357            try {
16358                observer.onPackageDeleted(packageName,
16359                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16360            } catch (RemoteException re) {
16361            }
16362            return;
16363        }
16364
16365        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16366            try {
16367                observer.onPackageDeleted(packageName,
16368                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16369            } catch (RemoteException re) {
16370            }
16371            return;
16372        }
16373
16374        if (DEBUG_REMOVE) {
16375            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16376                    + " deleteAllUsers: " + deleteAllUsers );
16377        }
16378        // Queue up an async operation since the package deletion may take a little while.
16379        mHandler.post(new Runnable() {
16380            public void run() {
16381                mHandler.removeCallbacks(this);
16382                int returnCode;
16383                if (!deleteAllUsers) {
16384                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16385                } else {
16386                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16387                    // If nobody is blocking uninstall, proceed with delete for all users
16388                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16389                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16390                    } else {
16391                        // Otherwise uninstall individually for users with blockUninstalls=false
16392                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16393                        for (int userId : users) {
16394                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16395                                returnCode = deletePackageX(packageName, userId, userFlags);
16396                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16397                                    Slog.w(TAG, "Package delete failed for user " + userId
16398                                            + ", returnCode " + returnCode);
16399                                }
16400                            }
16401                        }
16402                        // The app has only been marked uninstalled for certain users.
16403                        // We still need to report that delete was blocked
16404                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16405                    }
16406                }
16407                try {
16408                    observer.onPackageDeleted(packageName, returnCode, null);
16409                } catch (RemoteException e) {
16410                    Log.i(TAG, "Observer no longer exists.");
16411                } //end catch
16412            } //end run
16413        });
16414    }
16415
16416    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16417        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16418              || callingUid == Process.SYSTEM_UID) {
16419            return true;
16420        }
16421        final int callingUserId = UserHandle.getUserId(callingUid);
16422        // If the caller installed the pkgName, then allow it to silently uninstall.
16423        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16424            return true;
16425        }
16426
16427        // Allow package verifier to silently uninstall.
16428        if (mRequiredVerifierPackage != null &&
16429                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16430            return true;
16431        }
16432
16433        // Allow package uninstaller to silently uninstall.
16434        if (mRequiredUninstallerPackage != null &&
16435                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16436            return true;
16437        }
16438
16439        // Allow storage manager to silently uninstall.
16440        if (mStorageManagerPackage != null &&
16441                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16442            return true;
16443        }
16444        return false;
16445    }
16446
16447    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16448        int[] result = EMPTY_INT_ARRAY;
16449        for (int userId : userIds) {
16450            if (getBlockUninstallForUser(packageName, userId)) {
16451                result = ArrayUtils.appendInt(result, userId);
16452            }
16453        }
16454        return result;
16455    }
16456
16457    @Override
16458    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16459        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16460    }
16461
16462    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16463        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16464                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16465        try {
16466            if (dpm != null) {
16467                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16468                        /* callingUserOnly =*/ false);
16469                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16470                        : deviceOwnerComponentName.getPackageName();
16471                // Does the package contains the device owner?
16472                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16473                // this check is probably not needed, since DO should be registered as a device
16474                // admin on some user too. (Original bug for this: b/17657954)
16475                if (packageName.equals(deviceOwnerPackageName)) {
16476                    return true;
16477                }
16478                // Does it contain a device admin for any user?
16479                int[] users;
16480                if (userId == UserHandle.USER_ALL) {
16481                    users = sUserManager.getUserIds();
16482                } else {
16483                    users = new int[]{userId};
16484                }
16485                for (int i = 0; i < users.length; ++i) {
16486                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16487                        return true;
16488                    }
16489                }
16490            }
16491        } catch (RemoteException e) {
16492        }
16493        return false;
16494    }
16495
16496    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16497        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16498    }
16499
16500    /**
16501     *  This method is an internal method that could be get invoked either
16502     *  to delete an installed package or to clean up a failed installation.
16503     *  After deleting an installed package, a broadcast is sent to notify any
16504     *  listeners that the package has been removed. For cleaning up a failed
16505     *  installation, the broadcast is not necessary since the package's
16506     *  installation wouldn't have sent the initial broadcast either
16507     *  The key steps in deleting a package are
16508     *  deleting the package information in internal structures like mPackages,
16509     *  deleting the packages base directories through installd
16510     *  updating mSettings to reflect current status
16511     *  persisting settings for later use
16512     *  sending a broadcast if necessary
16513     */
16514    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16515        final PackageRemovedInfo info = new PackageRemovedInfo();
16516        final boolean res;
16517
16518        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16519                ? UserHandle.USER_ALL : userId;
16520
16521        if (isPackageDeviceAdmin(packageName, removeUser)) {
16522            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16523            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16524        }
16525
16526        PackageSetting uninstalledPs = null;
16527
16528        // for the uninstall-updates case and restricted profiles, remember the per-
16529        // user handle installed state
16530        int[] allUsers;
16531        synchronized (mPackages) {
16532            uninstalledPs = mSettings.mPackages.get(packageName);
16533            if (uninstalledPs == null) {
16534                Slog.w(TAG, "Not removing non-existent package " + packageName);
16535                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16536            }
16537            allUsers = sUserManager.getUserIds();
16538            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16539        }
16540
16541        final int freezeUser;
16542        if (isUpdatedSystemApp(uninstalledPs)
16543                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16544            // We're downgrading a system app, which will apply to all users, so
16545            // freeze them all during the downgrade
16546            freezeUser = UserHandle.USER_ALL;
16547        } else {
16548            freezeUser = removeUser;
16549        }
16550
16551        synchronized (mInstallLock) {
16552            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16553            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16554                    deleteFlags, "deletePackageX")) {
16555                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16556                        deleteFlags | REMOVE_CHATTY, info, true, null);
16557            }
16558            synchronized (mPackages) {
16559                if (res) {
16560                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16561                }
16562            }
16563        }
16564
16565        if (res) {
16566            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16567            info.sendPackageRemovedBroadcasts(killApp);
16568            info.sendSystemPackageUpdatedBroadcasts();
16569            info.sendSystemPackageAppearedBroadcasts();
16570        }
16571        // Force a gc here.
16572        Runtime.getRuntime().gc();
16573        // Delete the resources here after sending the broadcast to let
16574        // other processes clean up before deleting resources.
16575        if (info.args != null) {
16576            synchronized (mInstallLock) {
16577                info.args.doPostDeleteLI(true);
16578            }
16579        }
16580
16581        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16582    }
16583
16584    class PackageRemovedInfo {
16585        String removedPackage;
16586        int uid = -1;
16587        int removedAppId = -1;
16588        int[] origUsers;
16589        int[] removedUsers = null;
16590        SparseArray<Integer> installReasons;
16591        boolean isRemovedPackageSystemUpdate = false;
16592        boolean isUpdate;
16593        boolean dataRemoved;
16594        boolean removedForAllUsers;
16595        // Clean up resources deleted packages.
16596        InstallArgs args = null;
16597        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16598        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16599
16600        void sendPackageRemovedBroadcasts(boolean killApp) {
16601            sendPackageRemovedBroadcastInternal(killApp);
16602            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16603            for (int i = 0; i < childCount; i++) {
16604                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16605                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16606            }
16607        }
16608
16609        void sendSystemPackageUpdatedBroadcasts() {
16610            if (isRemovedPackageSystemUpdate) {
16611                sendSystemPackageUpdatedBroadcastsInternal();
16612                final int childCount = (removedChildPackages != null)
16613                        ? removedChildPackages.size() : 0;
16614                for (int i = 0; i < childCount; i++) {
16615                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16616                    if (childInfo.isRemovedPackageSystemUpdate) {
16617                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16618                    }
16619                }
16620            }
16621        }
16622
16623        void sendSystemPackageAppearedBroadcasts() {
16624            final int packageCount = (appearedChildPackages != null)
16625                    ? appearedChildPackages.size() : 0;
16626            for (int i = 0; i < packageCount; i++) {
16627                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16628                sendPackageAddedForNewUsers(installedInfo.name, true,
16629                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16630            }
16631        }
16632
16633        private void sendSystemPackageUpdatedBroadcastsInternal() {
16634            Bundle extras = new Bundle(2);
16635            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16636            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16637            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16638                    extras, 0, null, null, null);
16639            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16640                    extras, 0, null, null, null);
16641            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16642                    null, 0, removedPackage, null, null);
16643        }
16644
16645        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16646            Bundle extras = new Bundle(2);
16647            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16648            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16649            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16650            if (isUpdate || isRemovedPackageSystemUpdate) {
16651                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16652            }
16653            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16654            if (removedPackage != null) {
16655                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16656                        extras, 0, null, null, removedUsers);
16657                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16658                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16659                            removedPackage, extras, 0, null, null, removedUsers);
16660                }
16661            }
16662            if (removedAppId >= 0) {
16663                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16664                        removedUsers);
16665            }
16666        }
16667    }
16668
16669    /*
16670     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16671     * flag is not set, the data directory is removed as well.
16672     * make sure this flag is set for partially installed apps. If not its meaningless to
16673     * delete a partially installed application.
16674     */
16675    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16676            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16677        String packageName = ps.name;
16678        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16679        // Retrieve object to delete permissions for shared user later on
16680        final PackageParser.Package deletedPkg;
16681        final PackageSetting deletedPs;
16682        // reader
16683        synchronized (mPackages) {
16684            deletedPkg = mPackages.get(packageName);
16685            deletedPs = mSettings.mPackages.get(packageName);
16686            if (outInfo != null) {
16687                outInfo.removedPackage = packageName;
16688                outInfo.removedUsers = deletedPs != null
16689                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16690                        : null;
16691            }
16692        }
16693
16694        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16695
16696        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16697            final PackageParser.Package resolvedPkg;
16698            if (deletedPkg != null) {
16699                resolvedPkg = deletedPkg;
16700            } else {
16701                // We don't have a parsed package when it lives on an ejected
16702                // adopted storage device, so fake something together
16703                resolvedPkg = new PackageParser.Package(ps.name);
16704                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16705            }
16706            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16707                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16708            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16709            if (outInfo != null) {
16710                outInfo.dataRemoved = true;
16711            }
16712            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16713        }
16714
16715        // writer
16716        synchronized (mPackages) {
16717            if (deletedPs != null) {
16718                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16719                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16720                    clearDefaultBrowserIfNeeded(packageName);
16721                    if (outInfo != null) {
16722                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16723                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16724                    }
16725                    updatePermissionsLPw(deletedPs.name, null, 0);
16726                    if (deletedPs.sharedUser != null) {
16727                        // Remove permissions associated with package. Since runtime
16728                        // permissions are per user we have to kill the removed package
16729                        // or packages running under the shared user of the removed
16730                        // package if revoking the permissions requested only by the removed
16731                        // package is successful and this causes a change in gids.
16732                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16733                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16734                                    userId);
16735                            if (userIdToKill == UserHandle.USER_ALL
16736                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16737                                // If gids changed for this user, kill all affected packages.
16738                                mHandler.post(new Runnable() {
16739                                    @Override
16740                                    public void run() {
16741                                        // This has to happen with no lock held.
16742                                        killApplication(deletedPs.name, deletedPs.appId,
16743                                                KILL_APP_REASON_GIDS_CHANGED);
16744                                    }
16745                                });
16746                                break;
16747                            }
16748                        }
16749                    }
16750                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16751                }
16752                // make sure to preserve per-user disabled state if this removal was just
16753                // a downgrade of a system app to the factory package
16754                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16755                    if (DEBUG_REMOVE) {
16756                        Slog.d(TAG, "Propagating install state across downgrade");
16757                    }
16758                    for (int userId : allUserHandles) {
16759                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16760                        if (DEBUG_REMOVE) {
16761                            Slog.d(TAG, "    user " + userId + " => " + installed);
16762                        }
16763                        ps.setInstalled(installed, userId);
16764                    }
16765                }
16766            }
16767            // can downgrade to reader
16768            if (writeSettings) {
16769                // Save settings now
16770                mSettings.writeLPr();
16771            }
16772        }
16773        if (outInfo != null) {
16774            // A user ID was deleted here. Go through all users and remove it
16775            // from KeyStore.
16776            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16777        }
16778    }
16779
16780    static boolean locationIsPrivileged(File path) {
16781        try {
16782            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16783                    .getCanonicalPath();
16784            return path.getCanonicalPath().startsWith(privilegedAppDir);
16785        } catch (IOException e) {
16786            Slog.e(TAG, "Unable to access code path " + path);
16787        }
16788        return false;
16789    }
16790
16791    /*
16792     * Tries to delete system package.
16793     */
16794    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16795            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16796            boolean writeSettings) {
16797        if (deletedPs.parentPackageName != null) {
16798            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16799            return false;
16800        }
16801
16802        final boolean applyUserRestrictions
16803                = (allUserHandles != null) && (outInfo.origUsers != null);
16804        final PackageSetting disabledPs;
16805        // Confirm if the system package has been updated
16806        // An updated system app can be deleted. This will also have to restore
16807        // the system pkg from system partition
16808        // reader
16809        synchronized (mPackages) {
16810            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16811        }
16812
16813        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16814                + " disabledPs=" + disabledPs);
16815
16816        if (disabledPs == null) {
16817            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16818            return false;
16819        } else if (DEBUG_REMOVE) {
16820            Slog.d(TAG, "Deleting system pkg from data partition");
16821        }
16822
16823        if (DEBUG_REMOVE) {
16824            if (applyUserRestrictions) {
16825                Slog.d(TAG, "Remembering install states:");
16826                for (int userId : allUserHandles) {
16827                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16828                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16829                }
16830            }
16831        }
16832
16833        // Delete the updated package
16834        outInfo.isRemovedPackageSystemUpdate = true;
16835        if (outInfo.removedChildPackages != null) {
16836            final int childCount = (deletedPs.childPackageNames != null)
16837                    ? deletedPs.childPackageNames.size() : 0;
16838            for (int i = 0; i < childCount; i++) {
16839                String childPackageName = deletedPs.childPackageNames.get(i);
16840                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16841                        .contains(childPackageName)) {
16842                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16843                            childPackageName);
16844                    if (childInfo != null) {
16845                        childInfo.isRemovedPackageSystemUpdate = true;
16846                    }
16847                }
16848            }
16849        }
16850
16851        if (disabledPs.versionCode < deletedPs.versionCode) {
16852            // Delete data for downgrades
16853            flags &= ~PackageManager.DELETE_KEEP_DATA;
16854        } else {
16855            // Preserve data by setting flag
16856            flags |= PackageManager.DELETE_KEEP_DATA;
16857        }
16858
16859        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16860                outInfo, writeSettings, disabledPs.pkg);
16861        if (!ret) {
16862            return false;
16863        }
16864
16865        // writer
16866        synchronized (mPackages) {
16867            // Reinstate the old system package
16868            enableSystemPackageLPw(disabledPs.pkg);
16869            // Remove any native libraries from the upgraded package.
16870            removeNativeBinariesLI(deletedPs);
16871        }
16872
16873        // Install the system package
16874        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16875        int parseFlags = mDefParseFlags
16876                | PackageParser.PARSE_MUST_BE_APK
16877                | PackageParser.PARSE_IS_SYSTEM
16878                | PackageParser.PARSE_IS_SYSTEM_DIR;
16879        if (locationIsPrivileged(disabledPs.codePath)) {
16880            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16881        }
16882
16883        final PackageParser.Package newPkg;
16884        try {
16885            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16886                0 /* currentTime */, null);
16887        } catch (PackageManagerException e) {
16888            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16889                    + e.getMessage());
16890            return false;
16891        }
16892        try {
16893            // update shared libraries for the newly re-installed system package
16894            updateSharedLibrariesLPr(newPkg, null);
16895        } catch (PackageManagerException e) {
16896            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16897        }
16898
16899        prepareAppDataAfterInstallLIF(newPkg);
16900
16901        // writer
16902        synchronized (mPackages) {
16903            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16904
16905            // Propagate the permissions state as we do not want to drop on the floor
16906            // runtime permissions. The update permissions method below will take
16907            // care of removing obsolete permissions and grant install permissions.
16908            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16909            updatePermissionsLPw(newPkg.packageName, newPkg,
16910                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16911
16912            if (applyUserRestrictions) {
16913                if (DEBUG_REMOVE) {
16914                    Slog.d(TAG, "Propagating install state across reinstall");
16915                }
16916                for (int userId : allUserHandles) {
16917                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16918                    if (DEBUG_REMOVE) {
16919                        Slog.d(TAG, "    user " + userId + " => " + installed);
16920                    }
16921                    ps.setInstalled(installed, userId);
16922
16923                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16924                }
16925                // Regardless of writeSettings we need to ensure that this restriction
16926                // state propagation is persisted
16927                mSettings.writeAllUsersPackageRestrictionsLPr();
16928            }
16929            // can downgrade to reader here
16930            if (writeSettings) {
16931                mSettings.writeLPr();
16932            }
16933        }
16934        return true;
16935    }
16936
16937    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16938            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16939            PackageRemovedInfo outInfo, boolean writeSettings,
16940            PackageParser.Package replacingPackage) {
16941        synchronized (mPackages) {
16942            if (outInfo != null) {
16943                outInfo.uid = ps.appId;
16944            }
16945
16946            if (outInfo != null && outInfo.removedChildPackages != null) {
16947                final int childCount = (ps.childPackageNames != null)
16948                        ? ps.childPackageNames.size() : 0;
16949                for (int i = 0; i < childCount; i++) {
16950                    String childPackageName = ps.childPackageNames.get(i);
16951                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16952                    if (childPs == null) {
16953                        return false;
16954                    }
16955                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16956                            childPackageName);
16957                    if (childInfo != null) {
16958                        childInfo.uid = childPs.appId;
16959                    }
16960                }
16961            }
16962        }
16963
16964        // Delete package data from internal structures and also remove data if flag is set
16965        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16966
16967        // Delete the child packages data
16968        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16969        for (int i = 0; i < childCount; i++) {
16970            PackageSetting childPs;
16971            synchronized (mPackages) {
16972                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16973            }
16974            if (childPs != null) {
16975                PackageRemovedInfo childOutInfo = (outInfo != null
16976                        && outInfo.removedChildPackages != null)
16977                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16978                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16979                        && (replacingPackage != null
16980                        && !replacingPackage.hasChildPackage(childPs.name))
16981                        ? flags & ~DELETE_KEEP_DATA : flags;
16982                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16983                        deleteFlags, writeSettings);
16984            }
16985        }
16986
16987        // Delete application code and resources only for parent packages
16988        if (ps.parentPackageName == null) {
16989            if (deleteCodeAndResources && (outInfo != null)) {
16990                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16991                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16992                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16993            }
16994        }
16995
16996        return true;
16997    }
16998
16999    @Override
17000    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17001            int userId) {
17002        mContext.enforceCallingOrSelfPermission(
17003                android.Manifest.permission.DELETE_PACKAGES, null);
17004        synchronized (mPackages) {
17005            PackageSetting ps = mSettings.mPackages.get(packageName);
17006            if (ps == null) {
17007                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17008                return false;
17009            }
17010            if (!ps.getInstalled(userId)) {
17011                // Can't block uninstall for an app that is not installed or enabled.
17012                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17013                return false;
17014            }
17015            ps.setBlockUninstall(blockUninstall, userId);
17016            mSettings.writePackageRestrictionsLPr(userId);
17017        }
17018        return true;
17019    }
17020
17021    @Override
17022    public boolean getBlockUninstallForUser(String packageName, int userId) {
17023        synchronized (mPackages) {
17024            PackageSetting ps = mSettings.mPackages.get(packageName);
17025            if (ps == null) {
17026                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17027                return false;
17028            }
17029            return ps.getBlockUninstall(userId);
17030        }
17031    }
17032
17033    @Override
17034    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17035        int callingUid = Binder.getCallingUid();
17036        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17037            throw new SecurityException(
17038                    "setRequiredForSystemUser can only be run by the system or root");
17039        }
17040        synchronized (mPackages) {
17041            PackageSetting ps = mSettings.mPackages.get(packageName);
17042            if (ps == null) {
17043                Log.w(TAG, "Package doesn't exist: " + packageName);
17044                return false;
17045            }
17046            if (systemUserApp) {
17047                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17048            } else {
17049                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17050            }
17051            mSettings.writeLPr();
17052        }
17053        return true;
17054    }
17055
17056    /*
17057     * This method handles package deletion in general
17058     */
17059    private boolean deletePackageLIF(String packageName, UserHandle user,
17060            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17061            PackageRemovedInfo outInfo, boolean writeSettings,
17062            PackageParser.Package replacingPackage) {
17063        if (packageName == null) {
17064            Slog.w(TAG, "Attempt to delete null packageName.");
17065            return false;
17066        }
17067
17068        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17069
17070        PackageSetting ps;
17071
17072        synchronized (mPackages) {
17073            ps = mSettings.mPackages.get(packageName);
17074            if (ps == null) {
17075                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17076                return false;
17077            }
17078
17079            if (ps.parentPackageName != null && (!isSystemApp(ps)
17080                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17081                if (DEBUG_REMOVE) {
17082                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17083                            + ((user == null) ? UserHandle.USER_ALL : user));
17084                }
17085                final int removedUserId = (user != null) ? user.getIdentifier()
17086                        : UserHandle.USER_ALL;
17087                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17088                    return false;
17089                }
17090                markPackageUninstalledForUserLPw(ps, user);
17091                scheduleWritePackageRestrictionsLocked(user);
17092                return true;
17093            }
17094        }
17095
17096        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17097                && user.getIdentifier() != UserHandle.USER_ALL)) {
17098            // The caller is asking that the package only be deleted for a single
17099            // user.  To do this, we just mark its uninstalled state and delete
17100            // its data. If this is a system app, we only allow this to happen if
17101            // they have set the special DELETE_SYSTEM_APP which requests different
17102            // semantics than normal for uninstalling system apps.
17103            markPackageUninstalledForUserLPw(ps, user);
17104
17105            if (!isSystemApp(ps)) {
17106                // Do not uninstall the APK if an app should be cached
17107                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17108                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17109                    // Other user still have this package installed, so all
17110                    // we need to do is clear this user's data and save that
17111                    // it is uninstalled.
17112                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17113                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17114                        return false;
17115                    }
17116                    scheduleWritePackageRestrictionsLocked(user);
17117                    return true;
17118                } else {
17119                    // We need to set it back to 'installed' so the uninstall
17120                    // broadcasts will be sent correctly.
17121                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17122                    ps.setInstalled(true, user.getIdentifier());
17123                }
17124            } else {
17125                // This is a system app, so we assume that the
17126                // other users still have this package installed, so all
17127                // we need to do is clear this user's data and save that
17128                // it is uninstalled.
17129                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17130                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17131                    return false;
17132                }
17133                scheduleWritePackageRestrictionsLocked(user);
17134                return true;
17135            }
17136        }
17137
17138        // If we are deleting a composite package for all users, keep track
17139        // of result for each child.
17140        if (ps.childPackageNames != null && outInfo != null) {
17141            synchronized (mPackages) {
17142                final int childCount = ps.childPackageNames.size();
17143                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17144                for (int i = 0; i < childCount; i++) {
17145                    String childPackageName = ps.childPackageNames.get(i);
17146                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17147                    childInfo.removedPackage = childPackageName;
17148                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17149                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17150                    if (childPs != null) {
17151                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17152                    }
17153                }
17154            }
17155        }
17156
17157        boolean ret = false;
17158        if (isSystemApp(ps)) {
17159            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17160            // When an updated system application is deleted we delete the existing resources
17161            // as well and fall back to existing code in system partition
17162            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17163        } else {
17164            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17165            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17166                    outInfo, writeSettings, replacingPackage);
17167        }
17168
17169        // Take a note whether we deleted the package for all users
17170        if (outInfo != null) {
17171            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17172            if (outInfo.removedChildPackages != null) {
17173                synchronized (mPackages) {
17174                    final int childCount = outInfo.removedChildPackages.size();
17175                    for (int i = 0; i < childCount; i++) {
17176                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17177                        if (childInfo != null) {
17178                            childInfo.removedForAllUsers = mPackages.get(
17179                                    childInfo.removedPackage) == null;
17180                        }
17181                    }
17182                }
17183            }
17184            // If we uninstalled an update to a system app there may be some
17185            // child packages that appeared as they are declared in the system
17186            // app but were not declared in the update.
17187            if (isSystemApp(ps)) {
17188                synchronized (mPackages) {
17189                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17190                    final int childCount = (updatedPs.childPackageNames != null)
17191                            ? updatedPs.childPackageNames.size() : 0;
17192                    for (int i = 0; i < childCount; i++) {
17193                        String childPackageName = updatedPs.childPackageNames.get(i);
17194                        if (outInfo.removedChildPackages == null
17195                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17196                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17197                            if (childPs == null) {
17198                                continue;
17199                            }
17200                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17201                            installRes.name = childPackageName;
17202                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17203                            installRes.pkg = mPackages.get(childPackageName);
17204                            installRes.uid = childPs.pkg.applicationInfo.uid;
17205                            if (outInfo.appearedChildPackages == null) {
17206                                outInfo.appearedChildPackages = new ArrayMap<>();
17207                            }
17208                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17209                        }
17210                    }
17211                }
17212            }
17213        }
17214
17215        return ret;
17216    }
17217
17218    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17219        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17220                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17221        for (int nextUserId : userIds) {
17222            if (DEBUG_REMOVE) {
17223                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17224            }
17225            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17226                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
17227                    false /*hidden*/, false /*suspended*/, null, null, null,
17228                    false /*blockUninstall*/,
17229                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
17230                    PackageManager.INSTALL_REASON_UNKNOWN);
17231        }
17232    }
17233
17234    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17235            PackageRemovedInfo outInfo) {
17236        final PackageParser.Package pkg;
17237        synchronized (mPackages) {
17238            pkg = mPackages.get(ps.name);
17239        }
17240
17241        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17242                : new int[] {userId};
17243        for (int nextUserId : userIds) {
17244            if (DEBUG_REMOVE) {
17245                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17246                        + nextUserId);
17247            }
17248
17249            destroyAppDataLIF(pkg, userId,
17250                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17251            destroyAppProfilesLIF(pkg, userId);
17252            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17253            schedulePackageCleaning(ps.name, nextUserId, false);
17254            synchronized (mPackages) {
17255                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17256                    scheduleWritePackageRestrictionsLocked(nextUserId);
17257                }
17258                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17259            }
17260        }
17261
17262        if (outInfo != null) {
17263            outInfo.removedPackage = ps.name;
17264            outInfo.removedAppId = ps.appId;
17265            outInfo.removedUsers = userIds;
17266        }
17267
17268        return true;
17269    }
17270
17271    private final class ClearStorageConnection implements ServiceConnection {
17272        IMediaContainerService mContainerService;
17273
17274        @Override
17275        public void onServiceConnected(ComponentName name, IBinder service) {
17276            synchronized (this) {
17277                mContainerService = IMediaContainerService.Stub
17278                        .asInterface(Binder.allowBlocking(service));
17279                notifyAll();
17280            }
17281        }
17282
17283        @Override
17284        public void onServiceDisconnected(ComponentName name) {
17285        }
17286    }
17287
17288    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17289        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17290
17291        final boolean mounted;
17292        if (Environment.isExternalStorageEmulated()) {
17293            mounted = true;
17294        } else {
17295            final String status = Environment.getExternalStorageState();
17296
17297            mounted = status.equals(Environment.MEDIA_MOUNTED)
17298                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17299        }
17300
17301        if (!mounted) {
17302            return;
17303        }
17304
17305        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17306        int[] users;
17307        if (userId == UserHandle.USER_ALL) {
17308            users = sUserManager.getUserIds();
17309        } else {
17310            users = new int[] { userId };
17311        }
17312        final ClearStorageConnection conn = new ClearStorageConnection();
17313        if (mContext.bindServiceAsUser(
17314                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17315            try {
17316                for (int curUser : users) {
17317                    long timeout = SystemClock.uptimeMillis() + 5000;
17318                    synchronized (conn) {
17319                        long now;
17320                        while (conn.mContainerService == null &&
17321                                (now = SystemClock.uptimeMillis()) < timeout) {
17322                            try {
17323                                conn.wait(timeout - now);
17324                            } catch (InterruptedException e) {
17325                            }
17326                        }
17327                    }
17328                    if (conn.mContainerService == null) {
17329                        return;
17330                    }
17331
17332                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17333                    clearDirectory(conn.mContainerService,
17334                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17335                    if (allData) {
17336                        clearDirectory(conn.mContainerService,
17337                                userEnv.buildExternalStorageAppDataDirs(packageName));
17338                        clearDirectory(conn.mContainerService,
17339                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17340                    }
17341                }
17342            } finally {
17343                mContext.unbindService(conn);
17344            }
17345        }
17346    }
17347
17348    @Override
17349    public void clearApplicationProfileData(String packageName) {
17350        enforceSystemOrRoot("Only the system can clear all profile data");
17351
17352        final PackageParser.Package pkg;
17353        synchronized (mPackages) {
17354            pkg = mPackages.get(packageName);
17355        }
17356
17357        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17358            synchronized (mInstallLock) {
17359                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17360                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17361                        true /* removeBaseMarker */);
17362            }
17363        }
17364    }
17365
17366    @Override
17367    public void clearApplicationUserData(final String packageName,
17368            final IPackageDataObserver observer, final int userId) {
17369        mContext.enforceCallingOrSelfPermission(
17370                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17371
17372        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17373                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17374
17375        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17376            throw new SecurityException("Cannot clear data for a protected package: "
17377                    + packageName);
17378        }
17379        // Queue up an async operation since the package deletion may take a little while.
17380        mHandler.post(new Runnable() {
17381            public void run() {
17382                mHandler.removeCallbacks(this);
17383                final boolean succeeded;
17384                try (PackageFreezer freezer = freezePackage(packageName,
17385                        "clearApplicationUserData")) {
17386                    synchronized (mInstallLock) {
17387                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17388                    }
17389                    clearExternalStorageDataSync(packageName, userId, true);
17390                }
17391                if (succeeded) {
17392                    // invoke DeviceStorageMonitor's update method to clear any notifications
17393                    DeviceStorageMonitorInternal dsm = LocalServices
17394                            .getService(DeviceStorageMonitorInternal.class);
17395                    if (dsm != null) {
17396                        dsm.checkMemory();
17397                    }
17398                }
17399                if(observer != null) {
17400                    try {
17401                        observer.onRemoveCompleted(packageName, succeeded);
17402                    } catch (RemoteException e) {
17403                        Log.i(TAG, "Observer no longer exists.");
17404                    }
17405                } //end if observer
17406            } //end run
17407        });
17408    }
17409
17410    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17411        if (packageName == null) {
17412            Slog.w(TAG, "Attempt to delete null packageName.");
17413            return false;
17414        }
17415
17416        // Try finding details about the requested package
17417        PackageParser.Package pkg;
17418        synchronized (mPackages) {
17419            pkg = mPackages.get(packageName);
17420            if (pkg == null) {
17421                final PackageSetting ps = mSettings.mPackages.get(packageName);
17422                if (ps != null) {
17423                    pkg = ps.pkg;
17424                }
17425            }
17426
17427            if (pkg == null) {
17428                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17429                return false;
17430            }
17431
17432            PackageSetting ps = (PackageSetting) pkg.mExtras;
17433            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17434        }
17435
17436        clearAppDataLIF(pkg, userId,
17437                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17438
17439        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17440        removeKeystoreDataIfNeeded(userId, appId);
17441
17442        UserManagerInternal umInternal = getUserManagerInternal();
17443        final int flags;
17444        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17445            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17446        } else if (umInternal.isUserRunning(userId)) {
17447            flags = StorageManager.FLAG_STORAGE_DE;
17448        } else {
17449            flags = 0;
17450        }
17451        prepareAppDataContentsLIF(pkg, userId, flags);
17452
17453        return true;
17454    }
17455
17456    /**
17457     * Reverts user permission state changes (permissions and flags) in
17458     * all packages for a given user.
17459     *
17460     * @param userId The device user for which to do a reset.
17461     */
17462    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17463        final int packageCount = mPackages.size();
17464        for (int i = 0; i < packageCount; i++) {
17465            PackageParser.Package pkg = mPackages.valueAt(i);
17466            PackageSetting ps = (PackageSetting) pkg.mExtras;
17467            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17468        }
17469    }
17470
17471    private void resetNetworkPolicies(int userId) {
17472        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17473    }
17474
17475    /**
17476     * Reverts user permission state changes (permissions and flags).
17477     *
17478     * @param ps The package for which to reset.
17479     * @param userId The device user for which to do a reset.
17480     */
17481    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17482            final PackageSetting ps, final int userId) {
17483        if (ps.pkg == null) {
17484            return;
17485        }
17486
17487        // These are flags that can change base on user actions.
17488        final int userSettableMask = FLAG_PERMISSION_USER_SET
17489                | FLAG_PERMISSION_USER_FIXED
17490                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17491                | FLAG_PERMISSION_REVIEW_REQUIRED;
17492
17493        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17494                | FLAG_PERMISSION_POLICY_FIXED;
17495
17496        boolean writeInstallPermissions = false;
17497        boolean writeRuntimePermissions = false;
17498
17499        final int permissionCount = ps.pkg.requestedPermissions.size();
17500        for (int i = 0; i < permissionCount; i++) {
17501            String permission = ps.pkg.requestedPermissions.get(i);
17502
17503            BasePermission bp = mSettings.mPermissions.get(permission);
17504            if (bp == null) {
17505                continue;
17506            }
17507
17508            // If shared user we just reset the state to which only this app contributed.
17509            if (ps.sharedUser != null) {
17510                boolean used = false;
17511                final int packageCount = ps.sharedUser.packages.size();
17512                for (int j = 0; j < packageCount; j++) {
17513                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17514                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17515                            && pkg.pkg.requestedPermissions.contains(permission)) {
17516                        used = true;
17517                        break;
17518                    }
17519                }
17520                if (used) {
17521                    continue;
17522                }
17523            }
17524
17525            PermissionsState permissionsState = ps.getPermissionsState();
17526
17527            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17528
17529            // Always clear the user settable flags.
17530            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17531                    bp.name) != null;
17532            // If permission review is enabled and this is a legacy app, mark the
17533            // permission as requiring a review as this is the initial state.
17534            int flags = 0;
17535            if (mPermissionReviewRequired
17536                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17537                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17538            }
17539            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17540                if (hasInstallState) {
17541                    writeInstallPermissions = true;
17542                } else {
17543                    writeRuntimePermissions = true;
17544                }
17545            }
17546
17547            // Below is only runtime permission handling.
17548            if (!bp.isRuntime()) {
17549                continue;
17550            }
17551
17552            // Never clobber system or policy.
17553            if ((oldFlags & policyOrSystemFlags) != 0) {
17554                continue;
17555            }
17556
17557            // If this permission was granted by default, make sure it is.
17558            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17559                if (permissionsState.grantRuntimePermission(bp, userId)
17560                        != PERMISSION_OPERATION_FAILURE) {
17561                    writeRuntimePermissions = true;
17562                }
17563            // If permission review is enabled the permissions for a legacy apps
17564            // are represented as constantly granted runtime ones, so don't revoke.
17565            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17566                // Otherwise, reset the permission.
17567                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17568                switch (revokeResult) {
17569                    case PERMISSION_OPERATION_SUCCESS:
17570                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17571                        writeRuntimePermissions = true;
17572                        final int appId = ps.appId;
17573                        mHandler.post(new Runnable() {
17574                            @Override
17575                            public void run() {
17576                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17577                            }
17578                        });
17579                    } break;
17580                }
17581            }
17582        }
17583
17584        // Synchronously write as we are taking permissions away.
17585        if (writeRuntimePermissions) {
17586            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17587        }
17588
17589        // Synchronously write as we are taking permissions away.
17590        if (writeInstallPermissions) {
17591            mSettings.writeLPr();
17592        }
17593    }
17594
17595    /**
17596     * Remove entries from the keystore daemon. Will only remove it if the
17597     * {@code appId} is valid.
17598     */
17599    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17600        if (appId < 0) {
17601            return;
17602        }
17603
17604        final KeyStore keyStore = KeyStore.getInstance();
17605        if (keyStore != null) {
17606            if (userId == UserHandle.USER_ALL) {
17607                for (final int individual : sUserManager.getUserIds()) {
17608                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17609                }
17610            } else {
17611                keyStore.clearUid(UserHandle.getUid(userId, appId));
17612            }
17613        } else {
17614            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17615        }
17616    }
17617
17618    @Override
17619    public void deleteApplicationCacheFiles(final String packageName,
17620            final IPackageDataObserver observer) {
17621        final int userId = UserHandle.getCallingUserId();
17622        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17623    }
17624
17625    @Override
17626    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17627            final IPackageDataObserver observer) {
17628        mContext.enforceCallingOrSelfPermission(
17629                android.Manifest.permission.DELETE_CACHE_FILES, null);
17630        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17631                /* requireFullPermission= */ true, /* checkShell= */ false,
17632                "delete application cache files");
17633
17634        final PackageParser.Package pkg;
17635        synchronized (mPackages) {
17636            pkg = mPackages.get(packageName);
17637        }
17638
17639        // Queue up an async operation since the package deletion may take a little while.
17640        mHandler.post(new Runnable() {
17641            public void run() {
17642                synchronized (mInstallLock) {
17643                    final int flags = StorageManager.FLAG_STORAGE_DE
17644                            | StorageManager.FLAG_STORAGE_CE;
17645                    // We're only clearing cache files, so we don't care if the
17646                    // app is unfrozen and still able to run
17647                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17648                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17649                }
17650                clearExternalStorageDataSync(packageName, userId, false);
17651                if (observer != null) {
17652                    try {
17653                        observer.onRemoveCompleted(packageName, true);
17654                    } catch (RemoteException e) {
17655                        Log.i(TAG, "Observer no longer exists.");
17656                    }
17657                }
17658            }
17659        });
17660    }
17661
17662    @Override
17663    public void getPackageSizeInfo(final String packageName, int userHandle,
17664            final IPackageStatsObserver observer) {
17665        mContext.enforceCallingOrSelfPermission(
17666                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17667        if (packageName == null) {
17668            throw new IllegalArgumentException("Attempt to get size of null packageName");
17669        }
17670
17671        PackageStats stats = new PackageStats(packageName, userHandle);
17672
17673        /*
17674         * Queue up an async operation since the package measurement may take a
17675         * little while.
17676         */
17677        Message msg = mHandler.obtainMessage(INIT_COPY);
17678        msg.obj = new MeasureParams(stats, observer);
17679        mHandler.sendMessage(msg);
17680    }
17681
17682    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17683        final PackageSetting ps;
17684        synchronized (mPackages) {
17685            ps = mSettings.mPackages.get(packageName);
17686            if (ps == null) {
17687                Slog.w(TAG, "Failed to find settings for " + packageName);
17688                return false;
17689            }
17690        }
17691
17692        final String[] packageNames = { packageName };
17693        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
17694        final String[] codePaths = { ps.codePathString };
17695
17696        try {
17697            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
17698                    ps.appId, ceDataInodes, codePaths, stats);
17699
17700            // For now, ignore code size of packages on system partition
17701            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17702                stats.codeSize = 0;
17703            }
17704
17705            // External clients expect these to be tracked separately
17706            stats.dataSize -= stats.cacheSize;
17707
17708        } catch (InstallerException e) {
17709            Slog.w(TAG, String.valueOf(e));
17710            return false;
17711        }
17712
17713        return true;
17714    }
17715
17716    private int getUidTargetSdkVersionLockedLPr(int uid) {
17717        Object obj = mSettings.getUserIdLPr(uid);
17718        if (obj instanceof SharedUserSetting) {
17719            final SharedUserSetting sus = (SharedUserSetting) obj;
17720            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17721            final Iterator<PackageSetting> it = sus.packages.iterator();
17722            while (it.hasNext()) {
17723                final PackageSetting ps = it.next();
17724                if (ps.pkg != null) {
17725                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17726                    if (v < vers) vers = v;
17727                }
17728            }
17729            return vers;
17730        } else if (obj instanceof PackageSetting) {
17731            final PackageSetting ps = (PackageSetting) obj;
17732            if (ps.pkg != null) {
17733                return ps.pkg.applicationInfo.targetSdkVersion;
17734            }
17735        }
17736        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17737    }
17738
17739    @Override
17740    public void addPreferredActivity(IntentFilter filter, int match,
17741            ComponentName[] set, ComponentName activity, int userId) {
17742        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17743                "Adding preferred");
17744    }
17745
17746    private void addPreferredActivityInternal(IntentFilter filter, int match,
17747            ComponentName[] set, ComponentName activity, boolean always, int userId,
17748            String opname) {
17749        // writer
17750        int callingUid = Binder.getCallingUid();
17751        enforceCrossUserPermission(callingUid, userId,
17752                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17753        if (filter.countActions() == 0) {
17754            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17755            return;
17756        }
17757        synchronized (mPackages) {
17758            if (mContext.checkCallingOrSelfPermission(
17759                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17760                    != PackageManager.PERMISSION_GRANTED) {
17761                if (getUidTargetSdkVersionLockedLPr(callingUid)
17762                        < Build.VERSION_CODES.FROYO) {
17763                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17764                            + callingUid);
17765                    return;
17766                }
17767                mContext.enforceCallingOrSelfPermission(
17768                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17769            }
17770
17771            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17772            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17773                    + userId + ":");
17774            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17775            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17776            scheduleWritePackageRestrictionsLocked(userId);
17777            postPreferredActivityChangedBroadcast(userId);
17778        }
17779    }
17780
17781    private void postPreferredActivityChangedBroadcast(int userId) {
17782        mHandler.post(() -> {
17783            final IActivityManager am = ActivityManager.getService();
17784            if (am == null) {
17785                return;
17786            }
17787
17788            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17789            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17790            try {
17791                am.broadcastIntent(null, intent, null, null,
17792                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17793                        null, false, false, userId);
17794            } catch (RemoteException e) {
17795            }
17796        });
17797    }
17798
17799    @Override
17800    public void replacePreferredActivity(IntentFilter filter, int match,
17801            ComponentName[] set, ComponentName activity, int userId) {
17802        if (filter.countActions() != 1) {
17803            throw new IllegalArgumentException(
17804                    "replacePreferredActivity expects filter to have only 1 action.");
17805        }
17806        if (filter.countDataAuthorities() != 0
17807                || filter.countDataPaths() != 0
17808                || filter.countDataSchemes() > 1
17809                || filter.countDataTypes() != 0) {
17810            throw new IllegalArgumentException(
17811                    "replacePreferredActivity expects filter to have no data authorities, " +
17812                    "paths, or types; and at most one scheme.");
17813        }
17814
17815        final int callingUid = Binder.getCallingUid();
17816        enforceCrossUserPermission(callingUid, userId,
17817                true /* requireFullPermission */, false /* checkShell */,
17818                "replace preferred activity");
17819        synchronized (mPackages) {
17820            if (mContext.checkCallingOrSelfPermission(
17821                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17822                    != PackageManager.PERMISSION_GRANTED) {
17823                if (getUidTargetSdkVersionLockedLPr(callingUid)
17824                        < Build.VERSION_CODES.FROYO) {
17825                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17826                            + Binder.getCallingUid());
17827                    return;
17828                }
17829                mContext.enforceCallingOrSelfPermission(
17830                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17831            }
17832
17833            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17834            if (pir != null) {
17835                // Get all of the existing entries that exactly match this filter.
17836                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17837                if (existing != null && existing.size() == 1) {
17838                    PreferredActivity cur = existing.get(0);
17839                    if (DEBUG_PREFERRED) {
17840                        Slog.i(TAG, "Checking replace of preferred:");
17841                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17842                        if (!cur.mPref.mAlways) {
17843                            Slog.i(TAG, "  -- CUR; not mAlways!");
17844                        } else {
17845                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17846                            Slog.i(TAG, "  -- CUR: mSet="
17847                                    + Arrays.toString(cur.mPref.mSetComponents));
17848                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17849                            Slog.i(TAG, "  -- NEW: mMatch="
17850                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17851                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17852                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17853                        }
17854                    }
17855                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17856                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17857                            && cur.mPref.sameSet(set)) {
17858                        // Setting the preferred activity to what it happens to be already
17859                        if (DEBUG_PREFERRED) {
17860                            Slog.i(TAG, "Replacing with same preferred activity "
17861                                    + cur.mPref.mShortComponent + " for user "
17862                                    + userId + ":");
17863                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17864                        }
17865                        return;
17866                    }
17867                }
17868
17869                if (existing != null) {
17870                    if (DEBUG_PREFERRED) {
17871                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17872                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17873                    }
17874                    for (int i = 0; i < existing.size(); i++) {
17875                        PreferredActivity pa = existing.get(i);
17876                        if (DEBUG_PREFERRED) {
17877                            Slog.i(TAG, "Removing existing preferred activity "
17878                                    + pa.mPref.mComponent + ":");
17879                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17880                        }
17881                        pir.removeFilter(pa);
17882                    }
17883                }
17884            }
17885            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17886                    "Replacing preferred");
17887        }
17888    }
17889
17890    @Override
17891    public void clearPackagePreferredActivities(String packageName) {
17892        final int uid = Binder.getCallingUid();
17893        // writer
17894        synchronized (mPackages) {
17895            PackageParser.Package pkg = mPackages.get(packageName);
17896            if (pkg == null || pkg.applicationInfo.uid != uid) {
17897                if (mContext.checkCallingOrSelfPermission(
17898                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17899                        != PackageManager.PERMISSION_GRANTED) {
17900                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17901                            < Build.VERSION_CODES.FROYO) {
17902                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17903                                + Binder.getCallingUid());
17904                        return;
17905                    }
17906                    mContext.enforceCallingOrSelfPermission(
17907                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17908                }
17909            }
17910
17911            int user = UserHandle.getCallingUserId();
17912            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17913                scheduleWritePackageRestrictionsLocked(user);
17914            }
17915        }
17916    }
17917
17918    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17919    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17920        ArrayList<PreferredActivity> removed = null;
17921        boolean changed = false;
17922        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17923            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17924            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17925            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17926                continue;
17927            }
17928            Iterator<PreferredActivity> it = pir.filterIterator();
17929            while (it.hasNext()) {
17930                PreferredActivity pa = it.next();
17931                // Mark entry for removal only if it matches the package name
17932                // and the entry is of type "always".
17933                if (packageName == null ||
17934                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17935                                && pa.mPref.mAlways)) {
17936                    if (removed == null) {
17937                        removed = new ArrayList<PreferredActivity>();
17938                    }
17939                    removed.add(pa);
17940                }
17941            }
17942            if (removed != null) {
17943                for (int j=0; j<removed.size(); j++) {
17944                    PreferredActivity pa = removed.get(j);
17945                    pir.removeFilter(pa);
17946                }
17947                changed = true;
17948            }
17949        }
17950        if (changed) {
17951            postPreferredActivityChangedBroadcast(userId);
17952        }
17953        return changed;
17954    }
17955
17956    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17957    private void clearIntentFilterVerificationsLPw(int userId) {
17958        final int packageCount = mPackages.size();
17959        for (int i = 0; i < packageCount; i++) {
17960            PackageParser.Package pkg = mPackages.valueAt(i);
17961            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17962        }
17963    }
17964
17965    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17966    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17967        if (userId == UserHandle.USER_ALL) {
17968            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17969                    sUserManager.getUserIds())) {
17970                for (int oneUserId : sUserManager.getUserIds()) {
17971                    scheduleWritePackageRestrictionsLocked(oneUserId);
17972                }
17973            }
17974        } else {
17975            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17976                scheduleWritePackageRestrictionsLocked(userId);
17977            }
17978        }
17979    }
17980
17981    void clearDefaultBrowserIfNeeded(String packageName) {
17982        for (int oneUserId : sUserManager.getUserIds()) {
17983            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17984            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17985            if (packageName.equals(defaultBrowserPackageName)) {
17986                setDefaultBrowserPackageName(null, oneUserId);
17987            }
17988        }
17989    }
17990
17991    @Override
17992    public void resetApplicationPreferences(int userId) {
17993        mContext.enforceCallingOrSelfPermission(
17994                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17995        final long identity = Binder.clearCallingIdentity();
17996        // writer
17997        try {
17998            synchronized (mPackages) {
17999                clearPackagePreferredActivitiesLPw(null, userId);
18000                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18001                // TODO: We have to reset the default SMS and Phone. This requires
18002                // significant refactoring to keep all default apps in the package
18003                // manager (cleaner but more work) or have the services provide
18004                // callbacks to the package manager to request a default app reset.
18005                applyFactoryDefaultBrowserLPw(userId);
18006                clearIntentFilterVerificationsLPw(userId);
18007                primeDomainVerificationsLPw(userId);
18008                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18009                scheduleWritePackageRestrictionsLocked(userId);
18010            }
18011            resetNetworkPolicies(userId);
18012        } finally {
18013            Binder.restoreCallingIdentity(identity);
18014        }
18015    }
18016
18017    @Override
18018    public int getPreferredActivities(List<IntentFilter> outFilters,
18019            List<ComponentName> outActivities, String packageName) {
18020
18021        int num = 0;
18022        final int userId = UserHandle.getCallingUserId();
18023        // reader
18024        synchronized (mPackages) {
18025            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18026            if (pir != null) {
18027                final Iterator<PreferredActivity> it = pir.filterIterator();
18028                while (it.hasNext()) {
18029                    final PreferredActivity pa = it.next();
18030                    if (packageName == null
18031                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18032                                    && pa.mPref.mAlways)) {
18033                        if (outFilters != null) {
18034                            outFilters.add(new IntentFilter(pa));
18035                        }
18036                        if (outActivities != null) {
18037                            outActivities.add(pa.mPref.mComponent);
18038                        }
18039                    }
18040                }
18041            }
18042        }
18043
18044        return num;
18045    }
18046
18047    @Override
18048    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18049            int userId) {
18050        int callingUid = Binder.getCallingUid();
18051        if (callingUid != Process.SYSTEM_UID) {
18052            throw new SecurityException(
18053                    "addPersistentPreferredActivity can only be run by the system");
18054        }
18055        if (filter.countActions() == 0) {
18056            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18057            return;
18058        }
18059        synchronized (mPackages) {
18060            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18061                    ":");
18062            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18063            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18064                    new PersistentPreferredActivity(filter, activity));
18065            scheduleWritePackageRestrictionsLocked(userId);
18066            postPreferredActivityChangedBroadcast(userId);
18067        }
18068    }
18069
18070    @Override
18071    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18072        int callingUid = Binder.getCallingUid();
18073        if (callingUid != Process.SYSTEM_UID) {
18074            throw new SecurityException(
18075                    "clearPackagePersistentPreferredActivities can only be run by the system");
18076        }
18077        ArrayList<PersistentPreferredActivity> removed = null;
18078        boolean changed = false;
18079        synchronized (mPackages) {
18080            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18081                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18082                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18083                        .valueAt(i);
18084                if (userId != thisUserId) {
18085                    continue;
18086                }
18087                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18088                while (it.hasNext()) {
18089                    PersistentPreferredActivity ppa = it.next();
18090                    // Mark entry for removal only if it matches the package name.
18091                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18092                        if (removed == null) {
18093                            removed = new ArrayList<PersistentPreferredActivity>();
18094                        }
18095                        removed.add(ppa);
18096                    }
18097                }
18098                if (removed != null) {
18099                    for (int j=0; j<removed.size(); j++) {
18100                        PersistentPreferredActivity ppa = removed.get(j);
18101                        ppir.removeFilter(ppa);
18102                    }
18103                    changed = true;
18104                }
18105            }
18106
18107            if (changed) {
18108                scheduleWritePackageRestrictionsLocked(userId);
18109                postPreferredActivityChangedBroadcast(userId);
18110            }
18111        }
18112    }
18113
18114    /**
18115     * Common machinery for picking apart a restored XML blob and passing
18116     * it to a caller-supplied functor to be applied to the running system.
18117     */
18118    private void restoreFromXml(XmlPullParser parser, int userId,
18119            String expectedStartTag, BlobXmlRestorer functor)
18120            throws IOException, XmlPullParserException {
18121        int type;
18122        while ((type = parser.next()) != XmlPullParser.START_TAG
18123                && type != XmlPullParser.END_DOCUMENT) {
18124        }
18125        if (type != XmlPullParser.START_TAG) {
18126            // oops didn't find a start tag?!
18127            if (DEBUG_BACKUP) {
18128                Slog.e(TAG, "Didn't find start tag during restore");
18129            }
18130            return;
18131        }
18132Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18133        // this is supposed to be TAG_PREFERRED_BACKUP
18134        if (!expectedStartTag.equals(parser.getName())) {
18135            if (DEBUG_BACKUP) {
18136                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18137            }
18138            return;
18139        }
18140
18141        // skip interfering stuff, then we're aligned with the backing implementation
18142        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18143Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18144        functor.apply(parser, userId);
18145    }
18146
18147    private interface BlobXmlRestorer {
18148        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18149    }
18150
18151    /**
18152     * Non-Binder method, support for the backup/restore mechanism: write the
18153     * full set of preferred activities in its canonical XML format.  Returns the
18154     * XML output as a byte array, or null if there is none.
18155     */
18156    @Override
18157    public byte[] getPreferredActivityBackup(int userId) {
18158        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18159            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18160        }
18161
18162        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18163        try {
18164            final XmlSerializer serializer = new FastXmlSerializer();
18165            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18166            serializer.startDocument(null, true);
18167            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18168
18169            synchronized (mPackages) {
18170                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18171            }
18172
18173            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18174            serializer.endDocument();
18175            serializer.flush();
18176        } catch (Exception e) {
18177            if (DEBUG_BACKUP) {
18178                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18179            }
18180            return null;
18181        }
18182
18183        return dataStream.toByteArray();
18184    }
18185
18186    @Override
18187    public void restorePreferredActivities(byte[] backup, int userId) {
18188        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18189            throw new SecurityException("Only the system may call restorePreferredActivities()");
18190        }
18191
18192        try {
18193            final XmlPullParser parser = Xml.newPullParser();
18194            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18195            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18196                    new BlobXmlRestorer() {
18197                        @Override
18198                        public void apply(XmlPullParser parser, int userId)
18199                                throws XmlPullParserException, IOException {
18200                            synchronized (mPackages) {
18201                                mSettings.readPreferredActivitiesLPw(parser, userId);
18202                            }
18203                        }
18204                    } );
18205        } catch (Exception e) {
18206            if (DEBUG_BACKUP) {
18207                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18208            }
18209        }
18210    }
18211
18212    /**
18213     * Non-Binder method, support for the backup/restore mechanism: write the
18214     * default browser (etc) settings in its canonical XML format.  Returns the default
18215     * browser XML representation as a byte array, or null if there is none.
18216     */
18217    @Override
18218    public byte[] getDefaultAppsBackup(int userId) {
18219        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18220            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18221        }
18222
18223        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18224        try {
18225            final XmlSerializer serializer = new FastXmlSerializer();
18226            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18227            serializer.startDocument(null, true);
18228            serializer.startTag(null, TAG_DEFAULT_APPS);
18229
18230            synchronized (mPackages) {
18231                mSettings.writeDefaultAppsLPr(serializer, userId);
18232            }
18233
18234            serializer.endTag(null, TAG_DEFAULT_APPS);
18235            serializer.endDocument();
18236            serializer.flush();
18237        } catch (Exception e) {
18238            if (DEBUG_BACKUP) {
18239                Slog.e(TAG, "Unable to write default apps for backup", e);
18240            }
18241            return null;
18242        }
18243
18244        return dataStream.toByteArray();
18245    }
18246
18247    @Override
18248    public void restoreDefaultApps(byte[] backup, int userId) {
18249        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18250            throw new SecurityException("Only the system may call restoreDefaultApps()");
18251        }
18252
18253        try {
18254            final XmlPullParser parser = Xml.newPullParser();
18255            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18256            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18257                    new BlobXmlRestorer() {
18258                        @Override
18259                        public void apply(XmlPullParser parser, int userId)
18260                                throws XmlPullParserException, IOException {
18261                            synchronized (mPackages) {
18262                                mSettings.readDefaultAppsLPw(parser, userId);
18263                            }
18264                        }
18265                    } );
18266        } catch (Exception e) {
18267            if (DEBUG_BACKUP) {
18268                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18269            }
18270        }
18271    }
18272
18273    @Override
18274    public byte[] getIntentFilterVerificationBackup(int userId) {
18275        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18276            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18277        }
18278
18279        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18280        try {
18281            final XmlSerializer serializer = new FastXmlSerializer();
18282            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18283            serializer.startDocument(null, true);
18284            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18285
18286            synchronized (mPackages) {
18287                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18288            }
18289
18290            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18291            serializer.endDocument();
18292            serializer.flush();
18293        } catch (Exception e) {
18294            if (DEBUG_BACKUP) {
18295                Slog.e(TAG, "Unable to write default apps for backup", e);
18296            }
18297            return null;
18298        }
18299
18300        return dataStream.toByteArray();
18301    }
18302
18303    @Override
18304    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18305        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18306            throw new SecurityException("Only the system may call restorePreferredActivities()");
18307        }
18308
18309        try {
18310            final XmlPullParser parser = Xml.newPullParser();
18311            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18312            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18313                    new BlobXmlRestorer() {
18314                        @Override
18315                        public void apply(XmlPullParser parser, int userId)
18316                                throws XmlPullParserException, IOException {
18317                            synchronized (mPackages) {
18318                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18319                                mSettings.writeLPr();
18320                            }
18321                        }
18322                    } );
18323        } catch (Exception e) {
18324            if (DEBUG_BACKUP) {
18325                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18326            }
18327        }
18328    }
18329
18330    @Override
18331    public byte[] getPermissionGrantBackup(int userId) {
18332        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18333            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18334        }
18335
18336        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18337        try {
18338            final XmlSerializer serializer = new FastXmlSerializer();
18339            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18340            serializer.startDocument(null, true);
18341            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18342
18343            synchronized (mPackages) {
18344                serializeRuntimePermissionGrantsLPr(serializer, userId);
18345            }
18346
18347            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18348            serializer.endDocument();
18349            serializer.flush();
18350        } catch (Exception e) {
18351            if (DEBUG_BACKUP) {
18352                Slog.e(TAG, "Unable to write default apps for backup", e);
18353            }
18354            return null;
18355        }
18356
18357        return dataStream.toByteArray();
18358    }
18359
18360    @Override
18361    public void restorePermissionGrants(byte[] backup, int userId) {
18362        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18363            throw new SecurityException("Only the system may call restorePermissionGrants()");
18364        }
18365
18366        try {
18367            final XmlPullParser parser = Xml.newPullParser();
18368            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18369            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18370                    new BlobXmlRestorer() {
18371                        @Override
18372                        public void apply(XmlPullParser parser, int userId)
18373                                throws XmlPullParserException, IOException {
18374                            synchronized (mPackages) {
18375                                processRestoredPermissionGrantsLPr(parser, userId);
18376                            }
18377                        }
18378                    } );
18379        } catch (Exception e) {
18380            if (DEBUG_BACKUP) {
18381                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18382            }
18383        }
18384    }
18385
18386    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18387            throws IOException {
18388        serializer.startTag(null, TAG_ALL_GRANTS);
18389
18390        final int N = mSettings.mPackages.size();
18391        for (int i = 0; i < N; i++) {
18392            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18393            boolean pkgGrantsKnown = false;
18394
18395            PermissionsState packagePerms = ps.getPermissionsState();
18396
18397            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18398                final int grantFlags = state.getFlags();
18399                // only look at grants that are not system/policy fixed
18400                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18401                    final boolean isGranted = state.isGranted();
18402                    // And only back up the user-twiddled state bits
18403                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18404                        final String packageName = mSettings.mPackages.keyAt(i);
18405                        if (!pkgGrantsKnown) {
18406                            serializer.startTag(null, TAG_GRANT);
18407                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18408                            pkgGrantsKnown = true;
18409                        }
18410
18411                        final boolean userSet =
18412                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18413                        final boolean userFixed =
18414                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18415                        final boolean revoke =
18416                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18417
18418                        serializer.startTag(null, TAG_PERMISSION);
18419                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18420                        if (isGranted) {
18421                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18422                        }
18423                        if (userSet) {
18424                            serializer.attribute(null, ATTR_USER_SET, "true");
18425                        }
18426                        if (userFixed) {
18427                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18428                        }
18429                        if (revoke) {
18430                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18431                        }
18432                        serializer.endTag(null, TAG_PERMISSION);
18433                    }
18434                }
18435            }
18436
18437            if (pkgGrantsKnown) {
18438                serializer.endTag(null, TAG_GRANT);
18439            }
18440        }
18441
18442        serializer.endTag(null, TAG_ALL_GRANTS);
18443    }
18444
18445    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18446            throws XmlPullParserException, IOException {
18447        String pkgName = null;
18448        int outerDepth = parser.getDepth();
18449        int type;
18450        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18451                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18452            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18453                continue;
18454            }
18455
18456            final String tagName = parser.getName();
18457            if (tagName.equals(TAG_GRANT)) {
18458                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18459                if (DEBUG_BACKUP) {
18460                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18461                }
18462            } else if (tagName.equals(TAG_PERMISSION)) {
18463
18464                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18465                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18466
18467                int newFlagSet = 0;
18468                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18469                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18470                }
18471                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18472                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18473                }
18474                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18475                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18476                }
18477                if (DEBUG_BACKUP) {
18478                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18479                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18480                }
18481                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18482                if (ps != null) {
18483                    // Already installed so we apply the grant immediately
18484                    if (DEBUG_BACKUP) {
18485                        Slog.v(TAG, "        + already installed; applying");
18486                    }
18487                    PermissionsState perms = ps.getPermissionsState();
18488                    BasePermission bp = mSettings.mPermissions.get(permName);
18489                    if (bp != null) {
18490                        if (isGranted) {
18491                            perms.grantRuntimePermission(bp, userId);
18492                        }
18493                        if (newFlagSet != 0) {
18494                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18495                        }
18496                    }
18497                } else {
18498                    // Need to wait for post-restore install to apply the grant
18499                    if (DEBUG_BACKUP) {
18500                        Slog.v(TAG, "        - not yet installed; saving for later");
18501                    }
18502                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18503                            isGranted, newFlagSet, userId);
18504                }
18505            } else {
18506                PackageManagerService.reportSettingsProblem(Log.WARN,
18507                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18508                XmlUtils.skipCurrentTag(parser);
18509            }
18510        }
18511
18512        scheduleWriteSettingsLocked();
18513        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18514    }
18515
18516    @Override
18517    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18518            int sourceUserId, int targetUserId, int flags) {
18519        mContext.enforceCallingOrSelfPermission(
18520                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18521        int callingUid = Binder.getCallingUid();
18522        enforceOwnerRights(ownerPackage, callingUid);
18523        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18524        if (intentFilter.countActions() == 0) {
18525            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18526            return;
18527        }
18528        synchronized (mPackages) {
18529            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18530                    ownerPackage, targetUserId, flags);
18531            CrossProfileIntentResolver resolver =
18532                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18533            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18534            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18535            if (existing != null) {
18536                int size = existing.size();
18537                for (int i = 0; i < size; i++) {
18538                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18539                        return;
18540                    }
18541                }
18542            }
18543            resolver.addFilter(newFilter);
18544            scheduleWritePackageRestrictionsLocked(sourceUserId);
18545        }
18546    }
18547
18548    @Override
18549    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18550        mContext.enforceCallingOrSelfPermission(
18551                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18552        int callingUid = Binder.getCallingUid();
18553        enforceOwnerRights(ownerPackage, callingUid);
18554        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18555        synchronized (mPackages) {
18556            CrossProfileIntentResolver resolver =
18557                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18558            ArraySet<CrossProfileIntentFilter> set =
18559                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18560            for (CrossProfileIntentFilter filter : set) {
18561                if (filter.getOwnerPackage().equals(ownerPackage)) {
18562                    resolver.removeFilter(filter);
18563                }
18564            }
18565            scheduleWritePackageRestrictionsLocked(sourceUserId);
18566        }
18567    }
18568
18569    // Enforcing that callingUid is owning pkg on userId
18570    private void enforceOwnerRights(String pkg, int callingUid) {
18571        // The system owns everything.
18572        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18573            return;
18574        }
18575        int callingUserId = UserHandle.getUserId(callingUid);
18576        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18577        if (pi == null) {
18578            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18579                    + callingUserId);
18580        }
18581        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18582            throw new SecurityException("Calling uid " + callingUid
18583                    + " does not own package " + pkg);
18584        }
18585    }
18586
18587    @Override
18588    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18589        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18590    }
18591
18592    private Intent getHomeIntent() {
18593        Intent intent = new Intent(Intent.ACTION_MAIN);
18594        intent.addCategory(Intent.CATEGORY_HOME);
18595        intent.addCategory(Intent.CATEGORY_DEFAULT);
18596        return intent;
18597    }
18598
18599    private IntentFilter getHomeFilter() {
18600        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18601        filter.addCategory(Intent.CATEGORY_HOME);
18602        filter.addCategory(Intent.CATEGORY_DEFAULT);
18603        return filter;
18604    }
18605
18606    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18607            int userId) {
18608        Intent intent  = getHomeIntent();
18609        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18610                PackageManager.GET_META_DATA, userId);
18611        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18612                true, false, false, userId);
18613
18614        allHomeCandidates.clear();
18615        if (list != null) {
18616            for (ResolveInfo ri : list) {
18617                allHomeCandidates.add(ri);
18618            }
18619        }
18620        return (preferred == null || preferred.activityInfo == null)
18621                ? null
18622                : new ComponentName(preferred.activityInfo.packageName,
18623                        preferred.activityInfo.name);
18624    }
18625
18626    @Override
18627    public void setHomeActivity(ComponentName comp, int userId) {
18628        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18629        getHomeActivitiesAsUser(homeActivities, userId);
18630
18631        boolean found = false;
18632
18633        final int size = homeActivities.size();
18634        final ComponentName[] set = new ComponentName[size];
18635        for (int i = 0; i < size; i++) {
18636            final ResolveInfo candidate = homeActivities.get(i);
18637            final ActivityInfo info = candidate.activityInfo;
18638            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18639            set[i] = activityName;
18640            if (!found && activityName.equals(comp)) {
18641                found = true;
18642            }
18643        }
18644        if (!found) {
18645            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18646                    + userId);
18647        }
18648        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18649                set, comp, userId);
18650    }
18651
18652    private @Nullable String getSetupWizardPackageName() {
18653        final Intent intent = new Intent(Intent.ACTION_MAIN);
18654        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18655
18656        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18657                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18658                        | MATCH_DISABLED_COMPONENTS,
18659                UserHandle.myUserId());
18660        if (matches.size() == 1) {
18661            return matches.get(0).getComponentInfo().packageName;
18662        } else {
18663            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18664                    + ": matches=" + matches);
18665            return null;
18666        }
18667    }
18668
18669    private @Nullable String getStorageManagerPackageName() {
18670        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18671
18672        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18673                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18674                        | MATCH_DISABLED_COMPONENTS,
18675                UserHandle.myUserId());
18676        if (matches.size() == 1) {
18677            return matches.get(0).getComponentInfo().packageName;
18678        } else {
18679            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18680                    + matches.size() + ": matches=" + matches);
18681            return null;
18682        }
18683    }
18684
18685    @Override
18686    public void setApplicationEnabledSetting(String appPackageName,
18687            int newState, int flags, int userId, String callingPackage) {
18688        if (!sUserManager.exists(userId)) return;
18689        if (callingPackage == null) {
18690            callingPackage = Integer.toString(Binder.getCallingUid());
18691        }
18692        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18693    }
18694
18695    @Override
18696    public void setComponentEnabledSetting(ComponentName componentName,
18697            int newState, int flags, int userId) {
18698        if (!sUserManager.exists(userId)) return;
18699        setEnabledSetting(componentName.getPackageName(),
18700                componentName.getClassName(), newState, flags, userId, null);
18701    }
18702
18703    private void setEnabledSetting(final String packageName, String className, int newState,
18704            final int flags, int userId, String callingPackage) {
18705        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18706              || newState == COMPONENT_ENABLED_STATE_ENABLED
18707              || newState == COMPONENT_ENABLED_STATE_DISABLED
18708              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18709              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18710            throw new IllegalArgumentException("Invalid new component state: "
18711                    + newState);
18712        }
18713        PackageSetting pkgSetting;
18714        final int uid = Binder.getCallingUid();
18715        final int permission;
18716        if (uid == Process.SYSTEM_UID) {
18717            permission = PackageManager.PERMISSION_GRANTED;
18718        } else {
18719            permission = mContext.checkCallingOrSelfPermission(
18720                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18721        }
18722        enforceCrossUserPermission(uid, userId,
18723                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18724        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18725        boolean sendNow = false;
18726        boolean isApp = (className == null);
18727        String componentName = isApp ? packageName : className;
18728        int packageUid = -1;
18729        ArrayList<String> components;
18730
18731        // writer
18732        synchronized (mPackages) {
18733            pkgSetting = mSettings.mPackages.get(packageName);
18734            if (pkgSetting == null) {
18735                if (className == null) {
18736                    throw new IllegalArgumentException("Unknown package: " + packageName);
18737                }
18738                throw new IllegalArgumentException(
18739                        "Unknown component: " + packageName + "/" + className);
18740            }
18741        }
18742
18743        // Limit who can change which apps
18744        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18745            // Don't allow apps that don't have permission to modify other apps
18746            if (!allowedByPermission) {
18747                throw new SecurityException(
18748                        "Permission Denial: attempt to change component state from pid="
18749                        + Binder.getCallingPid()
18750                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18751            }
18752            // Don't allow changing protected packages.
18753            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18754                throw new SecurityException("Cannot disable a protected package: " + packageName);
18755            }
18756        }
18757
18758        synchronized (mPackages) {
18759            if (uid == Process.SHELL_UID
18760                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18761                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18762                // unless it is a test package.
18763                int oldState = pkgSetting.getEnabled(userId);
18764                if (className == null
18765                    &&
18766                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18767                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18768                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18769                    &&
18770                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18771                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18772                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18773                    // ok
18774                } else {
18775                    throw new SecurityException(
18776                            "Shell cannot change component state for " + packageName + "/"
18777                            + className + " to " + newState);
18778                }
18779            }
18780            if (className == null) {
18781                // We're dealing with an application/package level state change
18782                if (pkgSetting.getEnabled(userId) == newState) {
18783                    // Nothing to do
18784                    return;
18785                }
18786                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18787                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18788                    // Don't care about who enables an app.
18789                    callingPackage = null;
18790                }
18791                pkgSetting.setEnabled(newState, userId, callingPackage);
18792                // pkgSetting.pkg.mSetEnabled = newState;
18793            } else {
18794                // We're dealing with a component level state change
18795                // First, verify that this is a valid class name.
18796                PackageParser.Package pkg = pkgSetting.pkg;
18797                if (pkg == null || !pkg.hasComponentClassName(className)) {
18798                    if (pkg != null &&
18799                            pkg.applicationInfo.targetSdkVersion >=
18800                                    Build.VERSION_CODES.JELLY_BEAN) {
18801                        throw new IllegalArgumentException("Component class " + className
18802                                + " does not exist in " + packageName);
18803                    } else {
18804                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18805                                + className + " does not exist in " + packageName);
18806                    }
18807                }
18808                switch (newState) {
18809                case COMPONENT_ENABLED_STATE_ENABLED:
18810                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18811                        return;
18812                    }
18813                    break;
18814                case COMPONENT_ENABLED_STATE_DISABLED:
18815                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18816                        return;
18817                    }
18818                    break;
18819                case COMPONENT_ENABLED_STATE_DEFAULT:
18820                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18821                        return;
18822                    }
18823                    break;
18824                default:
18825                    Slog.e(TAG, "Invalid new component state: " + newState);
18826                    return;
18827                }
18828            }
18829            scheduleWritePackageRestrictionsLocked(userId);
18830            components = mPendingBroadcasts.get(userId, packageName);
18831            final boolean newPackage = components == null;
18832            if (newPackage) {
18833                components = new ArrayList<String>();
18834            }
18835            if (!components.contains(componentName)) {
18836                components.add(componentName);
18837            }
18838            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18839                sendNow = true;
18840                // Purge entry from pending broadcast list if another one exists already
18841                // since we are sending one right away.
18842                mPendingBroadcasts.remove(userId, packageName);
18843            } else {
18844                if (newPackage) {
18845                    mPendingBroadcasts.put(userId, packageName, components);
18846                }
18847                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18848                    // Schedule a message
18849                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18850                }
18851            }
18852        }
18853
18854        long callingId = Binder.clearCallingIdentity();
18855        try {
18856            if (sendNow) {
18857                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18858                sendPackageChangedBroadcast(packageName,
18859                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18860            }
18861        } finally {
18862            Binder.restoreCallingIdentity(callingId);
18863        }
18864    }
18865
18866    @Override
18867    public void flushPackageRestrictionsAsUser(int userId) {
18868        if (!sUserManager.exists(userId)) {
18869            return;
18870        }
18871        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18872                false /* checkShell */, "flushPackageRestrictions");
18873        synchronized (mPackages) {
18874            mSettings.writePackageRestrictionsLPr(userId);
18875            mDirtyUsers.remove(userId);
18876            if (mDirtyUsers.isEmpty()) {
18877                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18878            }
18879        }
18880    }
18881
18882    private void sendPackageChangedBroadcast(String packageName,
18883            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18884        if (DEBUG_INSTALL)
18885            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18886                    + componentNames);
18887        Bundle extras = new Bundle(4);
18888        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18889        String nameList[] = new String[componentNames.size()];
18890        componentNames.toArray(nameList);
18891        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18892        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18893        extras.putInt(Intent.EXTRA_UID, packageUid);
18894        // If this is not reporting a change of the overall package, then only send it
18895        // to registered receivers.  We don't want to launch a swath of apps for every
18896        // little component state change.
18897        final int flags = !componentNames.contains(packageName)
18898                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18899        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18900                new int[] {UserHandle.getUserId(packageUid)});
18901    }
18902
18903    @Override
18904    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18905        if (!sUserManager.exists(userId)) return;
18906        final int uid = Binder.getCallingUid();
18907        final int permission = mContext.checkCallingOrSelfPermission(
18908                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18909        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18910        enforceCrossUserPermission(uid, userId,
18911                true /* requireFullPermission */, true /* checkShell */, "stop package");
18912        // writer
18913        synchronized (mPackages) {
18914            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18915                    allowedByPermission, uid, userId)) {
18916                scheduleWritePackageRestrictionsLocked(userId);
18917            }
18918        }
18919    }
18920
18921    @Override
18922    public String getInstallerPackageName(String packageName) {
18923        // reader
18924        synchronized (mPackages) {
18925            return mSettings.getInstallerPackageNameLPr(packageName);
18926        }
18927    }
18928
18929    public boolean isOrphaned(String packageName) {
18930        // reader
18931        synchronized (mPackages) {
18932            return mSettings.isOrphaned(packageName);
18933        }
18934    }
18935
18936    @Override
18937    public int getApplicationEnabledSetting(String packageName, int userId) {
18938        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18939        int uid = Binder.getCallingUid();
18940        enforceCrossUserPermission(uid, userId,
18941                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18942        // reader
18943        synchronized (mPackages) {
18944            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18945        }
18946    }
18947
18948    @Override
18949    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18950        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18951        int uid = Binder.getCallingUid();
18952        enforceCrossUserPermission(uid, userId,
18953                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18954        // reader
18955        synchronized (mPackages) {
18956            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18957        }
18958    }
18959
18960    @Override
18961    public void enterSafeMode() {
18962        enforceSystemOrRoot("Only the system can request entering safe mode");
18963
18964        if (!mSystemReady) {
18965            mSafeMode = true;
18966        }
18967    }
18968
18969    @Override
18970    public void systemReady() {
18971        mSystemReady = true;
18972
18973        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18974        // disabled after already being started.
18975        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18976                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18977
18978        // Read the compatibilty setting when the system is ready.
18979        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18980                mContext.getContentResolver(),
18981                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18982        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18983        if (DEBUG_SETTINGS) {
18984            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18985        }
18986
18987        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18988
18989        synchronized (mPackages) {
18990            // Verify that all of the preferred activity components actually
18991            // exist.  It is possible for applications to be updated and at
18992            // that point remove a previously declared activity component that
18993            // had been set as a preferred activity.  We try to clean this up
18994            // the next time we encounter that preferred activity, but it is
18995            // possible for the user flow to never be able to return to that
18996            // situation so here we do a sanity check to make sure we haven't
18997            // left any junk around.
18998            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18999            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19000                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19001                removed.clear();
19002                for (PreferredActivity pa : pir.filterSet()) {
19003                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19004                        removed.add(pa);
19005                    }
19006                }
19007                if (removed.size() > 0) {
19008                    for (int r=0; r<removed.size(); r++) {
19009                        PreferredActivity pa = removed.get(r);
19010                        Slog.w(TAG, "Removing dangling preferred activity: "
19011                                + pa.mPref.mComponent);
19012                        pir.removeFilter(pa);
19013                    }
19014                    mSettings.writePackageRestrictionsLPr(
19015                            mSettings.mPreferredActivities.keyAt(i));
19016                }
19017            }
19018
19019            for (int userId : UserManagerService.getInstance().getUserIds()) {
19020                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19021                    grantPermissionsUserIds = ArrayUtils.appendInt(
19022                            grantPermissionsUserIds, userId);
19023                }
19024            }
19025        }
19026        sUserManager.systemReady();
19027
19028        // If we upgraded grant all default permissions before kicking off.
19029        for (int userId : grantPermissionsUserIds) {
19030            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19031        }
19032
19033        // If we did not grant default permissions, we preload from this the
19034        // default permission exceptions lazily to ensure we don't hit the
19035        // disk on a new user creation.
19036        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19037            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19038        }
19039
19040        // Kick off any messages waiting for system ready
19041        if (mPostSystemReadyMessages != null) {
19042            for (Message msg : mPostSystemReadyMessages) {
19043                msg.sendToTarget();
19044            }
19045            mPostSystemReadyMessages = null;
19046        }
19047
19048        // Watch for external volumes that come and go over time
19049        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19050        storage.registerListener(mStorageListener);
19051
19052        mInstallerService.systemReady();
19053        mPackageDexOptimizer.systemReady();
19054
19055        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19056                StorageManagerInternal.class);
19057        StorageManagerInternal.addExternalStoragePolicy(
19058                new StorageManagerInternal.ExternalStorageMountPolicy() {
19059            @Override
19060            public int getMountMode(int uid, String packageName) {
19061                if (Process.isIsolated(uid)) {
19062                    return Zygote.MOUNT_EXTERNAL_NONE;
19063                }
19064                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19065                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19066                }
19067                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19068                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19069                }
19070                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19071                    return Zygote.MOUNT_EXTERNAL_READ;
19072                }
19073                return Zygote.MOUNT_EXTERNAL_WRITE;
19074            }
19075
19076            @Override
19077            public boolean hasExternalStorage(int uid, String packageName) {
19078                return true;
19079            }
19080        });
19081
19082        // Now that we're mostly running, clean up stale users and apps
19083        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19084        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19085    }
19086
19087    @Override
19088    public boolean isSafeMode() {
19089        return mSafeMode;
19090    }
19091
19092    @Override
19093    public boolean hasSystemUidErrors() {
19094        return mHasSystemUidErrors;
19095    }
19096
19097    static String arrayToString(int[] array) {
19098        StringBuffer buf = new StringBuffer(128);
19099        buf.append('[');
19100        if (array != null) {
19101            for (int i=0; i<array.length; i++) {
19102                if (i > 0) buf.append(", ");
19103                buf.append(array[i]);
19104            }
19105        }
19106        buf.append(']');
19107        return buf.toString();
19108    }
19109
19110    static class DumpState {
19111        public static final int DUMP_LIBS = 1 << 0;
19112        public static final int DUMP_FEATURES = 1 << 1;
19113        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19114        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19115        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19116        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19117        public static final int DUMP_PERMISSIONS = 1 << 6;
19118        public static final int DUMP_PACKAGES = 1 << 7;
19119        public static final int DUMP_SHARED_USERS = 1 << 8;
19120        public static final int DUMP_MESSAGES = 1 << 9;
19121        public static final int DUMP_PROVIDERS = 1 << 10;
19122        public static final int DUMP_VERIFIERS = 1 << 11;
19123        public static final int DUMP_PREFERRED = 1 << 12;
19124        public static final int DUMP_PREFERRED_XML = 1 << 13;
19125        public static final int DUMP_KEYSETS = 1 << 14;
19126        public static final int DUMP_VERSION = 1 << 15;
19127        public static final int DUMP_INSTALLS = 1 << 16;
19128        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19129        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19130        public static final int DUMP_FROZEN = 1 << 19;
19131        public static final int DUMP_DEXOPT = 1 << 20;
19132        public static final int DUMP_COMPILER_STATS = 1 << 21;
19133
19134        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19135
19136        private int mTypes;
19137
19138        private int mOptions;
19139
19140        private boolean mTitlePrinted;
19141
19142        private SharedUserSetting mSharedUser;
19143
19144        public boolean isDumping(int type) {
19145            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19146                return true;
19147            }
19148
19149            return (mTypes & type) != 0;
19150        }
19151
19152        public void setDump(int type) {
19153            mTypes |= type;
19154        }
19155
19156        public boolean isOptionEnabled(int option) {
19157            return (mOptions & option) != 0;
19158        }
19159
19160        public void setOptionEnabled(int option) {
19161            mOptions |= option;
19162        }
19163
19164        public boolean onTitlePrinted() {
19165            final boolean printed = mTitlePrinted;
19166            mTitlePrinted = true;
19167            return printed;
19168        }
19169
19170        public boolean getTitlePrinted() {
19171            return mTitlePrinted;
19172        }
19173
19174        public void setTitlePrinted(boolean enabled) {
19175            mTitlePrinted = enabled;
19176        }
19177
19178        public SharedUserSetting getSharedUser() {
19179            return mSharedUser;
19180        }
19181
19182        public void setSharedUser(SharedUserSetting user) {
19183            mSharedUser = user;
19184        }
19185    }
19186
19187    @Override
19188    public void onShellCommand(FileDescriptor in, FileDescriptor out,
19189            FileDescriptor err, String[] args, ShellCallback callback,
19190            ResultReceiver resultReceiver) {
19191        (new PackageManagerShellCommand(this)).exec(
19192                this, in, out, err, args, callback, resultReceiver);
19193    }
19194
19195    @Override
19196    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
19197        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
19198                != PackageManager.PERMISSION_GRANTED) {
19199            pw.println("Permission Denial: can't dump ActivityManager from from pid="
19200                    + Binder.getCallingPid()
19201                    + ", uid=" + Binder.getCallingUid()
19202                    + " without permission "
19203                    + android.Manifest.permission.DUMP);
19204            return;
19205        }
19206
19207        DumpState dumpState = new DumpState();
19208        boolean fullPreferred = false;
19209        boolean checkin = false;
19210
19211        String packageName = null;
19212        ArraySet<String> permissionNames = null;
19213
19214        int opti = 0;
19215        while (opti < args.length) {
19216            String opt = args[opti];
19217            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
19218                break;
19219            }
19220            opti++;
19221
19222            if ("-a".equals(opt)) {
19223                // Right now we only know how to print all.
19224            } else if ("-h".equals(opt)) {
19225                pw.println("Package manager dump options:");
19226                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
19227                pw.println("    --checkin: dump for a checkin");
19228                pw.println("    -f: print details of intent filters");
19229                pw.println("    -h: print this help");
19230                pw.println("  cmd may be one of:");
19231                pw.println("    l[ibraries]: list known shared libraries");
19232                pw.println("    f[eatures]: list device features");
19233                pw.println("    k[eysets]: print known keysets");
19234                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
19235                pw.println("    perm[issions]: dump permissions");
19236                pw.println("    permission [name ...]: dump declaration and use of given permission");
19237                pw.println("    pref[erred]: print preferred package settings");
19238                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
19239                pw.println("    prov[iders]: dump content providers");
19240                pw.println("    p[ackages]: dump installed packages");
19241                pw.println("    s[hared-users]: dump shared user IDs");
19242                pw.println("    m[essages]: print collected runtime messages");
19243                pw.println("    v[erifiers]: print package verifier info");
19244                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
19245                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
19246                pw.println("    version: print database version info");
19247                pw.println("    write: write current settings now");
19248                pw.println("    installs: details about install sessions");
19249                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
19250                pw.println("    dexopt: dump dexopt state");
19251                pw.println("    compiler-stats: dump compiler statistics");
19252                pw.println("    <package.name>: info about given package");
19253                return;
19254            } else if ("--checkin".equals(opt)) {
19255                checkin = true;
19256            } else if ("-f".equals(opt)) {
19257                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19258            } else {
19259                pw.println("Unknown argument: " + opt + "; use -h for help");
19260            }
19261        }
19262
19263        // Is the caller requesting to dump a particular piece of data?
19264        if (opti < args.length) {
19265            String cmd = args[opti];
19266            opti++;
19267            // Is this a package name?
19268            if ("android".equals(cmd) || cmd.contains(".")) {
19269                packageName = cmd;
19270                // When dumping a single package, we always dump all of its
19271                // filter information since the amount of data will be reasonable.
19272                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19273            } else if ("check-permission".equals(cmd)) {
19274                if (opti >= args.length) {
19275                    pw.println("Error: check-permission missing permission argument");
19276                    return;
19277                }
19278                String perm = args[opti];
19279                opti++;
19280                if (opti >= args.length) {
19281                    pw.println("Error: check-permission missing package argument");
19282                    return;
19283                }
19284                String pkg = args[opti];
19285                opti++;
19286                int user = UserHandle.getUserId(Binder.getCallingUid());
19287                if (opti < args.length) {
19288                    try {
19289                        user = Integer.parseInt(args[opti]);
19290                    } catch (NumberFormatException e) {
19291                        pw.println("Error: check-permission user argument is not a number: "
19292                                + args[opti]);
19293                        return;
19294                    }
19295                }
19296                pw.println(checkPermission(perm, pkg, user));
19297                return;
19298            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
19299                dumpState.setDump(DumpState.DUMP_LIBS);
19300            } else if ("f".equals(cmd) || "features".equals(cmd)) {
19301                dumpState.setDump(DumpState.DUMP_FEATURES);
19302            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
19303                if (opti >= args.length) {
19304                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
19305                            | DumpState.DUMP_SERVICE_RESOLVERS
19306                            | DumpState.DUMP_RECEIVER_RESOLVERS
19307                            | DumpState.DUMP_CONTENT_RESOLVERS);
19308                } else {
19309                    while (opti < args.length) {
19310                        String name = args[opti];
19311                        if ("a".equals(name) || "activity".equals(name)) {
19312                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
19313                        } else if ("s".equals(name) || "service".equals(name)) {
19314                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
19315                        } else if ("r".equals(name) || "receiver".equals(name)) {
19316                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19317                        } else if ("c".equals(name) || "content".equals(name)) {
19318                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19319                        } else {
19320                            pw.println("Error: unknown resolver table type: " + name);
19321                            return;
19322                        }
19323                        opti++;
19324                    }
19325                }
19326            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19327                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19328            } else if ("permission".equals(cmd)) {
19329                if (opti >= args.length) {
19330                    pw.println("Error: permission requires permission name");
19331                    return;
19332                }
19333                permissionNames = new ArraySet<>();
19334                while (opti < args.length) {
19335                    permissionNames.add(args[opti]);
19336                    opti++;
19337                }
19338                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19339                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19340            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19341                dumpState.setDump(DumpState.DUMP_PREFERRED);
19342            } else if ("preferred-xml".equals(cmd)) {
19343                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19344                if (opti < args.length && "--full".equals(args[opti])) {
19345                    fullPreferred = true;
19346                    opti++;
19347                }
19348            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19349                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19350            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19351                dumpState.setDump(DumpState.DUMP_PACKAGES);
19352            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19353                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19354            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19355                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19356            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19357                dumpState.setDump(DumpState.DUMP_MESSAGES);
19358            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19359                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19360            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19361                    || "intent-filter-verifiers".equals(cmd)) {
19362                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19363            } else if ("version".equals(cmd)) {
19364                dumpState.setDump(DumpState.DUMP_VERSION);
19365            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19366                dumpState.setDump(DumpState.DUMP_KEYSETS);
19367            } else if ("installs".equals(cmd)) {
19368                dumpState.setDump(DumpState.DUMP_INSTALLS);
19369            } else if ("frozen".equals(cmd)) {
19370                dumpState.setDump(DumpState.DUMP_FROZEN);
19371            } else if ("dexopt".equals(cmd)) {
19372                dumpState.setDump(DumpState.DUMP_DEXOPT);
19373            } else if ("compiler-stats".equals(cmd)) {
19374                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19375            } else if ("write".equals(cmd)) {
19376                synchronized (mPackages) {
19377                    mSettings.writeLPr();
19378                    pw.println("Settings written.");
19379                    return;
19380                }
19381            }
19382        }
19383
19384        if (checkin) {
19385            pw.println("vers,1");
19386        }
19387
19388        // reader
19389        synchronized (mPackages) {
19390            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19391                if (!checkin) {
19392                    if (dumpState.onTitlePrinted())
19393                        pw.println();
19394                    pw.println("Database versions:");
19395                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19396                }
19397            }
19398
19399            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19400                if (!checkin) {
19401                    if (dumpState.onTitlePrinted())
19402                        pw.println();
19403                    pw.println("Verifiers:");
19404                    pw.print("  Required: ");
19405                    pw.print(mRequiredVerifierPackage);
19406                    pw.print(" (uid=");
19407                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19408                            UserHandle.USER_SYSTEM));
19409                    pw.println(")");
19410                } else if (mRequiredVerifierPackage != null) {
19411                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19412                    pw.print(",");
19413                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19414                            UserHandle.USER_SYSTEM));
19415                }
19416            }
19417
19418            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19419                    packageName == null) {
19420                if (mIntentFilterVerifierComponent != null) {
19421                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19422                    if (!checkin) {
19423                        if (dumpState.onTitlePrinted())
19424                            pw.println();
19425                        pw.println("Intent Filter Verifier:");
19426                        pw.print("  Using: ");
19427                        pw.print(verifierPackageName);
19428                        pw.print(" (uid=");
19429                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19430                                UserHandle.USER_SYSTEM));
19431                        pw.println(")");
19432                    } else if (verifierPackageName != null) {
19433                        pw.print("ifv,"); pw.print(verifierPackageName);
19434                        pw.print(",");
19435                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19436                                UserHandle.USER_SYSTEM));
19437                    }
19438                } else {
19439                    pw.println();
19440                    pw.println("No Intent Filter Verifier available!");
19441                }
19442            }
19443
19444            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19445                boolean printedHeader = false;
19446                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19447                while (it.hasNext()) {
19448                    String name = it.next();
19449                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19450                    if (!checkin) {
19451                        if (!printedHeader) {
19452                            if (dumpState.onTitlePrinted())
19453                                pw.println();
19454                            pw.println("Libraries:");
19455                            printedHeader = true;
19456                        }
19457                        pw.print("  ");
19458                    } else {
19459                        pw.print("lib,");
19460                    }
19461                    pw.print(name);
19462                    if (!checkin) {
19463                        pw.print(" -> ");
19464                    }
19465                    if (ent.path != null) {
19466                        if (!checkin) {
19467                            pw.print("(jar) ");
19468                            pw.print(ent.path);
19469                        } else {
19470                            pw.print(",jar,");
19471                            pw.print(ent.path);
19472                        }
19473                    } else {
19474                        if (!checkin) {
19475                            pw.print("(apk) ");
19476                            pw.print(ent.apk);
19477                        } else {
19478                            pw.print(",apk,");
19479                            pw.print(ent.apk);
19480                        }
19481                    }
19482                    pw.println();
19483                }
19484            }
19485
19486            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19487                if (dumpState.onTitlePrinted())
19488                    pw.println();
19489                if (!checkin) {
19490                    pw.println("Features:");
19491                }
19492
19493                for (FeatureInfo feat : mAvailableFeatures.values()) {
19494                    if (checkin) {
19495                        pw.print("feat,");
19496                        pw.print(feat.name);
19497                        pw.print(",");
19498                        pw.println(feat.version);
19499                    } else {
19500                        pw.print("  ");
19501                        pw.print(feat.name);
19502                        if (feat.version > 0) {
19503                            pw.print(" version=");
19504                            pw.print(feat.version);
19505                        }
19506                        pw.println();
19507                    }
19508                }
19509            }
19510
19511            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19512                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19513                        : "Activity Resolver Table:", "  ", packageName,
19514                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19515                    dumpState.setTitlePrinted(true);
19516                }
19517            }
19518            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19519                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19520                        : "Receiver Resolver Table:", "  ", packageName,
19521                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19522                    dumpState.setTitlePrinted(true);
19523                }
19524            }
19525            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19526                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19527                        : "Service Resolver Table:", "  ", packageName,
19528                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19529                    dumpState.setTitlePrinted(true);
19530                }
19531            }
19532            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19533                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19534                        : "Provider Resolver Table:", "  ", packageName,
19535                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19536                    dumpState.setTitlePrinted(true);
19537                }
19538            }
19539
19540            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19541                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19542                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19543                    int user = mSettings.mPreferredActivities.keyAt(i);
19544                    if (pir.dump(pw,
19545                            dumpState.getTitlePrinted()
19546                                ? "\nPreferred Activities User " + user + ":"
19547                                : "Preferred Activities User " + user + ":", "  ",
19548                            packageName, true, false)) {
19549                        dumpState.setTitlePrinted(true);
19550                    }
19551                }
19552            }
19553
19554            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19555                pw.flush();
19556                FileOutputStream fout = new FileOutputStream(fd);
19557                BufferedOutputStream str = new BufferedOutputStream(fout);
19558                XmlSerializer serializer = new FastXmlSerializer();
19559                try {
19560                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19561                    serializer.startDocument(null, true);
19562                    serializer.setFeature(
19563                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19564                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19565                    serializer.endDocument();
19566                    serializer.flush();
19567                } catch (IllegalArgumentException e) {
19568                    pw.println("Failed writing: " + e);
19569                } catch (IllegalStateException e) {
19570                    pw.println("Failed writing: " + e);
19571                } catch (IOException e) {
19572                    pw.println("Failed writing: " + e);
19573                }
19574            }
19575
19576            if (!checkin
19577                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19578                    && packageName == null) {
19579                pw.println();
19580                int count = mSettings.mPackages.size();
19581                if (count == 0) {
19582                    pw.println("No applications!");
19583                    pw.println();
19584                } else {
19585                    final String prefix = "  ";
19586                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19587                    if (allPackageSettings.size() == 0) {
19588                        pw.println("No domain preferred apps!");
19589                        pw.println();
19590                    } else {
19591                        pw.println("App verification status:");
19592                        pw.println();
19593                        count = 0;
19594                        for (PackageSetting ps : allPackageSettings) {
19595                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19596                            if (ivi == null || ivi.getPackageName() == null) continue;
19597                            pw.println(prefix + "Package: " + ivi.getPackageName());
19598                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19599                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19600                            pw.println();
19601                            count++;
19602                        }
19603                        if (count == 0) {
19604                            pw.println(prefix + "No app verification established.");
19605                            pw.println();
19606                        }
19607                        for (int userId : sUserManager.getUserIds()) {
19608                            pw.println("App linkages for user " + userId + ":");
19609                            pw.println();
19610                            count = 0;
19611                            for (PackageSetting ps : allPackageSettings) {
19612                                final long status = ps.getDomainVerificationStatusForUser(userId);
19613                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19614                                    continue;
19615                                }
19616                                pw.println(prefix + "Package: " + ps.name);
19617                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19618                                String statusStr = IntentFilterVerificationInfo.
19619                                        getStatusStringFromValue(status);
19620                                pw.println(prefix + "Status:  " + statusStr);
19621                                pw.println();
19622                                count++;
19623                            }
19624                            if (count == 0) {
19625                                pw.println(prefix + "No configured app linkages.");
19626                                pw.println();
19627                            }
19628                        }
19629                    }
19630                }
19631            }
19632
19633            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19634                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19635                if (packageName == null && permissionNames == null) {
19636                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19637                        if (iperm == 0) {
19638                            if (dumpState.onTitlePrinted())
19639                                pw.println();
19640                            pw.println("AppOp Permissions:");
19641                        }
19642                        pw.print("  AppOp Permission ");
19643                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19644                        pw.println(":");
19645                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19646                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19647                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19648                        }
19649                    }
19650                }
19651            }
19652
19653            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19654                boolean printedSomething = false;
19655                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19656                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19657                        continue;
19658                    }
19659                    if (!printedSomething) {
19660                        if (dumpState.onTitlePrinted())
19661                            pw.println();
19662                        pw.println("Registered ContentProviders:");
19663                        printedSomething = true;
19664                    }
19665                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19666                    pw.print("    "); pw.println(p.toString());
19667                }
19668                printedSomething = false;
19669                for (Map.Entry<String, PackageParser.Provider> entry :
19670                        mProvidersByAuthority.entrySet()) {
19671                    PackageParser.Provider p = entry.getValue();
19672                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19673                        continue;
19674                    }
19675                    if (!printedSomething) {
19676                        if (dumpState.onTitlePrinted())
19677                            pw.println();
19678                        pw.println("ContentProvider Authorities:");
19679                        printedSomething = true;
19680                    }
19681                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19682                    pw.print("    "); pw.println(p.toString());
19683                    if (p.info != null && p.info.applicationInfo != null) {
19684                        final String appInfo = p.info.applicationInfo.toString();
19685                        pw.print("      applicationInfo="); pw.println(appInfo);
19686                    }
19687                }
19688            }
19689
19690            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19691                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19692            }
19693
19694            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19695                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19696            }
19697
19698            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19699                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19700            }
19701
19702            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19703                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19704            }
19705
19706            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19707                // XXX should handle packageName != null by dumping only install data that
19708                // the given package is involved with.
19709                if (dumpState.onTitlePrinted()) pw.println();
19710                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19711            }
19712
19713            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19714                // XXX should handle packageName != null by dumping only install data that
19715                // the given package is involved with.
19716                if (dumpState.onTitlePrinted()) pw.println();
19717
19718                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19719                ipw.println();
19720                ipw.println("Frozen packages:");
19721                ipw.increaseIndent();
19722                if (mFrozenPackages.size() == 0) {
19723                    ipw.println("(none)");
19724                } else {
19725                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19726                        ipw.println(mFrozenPackages.valueAt(i));
19727                    }
19728                }
19729                ipw.decreaseIndent();
19730            }
19731
19732            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19733                if (dumpState.onTitlePrinted()) pw.println();
19734                dumpDexoptStateLPr(pw, packageName);
19735            }
19736
19737            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19738                if (dumpState.onTitlePrinted()) pw.println();
19739                dumpCompilerStatsLPr(pw, packageName);
19740            }
19741
19742            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19743                if (dumpState.onTitlePrinted()) pw.println();
19744                mSettings.dumpReadMessagesLPr(pw, dumpState);
19745
19746                pw.println();
19747                pw.println("Package warning messages:");
19748                BufferedReader in = null;
19749                String line = null;
19750                try {
19751                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19752                    while ((line = in.readLine()) != null) {
19753                        if (line.contains("ignored: updated version")) continue;
19754                        pw.println(line);
19755                    }
19756                } catch (IOException ignored) {
19757                } finally {
19758                    IoUtils.closeQuietly(in);
19759                }
19760            }
19761
19762            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19763                BufferedReader in = null;
19764                String line = null;
19765                try {
19766                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19767                    while ((line = in.readLine()) != null) {
19768                        if (line.contains("ignored: updated version")) continue;
19769                        pw.print("msg,");
19770                        pw.println(line);
19771                    }
19772                } catch (IOException ignored) {
19773                } finally {
19774                    IoUtils.closeQuietly(in);
19775                }
19776            }
19777        }
19778    }
19779
19780    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19781        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19782        ipw.println();
19783        ipw.println("Dexopt state:");
19784        ipw.increaseIndent();
19785        Collection<PackageParser.Package> packages = null;
19786        if (packageName != null) {
19787            PackageParser.Package targetPackage = mPackages.get(packageName);
19788            if (targetPackage != null) {
19789                packages = Collections.singletonList(targetPackage);
19790            } else {
19791                ipw.println("Unable to find package: " + packageName);
19792                return;
19793            }
19794        } else {
19795            packages = mPackages.values();
19796        }
19797
19798        for (PackageParser.Package pkg : packages) {
19799            ipw.println("[" + pkg.packageName + "]");
19800            ipw.increaseIndent();
19801            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19802            ipw.decreaseIndent();
19803        }
19804    }
19805
19806    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19807        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19808        ipw.println();
19809        ipw.println("Compiler stats:");
19810        ipw.increaseIndent();
19811        Collection<PackageParser.Package> packages = null;
19812        if (packageName != null) {
19813            PackageParser.Package targetPackage = mPackages.get(packageName);
19814            if (targetPackage != null) {
19815                packages = Collections.singletonList(targetPackage);
19816            } else {
19817                ipw.println("Unable to find package: " + packageName);
19818                return;
19819            }
19820        } else {
19821            packages = mPackages.values();
19822        }
19823
19824        for (PackageParser.Package pkg : packages) {
19825            ipw.println("[" + pkg.packageName + "]");
19826            ipw.increaseIndent();
19827
19828            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19829            if (stats == null) {
19830                ipw.println("(No recorded stats)");
19831            } else {
19832                stats.dump(ipw);
19833            }
19834            ipw.decreaseIndent();
19835        }
19836    }
19837
19838    private String dumpDomainString(String packageName) {
19839        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19840                .getList();
19841        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19842
19843        ArraySet<String> result = new ArraySet<>();
19844        if (iviList.size() > 0) {
19845            for (IntentFilterVerificationInfo ivi : iviList) {
19846                for (String host : ivi.getDomains()) {
19847                    result.add(host);
19848                }
19849            }
19850        }
19851        if (filters != null && filters.size() > 0) {
19852            for (IntentFilter filter : filters) {
19853                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19854                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19855                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19856                    result.addAll(filter.getHostsList());
19857                }
19858            }
19859        }
19860
19861        StringBuilder sb = new StringBuilder(result.size() * 16);
19862        for (String domain : result) {
19863            if (sb.length() > 0) sb.append(" ");
19864            sb.append(domain);
19865        }
19866        return sb.toString();
19867    }
19868
19869    // ------- apps on sdcard specific code -------
19870    static final boolean DEBUG_SD_INSTALL = false;
19871
19872    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19873
19874    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19875
19876    private boolean mMediaMounted = false;
19877
19878    static String getEncryptKey() {
19879        try {
19880            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19881                    SD_ENCRYPTION_KEYSTORE_NAME);
19882            if (sdEncKey == null) {
19883                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19884                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19885                if (sdEncKey == null) {
19886                    Slog.e(TAG, "Failed to create encryption keys");
19887                    return null;
19888                }
19889            }
19890            return sdEncKey;
19891        } catch (NoSuchAlgorithmException nsae) {
19892            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19893            return null;
19894        } catch (IOException ioe) {
19895            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19896            return null;
19897        }
19898    }
19899
19900    /*
19901     * Update media status on PackageManager.
19902     */
19903    @Override
19904    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19905        int callingUid = Binder.getCallingUid();
19906        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19907            throw new SecurityException("Media status can only be updated by the system");
19908        }
19909        // reader; this apparently protects mMediaMounted, but should probably
19910        // be a different lock in that case.
19911        synchronized (mPackages) {
19912            Log.i(TAG, "Updating external media status from "
19913                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19914                    + (mediaStatus ? "mounted" : "unmounted"));
19915            if (DEBUG_SD_INSTALL)
19916                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19917                        + ", mMediaMounted=" + mMediaMounted);
19918            if (mediaStatus == mMediaMounted) {
19919                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19920                        : 0, -1);
19921                mHandler.sendMessage(msg);
19922                return;
19923            }
19924            mMediaMounted = mediaStatus;
19925        }
19926        // Queue up an async operation since the package installation may take a
19927        // little while.
19928        mHandler.post(new Runnable() {
19929            public void run() {
19930                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19931            }
19932        });
19933    }
19934
19935    /**
19936     * Called by StorageManagerService when the initial ASECs to scan are available.
19937     * Should block until all the ASEC containers are finished being scanned.
19938     */
19939    public void scanAvailableAsecs() {
19940        updateExternalMediaStatusInner(true, false, false);
19941    }
19942
19943    /*
19944     * Collect information of applications on external media, map them against
19945     * existing containers and update information based on current mount status.
19946     * Please note that we always have to report status if reportStatus has been
19947     * set to true especially when unloading packages.
19948     */
19949    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19950            boolean externalStorage) {
19951        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19952        int[] uidArr = EmptyArray.INT;
19953
19954        final String[] list = PackageHelper.getSecureContainerList();
19955        if (ArrayUtils.isEmpty(list)) {
19956            Log.i(TAG, "No secure containers found");
19957        } else {
19958            // Process list of secure containers and categorize them
19959            // as active or stale based on their package internal state.
19960
19961            // reader
19962            synchronized (mPackages) {
19963                for (String cid : list) {
19964                    // Leave stages untouched for now; installer service owns them
19965                    if (PackageInstallerService.isStageName(cid)) continue;
19966
19967                    if (DEBUG_SD_INSTALL)
19968                        Log.i(TAG, "Processing container " + cid);
19969                    String pkgName = getAsecPackageName(cid);
19970                    if (pkgName == null) {
19971                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19972                        continue;
19973                    }
19974                    if (DEBUG_SD_INSTALL)
19975                        Log.i(TAG, "Looking for pkg : " + pkgName);
19976
19977                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19978                    if (ps == null) {
19979                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19980                        continue;
19981                    }
19982
19983                    /*
19984                     * Skip packages that are not external if we're unmounting
19985                     * external storage.
19986                     */
19987                    if (externalStorage && !isMounted && !isExternal(ps)) {
19988                        continue;
19989                    }
19990
19991                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19992                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19993                    // The package status is changed only if the code path
19994                    // matches between settings and the container id.
19995                    if (ps.codePathString != null
19996                            && ps.codePathString.startsWith(args.getCodePath())) {
19997                        if (DEBUG_SD_INSTALL) {
19998                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19999                                    + " at code path: " + ps.codePathString);
20000                        }
20001
20002                        // We do have a valid package installed on sdcard
20003                        processCids.put(args, ps.codePathString);
20004                        final int uid = ps.appId;
20005                        if (uid != -1) {
20006                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20007                        }
20008                    } else {
20009                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20010                                + ps.codePathString);
20011                    }
20012                }
20013            }
20014
20015            Arrays.sort(uidArr);
20016        }
20017
20018        // Process packages with valid entries.
20019        if (isMounted) {
20020            if (DEBUG_SD_INSTALL)
20021                Log.i(TAG, "Loading packages");
20022            loadMediaPackages(processCids, uidArr, externalStorage);
20023            startCleaningPackages();
20024            mInstallerService.onSecureContainersAvailable();
20025        } else {
20026            if (DEBUG_SD_INSTALL)
20027                Log.i(TAG, "Unloading packages");
20028            unloadMediaPackages(processCids, uidArr, reportStatus);
20029        }
20030    }
20031
20032    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20033            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20034        final int size = infos.size();
20035        final String[] packageNames = new String[size];
20036        final int[] packageUids = new int[size];
20037        for (int i = 0; i < size; i++) {
20038            final ApplicationInfo info = infos.get(i);
20039            packageNames[i] = info.packageName;
20040            packageUids[i] = info.uid;
20041        }
20042        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20043                finishedReceiver);
20044    }
20045
20046    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20047            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20048        sendResourcesChangedBroadcast(mediaStatus, replacing,
20049                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20050    }
20051
20052    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20053            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20054        int size = pkgList.length;
20055        if (size > 0) {
20056            // Send broadcasts here
20057            Bundle extras = new Bundle();
20058            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20059            if (uidArr != null) {
20060                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20061            }
20062            if (replacing) {
20063                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20064            }
20065            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20066                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20067            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20068        }
20069    }
20070
20071   /*
20072     * Look at potentially valid container ids from processCids If package
20073     * information doesn't match the one on record or package scanning fails,
20074     * the cid is added to list of removeCids. We currently don't delete stale
20075     * containers.
20076     */
20077    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20078            boolean externalStorage) {
20079        ArrayList<String> pkgList = new ArrayList<String>();
20080        Set<AsecInstallArgs> keys = processCids.keySet();
20081
20082        for (AsecInstallArgs args : keys) {
20083            String codePath = processCids.get(args);
20084            if (DEBUG_SD_INSTALL)
20085                Log.i(TAG, "Loading container : " + args.cid);
20086            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20087            try {
20088                // Make sure there are no container errors first.
20089                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20090                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20091                            + " when installing from sdcard");
20092                    continue;
20093                }
20094                // Check code path here.
20095                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20096                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20097                            + " does not match one in settings " + codePath);
20098                    continue;
20099                }
20100                // Parse package
20101                int parseFlags = mDefParseFlags;
20102                if (args.isExternalAsec()) {
20103                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20104                }
20105                if (args.isFwdLocked()) {
20106                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20107                }
20108
20109                synchronized (mInstallLock) {
20110                    PackageParser.Package pkg = null;
20111                    try {
20112                        // Sadly we don't know the package name yet to freeze it
20113                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20114                                SCAN_IGNORE_FROZEN, 0, null);
20115                    } catch (PackageManagerException e) {
20116                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20117                    }
20118                    // Scan the package
20119                    if (pkg != null) {
20120                        /*
20121                         * TODO why is the lock being held? doPostInstall is
20122                         * called in other places without the lock. This needs
20123                         * to be straightened out.
20124                         */
20125                        // writer
20126                        synchronized (mPackages) {
20127                            retCode = PackageManager.INSTALL_SUCCEEDED;
20128                            pkgList.add(pkg.packageName);
20129                            // Post process args
20130                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20131                                    pkg.applicationInfo.uid);
20132                        }
20133                    } else {
20134                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20135                    }
20136                }
20137
20138            } finally {
20139                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20140                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20141                }
20142            }
20143        }
20144        // writer
20145        synchronized (mPackages) {
20146            // If the platform SDK has changed since the last time we booted,
20147            // we need to re-grant app permission to catch any new ones that
20148            // appear. This is really a hack, and means that apps can in some
20149            // cases get permissions that the user didn't initially explicitly
20150            // allow... it would be nice to have some better way to handle
20151            // this situation.
20152            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20153                    : mSettings.getInternalVersion();
20154            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20155                    : StorageManager.UUID_PRIVATE_INTERNAL;
20156
20157            int updateFlags = UPDATE_PERMISSIONS_ALL;
20158            if (ver.sdkVersion != mSdkVersion) {
20159                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20160                        + mSdkVersion + "; regranting permissions for external");
20161                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20162            }
20163            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20164
20165            // Yay, everything is now upgraded
20166            ver.forceCurrent();
20167
20168            // can downgrade to reader
20169            // Persist settings
20170            mSettings.writeLPr();
20171        }
20172        // Send a broadcast to let everyone know we are done processing
20173        if (pkgList.size() > 0) {
20174            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20175        }
20176    }
20177
20178   /*
20179     * Utility method to unload a list of specified containers
20180     */
20181    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
20182        // Just unmount all valid containers.
20183        for (AsecInstallArgs arg : cidArgs) {
20184            synchronized (mInstallLock) {
20185                arg.doPostDeleteLI(false);
20186           }
20187       }
20188   }
20189
20190    /*
20191     * Unload packages mounted on external media. This involves deleting package
20192     * data from internal structures, sending broadcasts about disabled packages,
20193     * gc'ing to free up references, unmounting all secure containers
20194     * corresponding to packages on external media, and posting a
20195     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
20196     * that we always have to post this message if status has been requested no
20197     * matter what.
20198     */
20199    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
20200            final boolean reportStatus) {
20201        if (DEBUG_SD_INSTALL)
20202            Log.i(TAG, "unloading media packages");
20203        ArrayList<String> pkgList = new ArrayList<String>();
20204        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
20205        final Set<AsecInstallArgs> keys = processCids.keySet();
20206        for (AsecInstallArgs args : keys) {
20207            String pkgName = args.getPackageName();
20208            if (DEBUG_SD_INSTALL)
20209                Log.i(TAG, "Trying to unload pkg : " + pkgName);
20210            // Delete package internally
20211            PackageRemovedInfo outInfo = new PackageRemovedInfo();
20212            synchronized (mInstallLock) {
20213                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20214                final boolean res;
20215                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
20216                        "unloadMediaPackages")) {
20217                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
20218                            null);
20219                }
20220                if (res) {
20221                    pkgList.add(pkgName);
20222                } else {
20223                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
20224                    failedList.add(args);
20225                }
20226            }
20227        }
20228
20229        // reader
20230        synchronized (mPackages) {
20231            // We didn't update the settings after removing each package;
20232            // write them now for all packages.
20233            mSettings.writeLPr();
20234        }
20235
20236        // We have to absolutely send UPDATED_MEDIA_STATUS only
20237        // after confirming that all the receivers processed the ordered
20238        // broadcast when packages get disabled, force a gc to clean things up.
20239        // and unload all the containers.
20240        if (pkgList.size() > 0) {
20241            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
20242                    new IIntentReceiver.Stub() {
20243                public void performReceive(Intent intent, int resultCode, String data,
20244                        Bundle extras, boolean ordered, boolean sticky,
20245                        int sendingUser) throws RemoteException {
20246                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
20247                            reportStatus ? 1 : 0, 1, keys);
20248                    mHandler.sendMessage(msg);
20249                }
20250            });
20251        } else {
20252            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
20253                    keys);
20254            mHandler.sendMessage(msg);
20255        }
20256    }
20257
20258    private void loadPrivatePackages(final VolumeInfo vol) {
20259        mHandler.post(new Runnable() {
20260            @Override
20261            public void run() {
20262                loadPrivatePackagesInner(vol);
20263            }
20264        });
20265    }
20266
20267    private void loadPrivatePackagesInner(VolumeInfo vol) {
20268        final String volumeUuid = vol.fsUuid;
20269        if (TextUtils.isEmpty(volumeUuid)) {
20270            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20271            return;
20272        }
20273
20274        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20275        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20276        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20277
20278        final VersionInfo ver;
20279        final List<PackageSetting> packages;
20280        synchronized (mPackages) {
20281            ver = mSettings.findOrCreateVersion(volumeUuid);
20282            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20283        }
20284
20285        for (PackageSetting ps : packages) {
20286            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20287            synchronized (mInstallLock) {
20288                final PackageParser.Package pkg;
20289                try {
20290                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20291                    loaded.add(pkg.applicationInfo);
20292
20293                } catch (PackageManagerException e) {
20294                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20295                }
20296
20297                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20298                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20299                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20300                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20301                }
20302            }
20303        }
20304
20305        // Reconcile app data for all started/unlocked users
20306        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20307        final UserManager um = mContext.getSystemService(UserManager.class);
20308        UserManagerInternal umInternal = getUserManagerInternal();
20309        for (UserInfo user : um.getUsers()) {
20310            final int flags;
20311            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20312                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20313            } else if (umInternal.isUserRunning(user.id)) {
20314                flags = StorageManager.FLAG_STORAGE_DE;
20315            } else {
20316                continue;
20317            }
20318
20319            try {
20320                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20321                synchronized (mInstallLock) {
20322                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20323                }
20324            } catch (IllegalStateException e) {
20325                // Device was probably ejected, and we'll process that event momentarily
20326                Slog.w(TAG, "Failed to prepare storage: " + e);
20327            }
20328        }
20329
20330        synchronized (mPackages) {
20331            int updateFlags = UPDATE_PERMISSIONS_ALL;
20332            if (ver.sdkVersion != mSdkVersion) {
20333                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20334                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20335                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20336            }
20337            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20338
20339            // Yay, everything is now upgraded
20340            ver.forceCurrent();
20341
20342            mSettings.writeLPr();
20343        }
20344
20345        for (PackageFreezer freezer : freezers) {
20346            freezer.close();
20347        }
20348
20349        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20350        sendResourcesChangedBroadcast(true, false, loaded, null);
20351    }
20352
20353    private void unloadPrivatePackages(final VolumeInfo vol) {
20354        mHandler.post(new Runnable() {
20355            @Override
20356            public void run() {
20357                unloadPrivatePackagesInner(vol);
20358            }
20359        });
20360    }
20361
20362    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20363        final String volumeUuid = vol.fsUuid;
20364        if (TextUtils.isEmpty(volumeUuid)) {
20365            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20366            return;
20367        }
20368
20369        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20370        synchronized (mInstallLock) {
20371        synchronized (mPackages) {
20372            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20373            for (PackageSetting ps : packages) {
20374                if (ps.pkg == null) continue;
20375
20376                final ApplicationInfo info = ps.pkg.applicationInfo;
20377                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20378                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20379
20380                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20381                        "unloadPrivatePackagesInner")) {
20382                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20383                            false, null)) {
20384                        unloaded.add(info);
20385                    } else {
20386                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20387                    }
20388                }
20389
20390                // Try very hard to release any references to this package
20391                // so we don't risk the system server being killed due to
20392                // open FDs
20393                AttributeCache.instance().removePackage(ps.name);
20394            }
20395
20396            mSettings.writeLPr();
20397        }
20398        }
20399
20400        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20401        sendResourcesChangedBroadcast(false, false, unloaded, null);
20402
20403        // Try very hard to release any references to this path so we don't risk
20404        // the system server being killed due to open FDs
20405        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20406
20407        for (int i = 0; i < 3; i++) {
20408            System.gc();
20409            System.runFinalization();
20410        }
20411    }
20412
20413    /**
20414     * Prepare storage areas for given user on all mounted devices.
20415     */
20416    void prepareUserData(int userId, int userSerial, int flags) {
20417        synchronized (mInstallLock) {
20418            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20419            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20420                final String volumeUuid = vol.getFsUuid();
20421                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20422            }
20423        }
20424    }
20425
20426    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20427            boolean allowRecover) {
20428        // Prepare storage and verify that serial numbers are consistent; if
20429        // there's a mismatch we need to destroy to avoid leaking data
20430        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20431        try {
20432            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20433
20434            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20435                UserManagerService.enforceSerialNumber(
20436                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20437                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20438                    UserManagerService.enforceSerialNumber(
20439                            Environment.getDataSystemDeDirectory(userId), userSerial);
20440                }
20441            }
20442            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20443                UserManagerService.enforceSerialNumber(
20444                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20445                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20446                    UserManagerService.enforceSerialNumber(
20447                            Environment.getDataSystemCeDirectory(userId), userSerial);
20448                }
20449            }
20450
20451            synchronized (mInstallLock) {
20452                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20453            }
20454        } catch (Exception e) {
20455            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20456                    + " because we failed to prepare: " + e);
20457            destroyUserDataLI(volumeUuid, userId,
20458                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20459
20460            if (allowRecover) {
20461                // Try one last time; if we fail again we're really in trouble
20462                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20463            }
20464        }
20465    }
20466
20467    /**
20468     * Destroy storage areas for given user on all mounted devices.
20469     */
20470    void destroyUserData(int userId, int flags) {
20471        synchronized (mInstallLock) {
20472            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20473            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20474                final String volumeUuid = vol.getFsUuid();
20475                destroyUserDataLI(volumeUuid, userId, flags);
20476            }
20477        }
20478    }
20479
20480    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20481        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20482        try {
20483            // Clean up app data, profile data, and media data
20484            mInstaller.destroyUserData(volumeUuid, userId, flags);
20485
20486            // Clean up system data
20487            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20488                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20489                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20490                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20491                }
20492                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20493                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20494                }
20495            }
20496
20497            // Data with special labels is now gone, so finish the job
20498            storage.destroyUserStorage(volumeUuid, userId, flags);
20499
20500        } catch (Exception e) {
20501            logCriticalInfo(Log.WARN,
20502                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20503        }
20504    }
20505
20506    /**
20507     * Examine all users present on given mounted volume, and destroy data
20508     * belonging to users that are no longer valid, or whose user ID has been
20509     * recycled.
20510     */
20511    private void reconcileUsers(String volumeUuid) {
20512        final List<File> files = new ArrayList<>();
20513        Collections.addAll(files, FileUtils
20514                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20515        Collections.addAll(files, FileUtils
20516                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20517        Collections.addAll(files, FileUtils
20518                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20519        Collections.addAll(files, FileUtils
20520                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20521        for (File file : files) {
20522            if (!file.isDirectory()) continue;
20523
20524            final int userId;
20525            final UserInfo info;
20526            try {
20527                userId = Integer.parseInt(file.getName());
20528                info = sUserManager.getUserInfo(userId);
20529            } catch (NumberFormatException e) {
20530                Slog.w(TAG, "Invalid user directory " + file);
20531                continue;
20532            }
20533
20534            boolean destroyUser = false;
20535            if (info == null) {
20536                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20537                        + " because no matching user was found");
20538                destroyUser = true;
20539            } else if (!mOnlyCore) {
20540                try {
20541                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20542                } catch (IOException e) {
20543                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20544                            + " because we failed to enforce serial number: " + e);
20545                    destroyUser = true;
20546                }
20547            }
20548
20549            if (destroyUser) {
20550                synchronized (mInstallLock) {
20551                    destroyUserDataLI(volumeUuid, userId,
20552                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20553                }
20554            }
20555        }
20556    }
20557
20558    private void assertPackageKnown(String volumeUuid, String packageName)
20559            throws PackageManagerException {
20560        synchronized (mPackages) {
20561            // Normalize package name to handle renamed packages
20562            packageName = normalizePackageNameLPr(packageName);
20563
20564            final PackageSetting ps = mSettings.mPackages.get(packageName);
20565            if (ps == null) {
20566                throw new PackageManagerException("Package " + packageName + " is unknown");
20567            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20568                throw new PackageManagerException(
20569                        "Package " + packageName + " found on unknown volume " + volumeUuid
20570                                + "; expected volume " + ps.volumeUuid);
20571            }
20572        }
20573    }
20574
20575    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20576            throws PackageManagerException {
20577        synchronized (mPackages) {
20578            // Normalize package name to handle renamed packages
20579            packageName = normalizePackageNameLPr(packageName);
20580
20581            final PackageSetting ps = mSettings.mPackages.get(packageName);
20582            if (ps == null) {
20583                throw new PackageManagerException("Package " + packageName + " is unknown");
20584            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20585                throw new PackageManagerException(
20586                        "Package " + packageName + " found on unknown volume " + volumeUuid
20587                                + "; expected volume " + ps.volumeUuid);
20588            } else if (!ps.getInstalled(userId)) {
20589                throw new PackageManagerException(
20590                        "Package " + packageName + " not installed for user " + userId);
20591            }
20592        }
20593    }
20594
20595    /**
20596     * Examine all apps present on given mounted volume, and destroy apps that
20597     * aren't expected, either due to uninstallation or reinstallation on
20598     * another volume.
20599     */
20600    private void reconcileApps(String volumeUuid) {
20601        final File[] files = FileUtils
20602                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20603        for (File file : files) {
20604            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20605                    && !PackageInstallerService.isStageName(file.getName());
20606            if (!isPackage) {
20607                // Ignore entries which are not packages
20608                continue;
20609            }
20610
20611            try {
20612                final PackageLite pkg = PackageParser.parsePackageLite(file,
20613                        PackageParser.PARSE_MUST_BE_APK);
20614                assertPackageKnown(volumeUuid, pkg.packageName);
20615
20616            } catch (PackageParserException | PackageManagerException e) {
20617                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20618                synchronized (mInstallLock) {
20619                    removeCodePathLI(file);
20620                }
20621            }
20622        }
20623    }
20624
20625    /**
20626     * Reconcile all app data for the given user.
20627     * <p>
20628     * Verifies that directories exist and that ownership and labeling is
20629     * correct for all installed apps on all mounted volumes.
20630     */
20631    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20632        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20633        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20634            final String volumeUuid = vol.getFsUuid();
20635            synchronized (mInstallLock) {
20636                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20637            }
20638        }
20639    }
20640
20641    /**
20642     * Reconcile all app data on given mounted volume.
20643     * <p>
20644     * Destroys app data that isn't expected, either due to uninstallation or
20645     * reinstallation on another volume.
20646     * <p>
20647     * Verifies that directories exist and that ownership and labeling is
20648     * correct for all installed apps.
20649     */
20650    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20651            boolean migrateAppData) {
20652        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20653                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20654
20655        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20656        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20657
20658        // First look for stale data that doesn't belong, and check if things
20659        // have changed since we did our last restorecon
20660        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20661            if (StorageManager.isFileEncryptedNativeOrEmulated()
20662                    && !StorageManager.isUserKeyUnlocked(userId)) {
20663                throw new RuntimeException(
20664                        "Yikes, someone asked us to reconcile CE storage while " + userId
20665                                + " was still locked; this would have caused massive data loss!");
20666            }
20667
20668            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20669            for (File file : files) {
20670                final String packageName = file.getName();
20671                try {
20672                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20673                } catch (PackageManagerException e) {
20674                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20675                    try {
20676                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20677                                StorageManager.FLAG_STORAGE_CE, 0);
20678                    } catch (InstallerException e2) {
20679                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20680                    }
20681                }
20682            }
20683        }
20684        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20685            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20686            for (File file : files) {
20687                final String packageName = file.getName();
20688                try {
20689                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20690                } catch (PackageManagerException e) {
20691                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20692                    try {
20693                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20694                                StorageManager.FLAG_STORAGE_DE, 0);
20695                    } catch (InstallerException e2) {
20696                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20697                    }
20698                }
20699            }
20700        }
20701
20702        // Ensure that data directories are ready to roll for all packages
20703        // installed for this volume and user
20704        final List<PackageSetting> packages;
20705        synchronized (mPackages) {
20706            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20707        }
20708        int preparedCount = 0;
20709        for (PackageSetting ps : packages) {
20710            final String packageName = ps.name;
20711            if (ps.pkg == null) {
20712                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20713                // TODO: might be due to legacy ASEC apps; we should circle back
20714                // and reconcile again once they're scanned
20715                continue;
20716            }
20717
20718            if (ps.getInstalled(userId)) {
20719                prepareAppDataLIF(ps.pkg, userId, flags);
20720
20721                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20722                    // We may have just shuffled around app data directories, so
20723                    // prepare them one more time
20724                    prepareAppDataLIF(ps.pkg, userId, flags);
20725                }
20726
20727                preparedCount++;
20728            }
20729        }
20730
20731        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20732    }
20733
20734    /**
20735     * Prepare app data for the given app just after it was installed or
20736     * upgraded. This method carefully only touches users that it's installed
20737     * for, and it forces a restorecon to handle any seinfo changes.
20738     * <p>
20739     * Verifies that directories exist and that ownership and labeling is
20740     * correct for all installed apps. If there is an ownership mismatch, it
20741     * will try recovering system apps by wiping data; third-party app data is
20742     * left intact.
20743     * <p>
20744     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20745     */
20746    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20747        final PackageSetting ps;
20748        synchronized (mPackages) {
20749            ps = mSettings.mPackages.get(pkg.packageName);
20750            mSettings.writeKernelMappingLPr(ps);
20751        }
20752
20753        final UserManager um = mContext.getSystemService(UserManager.class);
20754        UserManagerInternal umInternal = getUserManagerInternal();
20755        for (UserInfo user : um.getUsers()) {
20756            final int flags;
20757            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20758                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20759            } else if (umInternal.isUserRunning(user.id)) {
20760                flags = StorageManager.FLAG_STORAGE_DE;
20761            } else {
20762                continue;
20763            }
20764
20765            if (ps.getInstalled(user.id)) {
20766                // TODO: when user data is locked, mark that we're still dirty
20767                prepareAppDataLIF(pkg, user.id, flags);
20768            }
20769        }
20770    }
20771
20772    /**
20773     * Prepare app data for the given app.
20774     * <p>
20775     * Verifies that directories exist and that ownership and labeling is
20776     * correct for all installed apps. If there is an ownership mismatch, this
20777     * will try recovering system apps by wiping data; third-party app data is
20778     * left intact.
20779     */
20780    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20781        if (pkg == null) {
20782            Slog.wtf(TAG, "Package was null!", new Throwable());
20783            return;
20784        }
20785        prepareAppDataLeafLIF(pkg, userId, flags);
20786        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20787        for (int i = 0; i < childCount; i++) {
20788            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20789        }
20790    }
20791
20792    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20793        if (DEBUG_APP_DATA) {
20794            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20795                    + Integer.toHexString(flags));
20796        }
20797
20798        final String volumeUuid = pkg.volumeUuid;
20799        final String packageName = pkg.packageName;
20800        final ApplicationInfo app = pkg.applicationInfo;
20801        final int appId = UserHandle.getAppId(app.uid);
20802
20803        Preconditions.checkNotNull(app.seinfo);
20804
20805        long ceDataInode = -1;
20806        try {
20807            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20808                    appId, app.seinfo, app.targetSdkVersion);
20809        } catch (InstallerException e) {
20810            if (app.isSystemApp()) {
20811                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20812                        + ", but trying to recover: " + e);
20813                destroyAppDataLeafLIF(pkg, userId, flags);
20814                try {
20815                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20816                            appId, app.seinfo, app.targetSdkVersion);
20817                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20818                } catch (InstallerException e2) {
20819                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20820                }
20821            } else {
20822                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20823            }
20824        }
20825
20826        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20827            // TODO: mark this structure as dirty so we persist it!
20828            synchronized (mPackages) {
20829                final PackageSetting ps = mSettings.mPackages.get(packageName);
20830                if (ps != null) {
20831                    ps.setCeDataInode(ceDataInode, userId);
20832                }
20833            }
20834        }
20835
20836        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20837    }
20838
20839    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20840        if (pkg == null) {
20841            Slog.wtf(TAG, "Package was null!", new Throwable());
20842            return;
20843        }
20844        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20845        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20846        for (int i = 0; i < childCount; i++) {
20847            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20848        }
20849    }
20850
20851    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20852        final String volumeUuid = pkg.volumeUuid;
20853        final String packageName = pkg.packageName;
20854        final ApplicationInfo app = pkg.applicationInfo;
20855
20856        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20857            // Create a native library symlink only if we have native libraries
20858            // and if the native libraries are 32 bit libraries. We do not provide
20859            // this symlink for 64 bit libraries.
20860            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20861                final String nativeLibPath = app.nativeLibraryDir;
20862                try {
20863                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20864                            nativeLibPath, userId);
20865                } catch (InstallerException e) {
20866                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20867                }
20868            }
20869        }
20870    }
20871
20872    /**
20873     * For system apps on non-FBE devices, this method migrates any existing
20874     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20875     * requested by the app.
20876     */
20877    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20878        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20879                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20880            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20881                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20882            try {
20883                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20884                        storageTarget);
20885            } catch (InstallerException e) {
20886                logCriticalInfo(Log.WARN,
20887                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20888            }
20889            return true;
20890        } else {
20891            return false;
20892        }
20893    }
20894
20895    public PackageFreezer freezePackage(String packageName, String killReason) {
20896        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20897    }
20898
20899    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20900        return new PackageFreezer(packageName, userId, killReason);
20901    }
20902
20903    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20904            String killReason) {
20905        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20906    }
20907
20908    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20909            String killReason) {
20910        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20911            return new PackageFreezer();
20912        } else {
20913            return freezePackage(packageName, userId, killReason);
20914        }
20915    }
20916
20917    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20918            String killReason) {
20919        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20920    }
20921
20922    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20923            String killReason) {
20924        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20925            return new PackageFreezer();
20926        } else {
20927            return freezePackage(packageName, userId, killReason);
20928        }
20929    }
20930
20931    /**
20932     * Class that freezes and kills the given package upon creation, and
20933     * unfreezes it upon closing. This is typically used when doing surgery on
20934     * app code/data to prevent the app from running while you're working.
20935     */
20936    private class PackageFreezer implements AutoCloseable {
20937        private final String mPackageName;
20938        private final PackageFreezer[] mChildren;
20939
20940        private final boolean mWeFroze;
20941
20942        private final AtomicBoolean mClosed = new AtomicBoolean();
20943        private final CloseGuard mCloseGuard = CloseGuard.get();
20944
20945        /**
20946         * Create and return a stub freezer that doesn't actually do anything,
20947         * typically used when someone requested
20948         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20949         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20950         */
20951        public PackageFreezer() {
20952            mPackageName = null;
20953            mChildren = null;
20954            mWeFroze = false;
20955            mCloseGuard.open("close");
20956        }
20957
20958        public PackageFreezer(String packageName, int userId, String killReason) {
20959            synchronized (mPackages) {
20960                mPackageName = packageName;
20961                mWeFroze = mFrozenPackages.add(mPackageName);
20962
20963                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20964                if (ps != null) {
20965                    killApplication(ps.name, ps.appId, userId, killReason);
20966                }
20967
20968                final PackageParser.Package p = mPackages.get(packageName);
20969                if (p != null && p.childPackages != null) {
20970                    final int N = p.childPackages.size();
20971                    mChildren = new PackageFreezer[N];
20972                    for (int i = 0; i < N; i++) {
20973                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20974                                userId, killReason);
20975                    }
20976                } else {
20977                    mChildren = null;
20978                }
20979            }
20980            mCloseGuard.open("close");
20981        }
20982
20983        @Override
20984        protected void finalize() throws Throwable {
20985            try {
20986                mCloseGuard.warnIfOpen();
20987                close();
20988            } finally {
20989                super.finalize();
20990            }
20991        }
20992
20993        @Override
20994        public void close() {
20995            mCloseGuard.close();
20996            if (mClosed.compareAndSet(false, true)) {
20997                synchronized (mPackages) {
20998                    if (mWeFroze) {
20999                        mFrozenPackages.remove(mPackageName);
21000                    }
21001
21002                    if (mChildren != null) {
21003                        for (PackageFreezer freezer : mChildren) {
21004                            freezer.close();
21005                        }
21006                    }
21007                }
21008            }
21009        }
21010    }
21011
21012    /**
21013     * Verify that given package is currently frozen.
21014     */
21015    private void checkPackageFrozen(String packageName) {
21016        synchronized (mPackages) {
21017            if (!mFrozenPackages.contains(packageName)) {
21018                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21019            }
21020        }
21021    }
21022
21023    @Override
21024    public int movePackage(final String packageName, final String volumeUuid) {
21025        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21026
21027        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21028        final int moveId = mNextMoveId.getAndIncrement();
21029        mHandler.post(new Runnable() {
21030            @Override
21031            public void run() {
21032                try {
21033                    movePackageInternal(packageName, volumeUuid, moveId, user);
21034                } catch (PackageManagerException e) {
21035                    Slog.w(TAG, "Failed to move " + packageName, e);
21036                    mMoveCallbacks.notifyStatusChanged(moveId,
21037                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21038                }
21039            }
21040        });
21041        return moveId;
21042    }
21043
21044    private void movePackageInternal(final String packageName, final String volumeUuid,
21045            final int moveId, UserHandle user) throws PackageManagerException {
21046        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21047        final PackageManager pm = mContext.getPackageManager();
21048
21049        final boolean currentAsec;
21050        final String currentVolumeUuid;
21051        final File codeFile;
21052        final String installerPackageName;
21053        final String packageAbiOverride;
21054        final int appId;
21055        final String seinfo;
21056        final String label;
21057        final int targetSdkVersion;
21058        final PackageFreezer freezer;
21059        final int[] installedUserIds;
21060
21061        // reader
21062        synchronized (mPackages) {
21063            final PackageParser.Package pkg = mPackages.get(packageName);
21064            final PackageSetting ps = mSettings.mPackages.get(packageName);
21065            if (pkg == null || ps == null) {
21066                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21067            }
21068
21069            if (pkg.applicationInfo.isSystemApp()) {
21070                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21071                        "Cannot move system application");
21072            }
21073
21074            if (pkg.applicationInfo.isExternalAsec()) {
21075                currentAsec = true;
21076                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21077            } else if (pkg.applicationInfo.isForwardLocked()) {
21078                currentAsec = true;
21079                currentVolumeUuid = "forward_locked";
21080            } else {
21081                currentAsec = false;
21082                currentVolumeUuid = ps.volumeUuid;
21083
21084                final File probe = new File(pkg.codePath);
21085                final File probeOat = new File(probe, "oat");
21086                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21087                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21088                            "Move only supported for modern cluster style installs");
21089                }
21090            }
21091
21092            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21093                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21094                        "Package already moved to " + volumeUuid);
21095            }
21096            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21097                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21098                        "Device admin cannot be moved");
21099            }
21100
21101            if (mFrozenPackages.contains(packageName)) {
21102                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21103                        "Failed to move already frozen package");
21104            }
21105
21106            codeFile = new File(pkg.codePath);
21107            installerPackageName = ps.installerPackageName;
21108            packageAbiOverride = ps.cpuAbiOverrideString;
21109            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21110            seinfo = pkg.applicationInfo.seinfo;
21111            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21112            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21113            freezer = freezePackage(packageName, "movePackageInternal");
21114            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21115        }
21116
21117        final Bundle extras = new Bundle();
21118        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21119        extras.putString(Intent.EXTRA_TITLE, label);
21120        mMoveCallbacks.notifyCreated(moveId, extras);
21121
21122        int installFlags;
21123        final boolean moveCompleteApp;
21124        final File measurePath;
21125
21126        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21127            installFlags = INSTALL_INTERNAL;
21128            moveCompleteApp = !currentAsec;
21129            measurePath = Environment.getDataAppDirectory(volumeUuid);
21130        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21131            installFlags = INSTALL_EXTERNAL;
21132            moveCompleteApp = false;
21133            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21134        } else {
21135            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21136            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21137                    || !volume.isMountedWritable()) {
21138                freezer.close();
21139                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21140                        "Move location not mounted private volume");
21141            }
21142
21143            Preconditions.checkState(!currentAsec);
21144
21145            installFlags = INSTALL_INTERNAL;
21146            moveCompleteApp = true;
21147            measurePath = Environment.getDataAppDirectory(volumeUuid);
21148        }
21149
21150        final PackageStats stats = new PackageStats(null, -1);
21151        synchronized (mInstaller) {
21152            for (int userId : installedUserIds) {
21153                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21154                    freezer.close();
21155                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21156                            "Failed to measure package size");
21157                }
21158            }
21159        }
21160
21161        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21162                + stats.dataSize);
21163
21164        final long startFreeBytes = measurePath.getFreeSpace();
21165        final long sizeBytes;
21166        if (moveCompleteApp) {
21167            sizeBytes = stats.codeSize + stats.dataSize;
21168        } else {
21169            sizeBytes = stats.codeSize;
21170        }
21171
21172        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21173            freezer.close();
21174            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21175                    "Not enough free space to move");
21176        }
21177
21178        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21179
21180        final CountDownLatch installedLatch = new CountDownLatch(1);
21181        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21182            @Override
21183            public void onUserActionRequired(Intent intent) throws RemoteException {
21184                throw new IllegalStateException();
21185            }
21186
21187            @Override
21188            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21189                    Bundle extras) throws RemoteException {
21190                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21191                        + PackageManager.installStatusToString(returnCode, msg));
21192
21193                installedLatch.countDown();
21194                freezer.close();
21195
21196                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21197                switch (status) {
21198                    case PackageInstaller.STATUS_SUCCESS:
21199                        mMoveCallbacks.notifyStatusChanged(moveId,
21200                                PackageManager.MOVE_SUCCEEDED);
21201                        break;
21202                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21203                        mMoveCallbacks.notifyStatusChanged(moveId,
21204                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21205                        break;
21206                    default:
21207                        mMoveCallbacks.notifyStatusChanged(moveId,
21208                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21209                        break;
21210                }
21211            }
21212        };
21213
21214        final MoveInfo move;
21215        if (moveCompleteApp) {
21216            // Kick off a thread to report progress estimates
21217            new Thread() {
21218                @Override
21219                public void run() {
21220                    while (true) {
21221                        try {
21222                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21223                                break;
21224                            }
21225                        } catch (InterruptedException ignored) {
21226                        }
21227
21228                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
21229                        final int progress = 10 + (int) MathUtils.constrain(
21230                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21231                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21232                    }
21233                }
21234            }.start();
21235
21236            final String dataAppName = codeFile.getName();
21237            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21238                    dataAppName, appId, seinfo, targetSdkVersion);
21239        } else {
21240            move = null;
21241        }
21242
21243        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21244
21245        final Message msg = mHandler.obtainMessage(INIT_COPY);
21246        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21247        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21248                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21249                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21250                PackageManager.INSTALL_REASON_UNKNOWN);
21251        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21252        msg.obj = params;
21253
21254        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21255                System.identityHashCode(msg.obj));
21256        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21257                System.identityHashCode(msg.obj));
21258
21259        mHandler.sendMessage(msg);
21260    }
21261
21262    @Override
21263    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21264        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21265
21266        final int realMoveId = mNextMoveId.getAndIncrement();
21267        final Bundle extras = new Bundle();
21268        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21269        mMoveCallbacks.notifyCreated(realMoveId, extras);
21270
21271        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21272            @Override
21273            public void onCreated(int moveId, Bundle extras) {
21274                // Ignored
21275            }
21276
21277            @Override
21278            public void onStatusChanged(int moveId, int status, long estMillis) {
21279                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21280            }
21281        };
21282
21283        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21284        storage.setPrimaryStorageUuid(volumeUuid, callback);
21285        return realMoveId;
21286    }
21287
21288    @Override
21289    public int getMoveStatus(int moveId) {
21290        mContext.enforceCallingOrSelfPermission(
21291                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21292        return mMoveCallbacks.mLastStatus.get(moveId);
21293    }
21294
21295    @Override
21296    public void registerMoveCallback(IPackageMoveObserver callback) {
21297        mContext.enforceCallingOrSelfPermission(
21298                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21299        mMoveCallbacks.register(callback);
21300    }
21301
21302    @Override
21303    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21304        mContext.enforceCallingOrSelfPermission(
21305                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21306        mMoveCallbacks.unregister(callback);
21307    }
21308
21309    @Override
21310    public boolean setInstallLocation(int loc) {
21311        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21312                null);
21313        if (getInstallLocation() == loc) {
21314            return true;
21315        }
21316        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21317                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21318            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21319                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21320            return true;
21321        }
21322        return false;
21323   }
21324
21325    @Override
21326    public int getInstallLocation() {
21327        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21328                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21329                PackageHelper.APP_INSTALL_AUTO);
21330    }
21331
21332    /** Called by UserManagerService */
21333    void cleanUpUser(UserManagerService userManager, int userHandle) {
21334        synchronized (mPackages) {
21335            mDirtyUsers.remove(userHandle);
21336            mUserNeedsBadging.delete(userHandle);
21337            mSettings.removeUserLPw(userHandle);
21338            mPendingBroadcasts.remove(userHandle);
21339            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21340            removeUnusedPackagesLPw(userManager, userHandle);
21341        }
21342    }
21343
21344    /**
21345     * We're removing userHandle and would like to remove any downloaded packages
21346     * that are no longer in use by any other user.
21347     * @param userHandle the user being removed
21348     */
21349    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21350        final boolean DEBUG_CLEAN_APKS = false;
21351        int [] users = userManager.getUserIds();
21352        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21353        while (psit.hasNext()) {
21354            PackageSetting ps = psit.next();
21355            if (ps.pkg == null) {
21356                continue;
21357            }
21358            final String packageName = ps.pkg.packageName;
21359            // Skip over if system app
21360            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21361                continue;
21362            }
21363            if (DEBUG_CLEAN_APKS) {
21364                Slog.i(TAG, "Checking package " + packageName);
21365            }
21366            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21367            if (keep) {
21368                if (DEBUG_CLEAN_APKS) {
21369                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21370                }
21371            } else {
21372                for (int i = 0; i < users.length; i++) {
21373                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21374                        keep = true;
21375                        if (DEBUG_CLEAN_APKS) {
21376                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21377                                    + users[i]);
21378                        }
21379                        break;
21380                    }
21381                }
21382            }
21383            if (!keep) {
21384                if (DEBUG_CLEAN_APKS) {
21385                    Slog.i(TAG, "  Removing package " + packageName);
21386                }
21387                mHandler.post(new Runnable() {
21388                    public void run() {
21389                        deletePackageX(packageName, userHandle, 0);
21390                    } //end run
21391                });
21392            }
21393        }
21394    }
21395
21396    /** Called by UserManagerService */
21397    void createNewUser(int userId, String[] disallowedPackages) {
21398        synchronized (mInstallLock) {
21399            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21400        }
21401        synchronized (mPackages) {
21402            scheduleWritePackageRestrictionsLocked(userId);
21403            scheduleWritePackageListLocked(userId);
21404            applyFactoryDefaultBrowserLPw(userId);
21405            primeDomainVerificationsLPw(userId);
21406        }
21407    }
21408
21409    void onNewUserCreated(final int userId) {
21410        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21411        // If permission review for legacy apps is required, we represent
21412        // dagerous permissions for such apps as always granted runtime
21413        // permissions to keep per user flag state whether review is needed.
21414        // Hence, if a new user is added we have to propagate dangerous
21415        // permission grants for these legacy apps.
21416        if (mPermissionReviewRequired) {
21417            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21418                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21419        }
21420    }
21421
21422    @Override
21423    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21424        mContext.enforceCallingOrSelfPermission(
21425                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21426                "Only package verification agents can read the verifier device identity");
21427
21428        synchronized (mPackages) {
21429            return mSettings.getVerifierDeviceIdentityLPw();
21430        }
21431    }
21432
21433    @Override
21434    public void setPermissionEnforced(String permission, boolean enforced) {
21435        // TODO: Now that we no longer change GID for storage, this should to away.
21436        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21437                "setPermissionEnforced");
21438        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21439            synchronized (mPackages) {
21440                if (mSettings.mReadExternalStorageEnforced == null
21441                        || mSettings.mReadExternalStorageEnforced != enforced) {
21442                    mSettings.mReadExternalStorageEnforced = enforced;
21443                    mSettings.writeLPr();
21444                }
21445            }
21446            // kill any non-foreground processes so we restart them and
21447            // grant/revoke the GID.
21448            final IActivityManager am = ActivityManager.getService();
21449            if (am != null) {
21450                final long token = Binder.clearCallingIdentity();
21451                try {
21452                    am.killProcessesBelowForeground("setPermissionEnforcement");
21453                } catch (RemoteException e) {
21454                } finally {
21455                    Binder.restoreCallingIdentity(token);
21456                }
21457            }
21458        } else {
21459            throw new IllegalArgumentException("No selective enforcement for " + permission);
21460        }
21461    }
21462
21463    @Override
21464    @Deprecated
21465    public boolean isPermissionEnforced(String permission) {
21466        return true;
21467    }
21468
21469    @Override
21470    public boolean isStorageLow() {
21471        final long token = Binder.clearCallingIdentity();
21472        try {
21473            final DeviceStorageMonitorInternal
21474                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21475            if (dsm != null) {
21476                return dsm.isMemoryLow();
21477            } else {
21478                return false;
21479            }
21480        } finally {
21481            Binder.restoreCallingIdentity(token);
21482        }
21483    }
21484
21485    @Override
21486    public IPackageInstaller getPackageInstaller() {
21487        return mInstallerService;
21488    }
21489
21490    private boolean userNeedsBadging(int userId) {
21491        int index = mUserNeedsBadging.indexOfKey(userId);
21492        if (index < 0) {
21493            final UserInfo userInfo;
21494            final long token = Binder.clearCallingIdentity();
21495            try {
21496                userInfo = sUserManager.getUserInfo(userId);
21497            } finally {
21498                Binder.restoreCallingIdentity(token);
21499            }
21500            final boolean b;
21501            if (userInfo != null && userInfo.isManagedProfile()) {
21502                b = true;
21503            } else {
21504                b = false;
21505            }
21506            mUserNeedsBadging.put(userId, b);
21507            return b;
21508        }
21509        return mUserNeedsBadging.valueAt(index);
21510    }
21511
21512    @Override
21513    public KeySet getKeySetByAlias(String packageName, String alias) {
21514        if (packageName == null || alias == null) {
21515            return null;
21516        }
21517        synchronized(mPackages) {
21518            final PackageParser.Package pkg = mPackages.get(packageName);
21519            if (pkg == null) {
21520                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21521                throw new IllegalArgumentException("Unknown package: " + packageName);
21522            }
21523            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21524            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21525        }
21526    }
21527
21528    @Override
21529    public KeySet getSigningKeySet(String packageName) {
21530        if (packageName == null) {
21531            return null;
21532        }
21533        synchronized(mPackages) {
21534            final PackageParser.Package pkg = mPackages.get(packageName);
21535            if (pkg == null) {
21536                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21537                throw new IllegalArgumentException("Unknown package: " + packageName);
21538            }
21539            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21540                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21541                throw new SecurityException("May not access signing KeySet of other apps.");
21542            }
21543            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21544            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21545        }
21546    }
21547
21548    @Override
21549    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21550        if (packageName == null || ks == null) {
21551            return false;
21552        }
21553        synchronized(mPackages) {
21554            final PackageParser.Package pkg = mPackages.get(packageName);
21555            if (pkg == null) {
21556                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21557                throw new IllegalArgumentException("Unknown package: " + packageName);
21558            }
21559            IBinder ksh = ks.getToken();
21560            if (ksh instanceof KeySetHandle) {
21561                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21562                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21563            }
21564            return false;
21565        }
21566    }
21567
21568    @Override
21569    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21570        if (packageName == null || ks == null) {
21571            return false;
21572        }
21573        synchronized(mPackages) {
21574            final PackageParser.Package pkg = mPackages.get(packageName);
21575            if (pkg == null) {
21576                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21577                throw new IllegalArgumentException("Unknown package: " + packageName);
21578            }
21579            IBinder ksh = ks.getToken();
21580            if (ksh instanceof KeySetHandle) {
21581                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21582                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21583            }
21584            return false;
21585        }
21586    }
21587
21588    private void deletePackageIfUnusedLPr(final String packageName) {
21589        PackageSetting ps = mSettings.mPackages.get(packageName);
21590        if (ps == null) {
21591            return;
21592        }
21593        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21594            // TODO Implement atomic delete if package is unused
21595            // It is currently possible that the package will be deleted even if it is installed
21596            // after this method returns.
21597            mHandler.post(new Runnable() {
21598                public void run() {
21599                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21600                }
21601            });
21602        }
21603    }
21604
21605    /**
21606     * Check and throw if the given before/after packages would be considered a
21607     * downgrade.
21608     */
21609    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21610            throws PackageManagerException {
21611        if (after.versionCode < before.mVersionCode) {
21612            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21613                    "Update version code " + after.versionCode + " is older than current "
21614                    + before.mVersionCode);
21615        } else if (after.versionCode == before.mVersionCode) {
21616            if (after.baseRevisionCode < before.baseRevisionCode) {
21617                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21618                        "Update base revision code " + after.baseRevisionCode
21619                        + " is older than current " + before.baseRevisionCode);
21620            }
21621
21622            if (!ArrayUtils.isEmpty(after.splitNames)) {
21623                for (int i = 0; i < after.splitNames.length; i++) {
21624                    final String splitName = after.splitNames[i];
21625                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21626                    if (j != -1) {
21627                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21628                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21629                                    "Update split " + splitName + " revision code "
21630                                    + after.splitRevisionCodes[i] + " is older than current "
21631                                    + before.splitRevisionCodes[j]);
21632                        }
21633                    }
21634                }
21635            }
21636        }
21637    }
21638
21639    private static class MoveCallbacks extends Handler {
21640        private static final int MSG_CREATED = 1;
21641        private static final int MSG_STATUS_CHANGED = 2;
21642
21643        private final RemoteCallbackList<IPackageMoveObserver>
21644                mCallbacks = new RemoteCallbackList<>();
21645
21646        private final SparseIntArray mLastStatus = new SparseIntArray();
21647
21648        public MoveCallbacks(Looper looper) {
21649            super(looper);
21650        }
21651
21652        public void register(IPackageMoveObserver callback) {
21653            mCallbacks.register(callback);
21654        }
21655
21656        public void unregister(IPackageMoveObserver callback) {
21657            mCallbacks.unregister(callback);
21658        }
21659
21660        @Override
21661        public void handleMessage(Message msg) {
21662            final SomeArgs args = (SomeArgs) msg.obj;
21663            final int n = mCallbacks.beginBroadcast();
21664            for (int i = 0; i < n; i++) {
21665                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21666                try {
21667                    invokeCallback(callback, msg.what, args);
21668                } catch (RemoteException ignored) {
21669                }
21670            }
21671            mCallbacks.finishBroadcast();
21672            args.recycle();
21673        }
21674
21675        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21676                throws RemoteException {
21677            switch (what) {
21678                case MSG_CREATED: {
21679                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21680                    break;
21681                }
21682                case MSG_STATUS_CHANGED: {
21683                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21684                    break;
21685                }
21686            }
21687        }
21688
21689        private void notifyCreated(int moveId, Bundle extras) {
21690            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21691
21692            final SomeArgs args = SomeArgs.obtain();
21693            args.argi1 = moveId;
21694            args.arg2 = extras;
21695            obtainMessage(MSG_CREATED, args).sendToTarget();
21696        }
21697
21698        private void notifyStatusChanged(int moveId, int status) {
21699            notifyStatusChanged(moveId, status, -1);
21700        }
21701
21702        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21703            Slog.v(TAG, "Move " + moveId + " status " + status);
21704
21705            final SomeArgs args = SomeArgs.obtain();
21706            args.argi1 = moveId;
21707            args.argi2 = status;
21708            args.arg3 = estMillis;
21709            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21710
21711            synchronized (mLastStatus) {
21712                mLastStatus.put(moveId, status);
21713            }
21714        }
21715    }
21716
21717    private final static class OnPermissionChangeListeners extends Handler {
21718        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21719
21720        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21721                new RemoteCallbackList<>();
21722
21723        public OnPermissionChangeListeners(Looper looper) {
21724            super(looper);
21725        }
21726
21727        @Override
21728        public void handleMessage(Message msg) {
21729            switch (msg.what) {
21730                case MSG_ON_PERMISSIONS_CHANGED: {
21731                    final int uid = msg.arg1;
21732                    handleOnPermissionsChanged(uid);
21733                } break;
21734            }
21735        }
21736
21737        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21738            mPermissionListeners.register(listener);
21739
21740        }
21741
21742        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21743            mPermissionListeners.unregister(listener);
21744        }
21745
21746        public void onPermissionsChanged(int uid) {
21747            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21748                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21749            }
21750        }
21751
21752        private void handleOnPermissionsChanged(int uid) {
21753            final int count = mPermissionListeners.beginBroadcast();
21754            try {
21755                for (int i = 0; i < count; i++) {
21756                    IOnPermissionsChangeListener callback = mPermissionListeners
21757                            .getBroadcastItem(i);
21758                    try {
21759                        callback.onPermissionsChanged(uid);
21760                    } catch (RemoteException e) {
21761                        Log.e(TAG, "Permission listener is dead", e);
21762                    }
21763                }
21764            } finally {
21765                mPermissionListeners.finishBroadcast();
21766            }
21767        }
21768    }
21769
21770    private class PackageManagerInternalImpl extends PackageManagerInternal {
21771        @Override
21772        public void setLocationPackagesProvider(PackagesProvider provider) {
21773            synchronized (mPackages) {
21774                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21775            }
21776        }
21777
21778        @Override
21779        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21780            synchronized (mPackages) {
21781                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21782            }
21783        }
21784
21785        @Override
21786        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21787            synchronized (mPackages) {
21788                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21789            }
21790        }
21791
21792        @Override
21793        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21794            synchronized (mPackages) {
21795                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21796            }
21797        }
21798
21799        @Override
21800        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21801            synchronized (mPackages) {
21802                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21803            }
21804        }
21805
21806        @Override
21807        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21808            synchronized (mPackages) {
21809                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21810            }
21811        }
21812
21813        @Override
21814        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21815            synchronized (mPackages) {
21816                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21817                        packageName, userId);
21818            }
21819        }
21820
21821        @Override
21822        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21823            synchronized (mPackages) {
21824                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21825                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21826                        packageName, userId);
21827            }
21828        }
21829
21830        @Override
21831        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21832            synchronized (mPackages) {
21833                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21834                        packageName, userId);
21835            }
21836        }
21837
21838        @Override
21839        public void setKeepUninstalledPackages(final List<String> packageList) {
21840            Preconditions.checkNotNull(packageList);
21841            List<String> removedFromList = null;
21842            synchronized (mPackages) {
21843                if (mKeepUninstalledPackages != null) {
21844                    final int packagesCount = mKeepUninstalledPackages.size();
21845                    for (int i = 0; i < packagesCount; i++) {
21846                        String oldPackage = mKeepUninstalledPackages.get(i);
21847                        if (packageList != null && packageList.contains(oldPackage)) {
21848                            continue;
21849                        }
21850                        if (removedFromList == null) {
21851                            removedFromList = new ArrayList<>();
21852                        }
21853                        removedFromList.add(oldPackage);
21854                    }
21855                }
21856                mKeepUninstalledPackages = new ArrayList<>(packageList);
21857                if (removedFromList != null) {
21858                    final int removedCount = removedFromList.size();
21859                    for (int i = 0; i < removedCount; i++) {
21860                        deletePackageIfUnusedLPr(removedFromList.get(i));
21861                    }
21862                }
21863            }
21864        }
21865
21866        @Override
21867        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21868            synchronized (mPackages) {
21869                // If we do not support permission review, done.
21870                if (!mPermissionReviewRequired) {
21871                    return false;
21872                }
21873
21874                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21875                if (packageSetting == null) {
21876                    return false;
21877                }
21878
21879                // Permission review applies only to apps not supporting the new permission model.
21880                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21881                    return false;
21882                }
21883
21884                // Legacy apps have the permission and get user consent on launch.
21885                PermissionsState permissionsState = packageSetting.getPermissionsState();
21886                return permissionsState.isPermissionReviewRequired(userId);
21887            }
21888        }
21889
21890        @Override
21891        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21892            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21893        }
21894
21895        @Override
21896        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21897                int userId) {
21898            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21899        }
21900
21901        @Override
21902        public void setDeviceAndProfileOwnerPackages(
21903                int deviceOwnerUserId, String deviceOwnerPackage,
21904                SparseArray<String> profileOwnerPackages) {
21905            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21906                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21907        }
21908
21909        @Override
21910        public boolean isPackageDataProtected(int userId, String packageName) {
21911            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21912        }
21913
21914        @Override
21915        public boolean isPackageEphemeral(int userId, String packageName) {
21916            synchronized (mPackages) {
21917                PackageParser.Package p = mPackages.get(packageName);
21918                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21919            }
21920        }
21921
21922        @Override
21923        public boolean wasPackageEverLaunched(String packageName, int userId) {
21924            synchronized (mPackages) {
21925                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21926            }
21927        }
21928
21929        @Override
21930        public void grantRuntimePermission(String packageName, String name, int userId,
21931                boolean overridePolicy) {
21932            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21933                    overridePolicy);
21934        }
21935
21936        @Override
21937        public void revokeRuntimePermission(String packageName, String name, int userId,
21938                boolean overridePolicy) {
21939            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21940                    overridePolicy);
21941        }
21942
21943        @Override
21944        public String getNameForUid(int uid) {
21945            return PackageManagerService.this.getNameForUid(uid);
21946        }
21947
21948        @Override
21949        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21950                Intent origIntent, String resolvedType, Intent launchIntent,
21951                String callingPackage, int userId) {
21952            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21953                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21954        }
21955
21956        public String getSetupWizardPackageName() {
21957            return mSetupWizardPackage;
21958        }
21959    }
21960
21961    @Override
21962    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21963        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21964        synchronized (mPackages) {
21965            final long identity = Binder.clearCallingIdentity();
21966            try {
21967                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21968                        packageNames, userId);
21969            } finally {
21970                Binder.restoreCallingIdentity(identity);
21971            }
21972        }
21973    }
21974
21975    private static void enforceSystemOrPhoneCaller(String tag) {
21976        int callingUid = Binder.getCallingUid();
21977        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21978            throw new SecurityException(
21979                    "Cannot call " + tag + " from UID " + callingUid);
21980        }
21981    }
21982
21983    boolean isHistoricalPackageUsageAvailable() {
21984        return mPackageUsage.isHistoricalPackageUsageAvailable();
21985    }
21986
21987    /**
21988     * Return a <b>copy</b> of the collection of packages known to the package manager.
21989     * @return A copy of the values of mPackages.
21990     */
21991    Collection<PackageParser.Package> getPackages() {
21992        synchronized (mPackages) {
21993            return new ArrayList<>(mPackages.values());
21994        }
21995    }
21996
21997    /**
21998     * Logs process start information (including base APK hash) to the security log.
21999     * @hide
22000     */
22001    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22002            String apkFile, int pid) {
22003        if (!SecurityLog.isLoggingEnabled()) {
22004            return;
22005        }
22006        Bundle data = new Bundle();
22007        data.putLong("startTimestamp", System.currentTimeMillis());
22008        data.putString("processName", processName);
22009        data.putInt("uid", uid);
22010        data.putString("seinfo", seinfo);
22011        data.putString("apkFile", apkFile);
22012        data.putInt("pid", pid);
22013        Message msg = mProcessLoggingHandler.obtainMessage(
22014                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22015        msg.setData(data);
22016        mProcessLoggingHandler.sendMessage(msg);
22017    }
22018
22019    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22020        return mCompilerStats.getPackageStats(pkgName);
22021    }
22022
22023    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22024        return getOrCreateCompilerPackageStats(pkg.packageName);
22025    }
22026
22027    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22028        return mCompilerStats.getOrCreatePackageStats(pkgName);
22029    }
22030
22031    public void deleteCompilerPackageStats(String pkgName) {
22032        mCompilerStats.deletePackageStats(pkgName);
22033    }
22034
22035    @Override
22036    public int getInstallReason(String packageName, int userId) {
22037        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22038                true /* requireFullPermission */, false /* checkShell */,
22039                "get install reason");
22040        synchronized (mPackages) {
22041            final PackageSetting ps = mSettings.mPackages.get(packageName);
22042            if (ps != null) {
22043                return ps.getInstallReason(userId);
22044            }
22045        }
22046        return PackageManager.INSTALL_REASON_UNKNOWN;
22047    }
22048}
22049