PackageManagerService.java revision 6130fb741c86d7d4f0f86e3a875c3eca1fe8aa51
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 flags when being used to request {@link ResolveInfo}.
3749     */
3750    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3751        // Safe mode means we shouldn't match any third-party components
3752        if (mSafeMode) {
3753            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3754        }
3755        final int callingUid = Binder.getCallingUid();
3756        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3757            // The system sees all components
3758            flags |= PackageManager.MATCH_EPHEMERAL;
3759        } else if (getEphemeralPackageName(callingUid) != null) {
3760            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3761            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3762            flags |= PackageManager.MATCH_EPHEMERAL;
3763        } else {
3764            // Otherwise, prevent leaking ephemeral components
3765            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3766            flags &= ~PackageManager.MATCH_EPHEMERAL;
3767        }
3768        return updateFlagsForComponent(flags, userId, cookie);
3769    }
3770
3771    @Override
3772    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3773        if (!sUserManager.exists(userId)) return null;
3774        flags = updateFlagsForComponent(flags, userId, component);
3775        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3776                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3777        synchronized (mPackages) {
3778            PackageParser.Activity a = mActivities.mActivities.get(component);
3779
3780            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3781            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3783                if (ps == null) return null;
3784                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3785                        userId);
3786            }
3787            if (mResolveComponentName.equals(component)) {
3788                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3789                        new PackageUserState(), userId);
3790            }
3791        }
3792        return null;
3793    }
3794
3795    @Override
3796    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3797            String resolvedType) {
3798        synchronized (mPackages) {
3799            if (component.equals(mResolveComponentName)) {
3800                // The resolver supports EVERYTHING!
3801                return true;
3802            }
3803            PackageParser.Activity a = mActivities.mActivities.get(component);
3804            if (a == null) {
3805                return false;
3806            }
3807            for (int i=0; i<a.intents.size(); i++) {
3808                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3809                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3810                    return true;
3811                }
3812            }
3813            return false;
3814        }
3815    }
3816
3817    @Override
3818    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3819        if (!sUserManager.exists(userId)) return null;
3820        flags = updateFlagsForComponent(flags, userId, component);
3821        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3822                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3823        synchronized (mPackages) {
3824            PackageParser.Activity a = mReceivers.mActivities.get(component);
3825            if (DEBUG_PACKAGE_INFO) Log.v(
3826                TAG, "getReceiverInfo " + component + ": " + a);
3827            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3828                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3829                if (ps == null) return null;
3830                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3831                        userId);
3832            }
3833        }
3834        return null;
3835    }
3836
3837    @Override
3838    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3839        if (!sUserManager.exists(userId)) return null;
3840        flags = updateFlagsForComponent(flags, userId, component);
3841        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3842                false /* requireFullPermission */, false /* checkShell */, "get service info");
3843        synchronized (mPackages) {
3844            PackageParser.Service s = mServices.mServices.get(component);
3845            if (DEBUG_PACKAGE_INFO) Log.v(
3846                TAG, "getServiceInfo " + component + ": " + s);
3847            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3848                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3849                if (ps == null) return null;
3850                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3851                        userId);
3852            }
3853        }
3854        return null;
3855    }
3856
3857    @Override
3858    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3859        if (!sUserManager.exists(userId)) return null;
3860        flags = updateFlagsForComponent(flags, userId, component);
3861        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3862                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3863        synchronized (mPackages) {
3864            PackageParser.Provider p = mProviders.mProviders.get(component);
3865            if (DEBUG_PACKAGE_INFO) Log.v(
3866                TAG, "getProviderInfo " + component + ": " + p);
3867            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3868                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3869                if (ps == null) return null;
3870                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3871                        userId);
3872            }
3873        }
3874        return null;
3875    }
3876
3877    @Override
3878    public String[] getSystemSharedLibraryNames() {
3879        Set<String> libSet;
3880        synchronized (mPackages) {
3881            libSet = mSharedLibraries.keySet();
3882            int size = libSet.size();
3883            if (size > 0) {
3884                String[] libs = new String[size];
3885                libSet.toArray(libs);
3886                return libs;
3887            }
3888        }
3889        return null;
3890    }
3891
3892    @Override
3893    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3894        synchronized (mPackages) {
3895            return mServicesSystemSharedLibraryPackageName;
3896        }
3897    }
3898
3899    @Override
3900    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3901        synchronized (mPackages) {
3902            return mSharedSystemSharedLibraryPackageName;
3903        }
3904    }
3905
3906    @Override
3907    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3908        synchronized (mPackages) {
3909            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3910
3911            final FeatureInfo fi = new FeatureInfo();
3912            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3913                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3914            res.add(fi);
3915
3916            return new ParceledListSlice<>(res);
3917        }
3918    }
3919
3920    @Override
3921    public boolean hasSystemFeature(String name, int version) {
3922        synchronized (mPackages) {
3923            final FeatureInfo feat = mAvailableFeatures.get(name);
3924            if (feat == null) {
3925                return false;
3926            } else {
3927                return feat.version >= version;
3928            }
3929        }
3930    }
3931
3932    @Override
3933    public int checkPermission(String permName, String pkgName, int userId) {
3934        if (!sUserManager.exists(userId)) {
3935            return PackageManager.PERMISSION_DENIED;
3936        }
3937
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(pkgName);
3940            if (p != null && p.mExtras != null) {
3941                final PackageSetting ps = (PackageSetting) p.mExtras;
3942                final PermissionsState permissionsState = ps.getPermissionsState();
3943                if (permissionsState.hasPermission(permName, userId)) {
3944                    return PackageManager.PERMISSION_GRANTED;
3945                }
3946                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3947                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3948                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3949                    return PackageManager.PERMISSION_GRANTED;
3950                }
3951            }
3952        }
3953
3954        return PackageManager.PERMISSION_DENIED;
3955    }
3956
3957    @Override
3958    public int checkUidPermission(String permName, int uid) {
3959        final int userId = UserHandle.getUserId(uid);
3960
3961        if (!sUserManager.exists(userId)) {
3962            return PackageManager.PERMISSION_DENIED;
3963        }
3964
3965        synchronized (mPackages) {
3966            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3967            if (obj != null) {
3968                final SettingBase ps = (SettingBase) obj;
3969                final PermissionsState permissionsState = ps.getPermissionsState();
3970                if (permissionsState.hasPermission(permName, userId)) {
3971                    return PackageManager.PERMISSION_GRANTED;
3972                }
3973                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3974                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3975                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3976                    return PackageManager.PERMISSION_GRANTED;
3977                }
3978            } else {
3979                ArraySet<String> perms = mSystemPermissions.get(uid);
3980                if (perms != null) {
3981                    if (perms.contains(permName)) {
3982                        return PackageManager.PERMISSION_GRANTED;
3983                    }
3984                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3985                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3986                        return PackageManager.PERMISSION_GRANTED;
3987                    }
3988                }
3989            }
3990        }
3991
3992        return PackageManager.PERMISSION_DENIED;
3993    }
3994
3995    @Override
3996    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3997        if (UserHandle.getCallingUserId() != userId) {
3998            mContext.enforceCallingPermission(
3999                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4000                    "isPermissionRevokedByPolicy for user " + userId);
4001        }
4002
4003        if (checkPermission(permission, packageName, userId)
4004                == PackageManager.PERMISSION_GRANTED) {
4005            return false;
4006        }
4007
4008        final long identity = Binder.clearCallingIdentity();
4009        try {
4010            final int flags = getPermissionFlags(permission, packageName, userId);
4011            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4012        } finally {
4013            Binder.restoreCallingIdentity(identity);
4014        }
4015    }
4016
4017    @Override
4018    public String getPermissionControllerPackageName() {
4019        synchronized (mPackages) {
4020            return mRequiredInstallerPackage;
4021        }
4022    }
4023
4024    /**
4025     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4026     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4027     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4028     * @param message the message to log on security exception
4029     */
4030    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4031            boolean checkShell, String message) {
4032        if (userId < 0) {
4033            throw new IllegalArgumentException("Invalid userId " + userId);
4034        }
4035        if (checkShell) {
4036            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4037        }
4038        if (userId == UserHandle.getUserId(callingUid)) return;
4039        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4040            if (requireFullPermission) {
4041                mContext.enforceCallingOrSelfPermission(
4042                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4043            } else {
4044                try {
4045                    mContext.enforceCallingOrSelfPermission(
4046                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4047                } catch (SecurityException se) {
4048                    mContext.enforceCallingOrSelfPermission(
4049                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4050                }
4051            }
4052        }
4053    }
4054
4055    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4056        if (callingUid == Process.SHELL_UID) {
4057            if (userHandle >= 0
4058                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4059                throw new SecurityException("Shell does not have permission to access user "
4060                        + userHandle);
4061            } else if (userHandle < 0) {
4062                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4063                        + Debug.getCallers(3));
4064            }
4065        }
4066    }
4067
4068    private BasePermission findPermissionTreeLP(String permName) {
4069        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4070            if (permName.startsWith(bp.name) &&
4071                    permName.length() > bp.name.length() &&
4072                    permName.charAt(bp.name.length()) == '.') {
4073                return bp;
4074            }
4075        }
4076        return null;
4077    }
4078
4079    private BasePermission checkPermissionTreeLP(String permName) {
4080        if (permName != null) {
4081            BasePermission bp = findPermissionTreeLP(permName);
4082            if (bp != null) {
4083                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4084                    return bp;
4085                }
4086                throw new SecurityException("Calling uid "
4087                        + Binder.getCallingUid()
4088                        + " is not allowed to add to permission tree "
4089                        + bp.name + " owned by uid " + bp.uid);
4090            }
4091        }
4092        throw new SecurityException("No permission tree found for " + permName);
4093    }
4094
4095    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4096        if (s1 == null) {
4097            return s2 == null;
4098        }
4099        if (s2 == null) {
4100            return false;
4101        }
4102        if (s1.getClass() != s2.getClass()) {
4103            return false;
4104        }
4105        return s1.equals(s2);
4106    }
4107
4108    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4109        if (pi1.icon != pi2.icon) return false;
4110        if (pi1.logo != pi2.logo) return false;
4111        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4112        if (!compareStrings(pi1.name, pi2.name)) return false;
4113        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4114        // We'll take care of setting this one.
4115        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4116        // These are not currently stored in settings.
4117        //if (!compareStrings(pi1.group, pi2.group)) return false;
4118        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4119        //if (pi1.labelRes != pi2.labelRes) return false;
4120        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4121        return true;
4122    }
4123
4124    int permissionInfoFootprint(PermissionInfo info) {
4125        int size = info.name.length();
4126        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4127        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4128        return size;
4129    }
4130
4131    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4132        int size = 0;
4133        for (BasePermission perm : mSettings.mPermissions.values()) {
4134            if (perm.uid == tree.uid) {
4135                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4136            }
4137        }
4138        return size;
4139    }
4140
4141    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4142        // We calculate the max size of permissions defined by this uid and throw
4143        // if that plus the size of 'info' would exceed our stated maximum.
4144        if (tree.uid != Process.SYSTEM_UID) {
4145            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4146            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4147                throw new SecurityException("Permission tree size cap exceeded");
4148            }
4149        }
4150    }
4151
4152    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4153        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4154            throw new SecurityException("Label must be specified in permission");
4155        }
4156        BasePermission tree = checkPermissionTreeLP(info.name);
4157        BasePermission bp = mSettings.mPermissions.get(info.name);
4158        boolean added = bp == null;
4159        boolean changed = true;
4160        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4161        if (added) {
4162            enforcePermissionCapLocked(info, tree);
4163            bp = new BasePermission(info.name, tree.sourcePackage,
4164                    BasePermission.TYPE_DYNAMIC);
4165        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4166            throw new SecurityException(
4167                    "Not allowed to modify non-dynamic permission "
4168                    + info.name);
4169        } else {
4170            if (bp.protectionLevel == fixedLevel
4171                    && bp.perm.owner.equals(tree.perm.owner)
4172                    && bp.uid == tree.uid
4173                    && comparePermissionInfos(bp.perm.info, info)) {
4174                changed = false;
4175            }
4176        }
4177        bp.protectionLevel = fixedLevel;
4178        info = new PermissionInfo(info);
4179        info.protectionLevel = fixedLevel;
4180        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4181        bp.perm.info.packageName = tree.perm.info.packageName;
4182        bp.uid = tree.uid;
4183        if (added) {
4184            mSettings.mPermissions.put(info.name, bp);
4185        }
4186        if (changed) {
4187            if (!async) {
4188                mSettings.writeLPr();
4189            } else {
4190                scheduleWriteSettingsLocked();
4191            }
4192        }
4193        return added;
4194    }
4195
4196    @Override
4197    public boolean addPermission(PermissionInfo info) {
4198        synchronized (mPackages) {
4199            return addPermissionLocked(info, false);
4200        }
4201    }
4202
4203    @Override
4204    public boolean addPermissionAsync(PermissionInfo info) {
4205        synchronized (mPackages) {
4206            return addPermissionLocked(info, true);
4207        }
4208    }
4209
4210    @Override
4211    public void removePermission(String name) {
4212        synchronized (mPackages) {
4213            checkPermissionTreeLP(name);
4214            BasePermission bp = mSettings.mPermissions.get(name);
4215            if (bp != null) {
4216                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4217                    throw new SecurityException(
4218                            "Not allowed to modify non-dynamic permission "
4219                            + name);
4220                }
4221                mSettings.mPermissions.remove(name);
4222                mSettings.writeLPr();
4223            }
4224        }
4225    }
4226
4227    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4228            BasePermission bp) {
4229        int index = pkg.requestedPermissions.indexOf(bp.name);
4230        if (index == -1) {
4231            throw new SecurityException("Package " + pkg.packageName
4232                    + " has not requested permission " + bp.name);
4233        }
4234        if (!bp.isRuntime() && !bp.isDevelopment()) {
4235            throw new SecurityException("Permission " + bp.name
4236                    + " is not a changeable permission type");
4237        }
4238    }
4239
4240    @Override
4241    public void grantRuntimePermission(String packageName, String name, final int userId) {
4242        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4243    }
4244
4245    private void grantRuntimePermission(String packageName, String name, final int userId,
4246            boolean overridePolicy) {
4247        if (!sUserManager.exists(userId)) {
4248            Log.e(TAG, "No such user:" + userId);
4249            return;
4250        }
4251
4252        mContext.enforceCallingOrSelfPermission(
4253                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4254                "grantRuntimePermission");
4255
4256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4257                true /* requireFullPermission */, true /* checkShell */,
4258                "grantRuntimePermission");
4259
4260        final int uid;
4261        final SettingBase sb;
4262
4263        synchronized (mPackages) {
4264            final PackageParser.Package pkg = mPackages.get(packageName);
4265            if (pkg == null) {
4266                throw new IllegalArgumentException("Unknown package: " + packageName);
4267            }
4268
4269            final BasePermission bp = mSettings.mPermissions.get(name);
4270            if (bp == null) {
4271                throw new IllegalArgumentException("Unknown permission: " + name);
4272            }
4273
4274            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4275
4276            // If a permission review is required for legacy apps we represent
4277            // their permissions as always granted runtime ones since we need
4278            // to keep the review required permission flag per user while an
4279            // install permission's state is shared across all users.
4280            if (mPermissionReviewRequired
4281                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4282                    && bp.isRuntime()) {
4283                return;
4284            }
4285
4286            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4287            sb = (SettingBase) pkg.mExtras;
4288            if (sb == null) {
4289                throw new IllegalArgumentException("Unknown package: " + packageName);
4290            }
4291
4292            final PermissionsState permissionsState = sb.getPermissionsState();
4293
4294            final int flags = permissionsState.getPermissionFlags(name, userId);
4295            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4296                throw new SecurityException("Cannot grant system fixed permission "
4297                        + name + " for package " + packageName);
4298            }
4299            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4300                throw new SecurityException("Cannot grant policy fixed permission "
4301                        + name + " for package " + packageName);
4302            }
4303
4304            if (bp.isDevelopment()) {
4305                // Development permissions must be handled specially, since they are not
4306                // normal runtime permissions.  For now they apply to all users.
4307                if (permissionsState.grantInstallPermission(bp) !=
4308                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4309                    scheduleWriteSettingsLocked();
4310                }
4311                return;
4312            }
4313
4314            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4315                throw new SecurityException("Cannot grant non-ephemeral permission"
4316                        + name + " for package " + packageName);
4317            }
4318
4319            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4320                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4321                return;
4322            }
4323
4324            final int result = permissionsState.grantRuntimePermission(bp, userId);
4325            switch (result) {
4326                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4327                    return;
4328                }
4329
4330                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4331                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4332                    mHandler.post(new Runnable() {
4333                        @Override
4334                        public void run() {
4335                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4336                        }
4337                    });
4338                }
4339                break;
4340            }
4341
4342            if (bp.isRuntime()) {
4343                logPermissionGranted(mContext, name, packageName);
4344            }
4345
4346            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4347
4348            // Not critical if that is lost - app has to request again.
4349            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4350        }
4351
4352        // Only need to do this if user is initialized. Otherwise it's a new user
4353        // and there are no processes running as the user yet and there's no need
4354        // to make an expensive call to remount processes for the changed permissions.
4355        if (READ_EXTERNAL_STORAGE.equals(name)
4356                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4357            final long token = Binder.clearCallingIdentity();
4358            try {
4359                if (sUserManager.isInitialized(userId)) {
4360                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4361                            StorageManagerInternal.class);
4362                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4363                }
4364            } finally {
4365                Binder.restoreCallingIdentity(token);
4366            }
4367        }
4368    }
4369
4370    @Override
4371    public void revokeRuntimePermission(String packageName, String name, int userId) {
4372        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4373    }
4374
4375    private void revokeRuntimePermission(String packageName, String name, int userId,
4376            boolean overridePolicy) {
4377        if (!sUserManager.exists(userId)) {
4378            Log.e(TAG, "No such user:" + userId);
4379            return;
4380        }
4381
4382        mContext.enforceCallingOrSelfPermission(
4383                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4384                "revokeRuntimePermission");
4385
4386        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4387                true /* requireFullPermission */, true /* checkShell */,
4388                "revokeRuntimePermission");
4389
4390        final int appId;
4391
4392        synchronized (mPackages) {
4393            final PackageParser.Package pkg = mPackages.get(packageName);
4394            if (pkg == null) {
4395                throw new IllegalArgumentException("Unknown package: " + packageName);
4396            }
4397
4398            final BasePermission bp = mSettings.mPermissions.get(name);
4399            if (bp == null) {
4400                throw new IllegalArgumentException("Unknown permission: " + name);
4401            }
4402
4403            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4404
4405            // If a permission review is required for legacy apps we represent
4406            // their permissions as always granted runtime ones since we need
4407            // to keep the review required permission flag per user while an
4408            // install permission's state is shared across all users.
4409            if (mPermissionReviewRequired
4410                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4411                    && bp.isRuntime()) {
4412                return;
4413            }
4414
4415            SettingBase sb = (SettingBase) pkg.mExtras;
4416            if (sb == null) {
4417                throw new IllegalArgumentException("Unknown package: " + packageName);
4418            }
4419
4420            final PermissionsState permissionsState = sb.getPermissionsState();
4421
4422            final int flags = permissionsState.getPermissionFlags(name, userId);
4423            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4424                throw new SecurityException("Cannot revoke system fixed permission "
4425                        + name + " for package " + packageName);
4426            }
4427            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4428                throw new SecurityException("Cannot revoke policy fixed permission "
4429                        + name + " for package " + packageName);
4430            }
4431
4432            if (bp.isDevelopment()) {
4433                // Development permissions must be handled specially, since they are not
4434                // normal runtime permissions.  For now they apply to all users.
4435                if (permissionsState.revokeInstallPermission(bp) !=
4436                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4437                    scheduleWriteSettingsLocked();
4438                }
4439                return;
4440            }
4441
4442            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4443                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4444                return;
4445            }
4446
4447            if (bp.isRuntime()) {
4448                logPermissionRevoked(mContext, name, packageName);
4449            }
4450
4451            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4452
4453            // Critical, after this call app should never have the permission.
4454            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4455
4456            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4457        }
4458
4459        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4460    }
4461
4462    /**
4463     * Get the first event id for the permission.
4464     *
4465     * <p>There are four events for each permission: <ul>
4466     *     <li>Request permission: first id + 0</li>
4467     *     <li>Grant permission: first id + 1</li>
4468     *     <li>Request for permission denied: first id + 2</li>
4469     *     <li>Revoke permission: first id + 3</li>
4470     * </ul></p>
4471     *
4472     * @param name name of the permission
4473     *
4474     * @return The first event id for the permission
4475     */
4476    private static int getBaseEventId(@NonNull String name) {
4477        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4478
4479        if (eventIdIndex == -1) {
4480            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4481                    || "user".equals(Build.TYPE)) {
4482                Log.i(TAG, "Unknown permission " + name);
4483
4484                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4485            } else {
4486                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4487                //
4488                // Also update
4489                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4490                // - metrics_constants.proto
4491                throw new IllegalStateException("Unknown permission " + name);
4492            }
4493        }
4494
4495        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4496    }
4497
4498    /**
4499     * Log that a permission was revoked.
4500     *
4501     * @param context Context of the caller
4502     * @param name name of the permission
4503     * @param packageName package permission if for
4504     */
4505    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4506            @NonNull String packageName) {
4507        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4508    }
4509
4510    /**
4511     * Log that a permission request was granted.
4512     *
4513     * @param context Context of the caller
4514     * @param name name of the permission
4515     * @param packageName package permission if for
4516     */
4517    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4518            @NonNull String packageName) {
4519        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4520    }
4521
4522    @Override
4523    public void resetRuntimePermissions() {
4524        mContext.enforceCallingOrSelfPermission(
4525                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4526                "revokeRuntimePermission");
4527
4528        int callingUid = Binder.getCallingUid();
4529        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4530            mContext.enforceCallingOrSelfPermission(
4531                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4532                    "resetRuntimePermissions");
4533        }
4534
4535        synchronized (mPackages) {
4536            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4537            for (int userId : UserManagerService.getInstance().getUserIds()) {
4538                final int packageCount = mPackages.size();
4539                for (int i = 0; i < packageCount; i++) {
4540                    PackageParser.Package pkg = mPackages.valueAt(i);
4541                    if (!(pkg.mExtras instanceof PackageSetting)) {
4542                        continue;
4543                    }
4544                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4545                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4546                }
4547            }
4548        }
4549    }
4550
4551    @Override
4552    public int getPermissionFlags(String name, String packageName, int userId) {
4553        if (!sUserManager.exists(userId)) {
4554            return 0;
4555        }
4556
4557        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4558
4559        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4560                true /* requireFullPermission */, false /* checkShell */,
4561                "getPermissionFlags");
4562
4563        synchronized (mPackages) {
4564            final PackageParser.Package pkg = mPackages.get(packageName);
4565            if (pkg == null) {
4566                return 0;
4567            }
4568
4569            final BasePermission bp = mSettings.mPermissions.get(name);
4570            if (bp == null) {
4571                return 0;
4572            }
4573
4574            SettingBase sb = (SettingBase) pkg.mExtras;
4575            if (sb == null) {
4576                return 0;
4577            }
4578
4579            PermissionsState permissionsState = sb.getPermissionsState();
4580            return permissionsState.getPermissionFlags(name, userId);
4581        }
4582    }
4583
4584    @Override
4585    public void updatePermissionFlags(String name, String packageName, int flagMask,
4586            int flagValues, int userId) {
4587        if (!sUserManager.exists(userId)) {
4588            return;
4589        }
4590
4591        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4592
4593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4594                true /* requireFullPermission */, true /* checkShell */,
4595                "updatePermissionFlags");
4596
4597        // Only the system can change these flags and nothing else.
4598        if (getCallingUid() != Process.SYSTEM_UID) {
4599            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4600            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4601            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4602            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4603            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4604        }
4605
4606        synchronized (mPackages) {
4607            final PackageParser.Package pkg = mPackages.get(packageName);
4608            if (pkg == null) {
4609                throw new IllegalArgumentException("Unknown package: " + packageName);
4610            }
4611
4612            final BasePermission bp = mSettings.mPermissions.get(name);
4613            if (bp == null) {
4614                throw new IllegalArgumentException("Unknown permission: " + name);
4615            }
4616
4617            SettingBase sb = (SettingBase) pkg.mExtras;
4618            if (sb == null) {
4619                throw new IllegalArgumentException("Unknown package: " + packageName);
4620            }
4621
4622            PermissionsState permissionsState = sb.getPermissionsState();
4623
4624            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4625
4626            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4627                // Install and runtime permissions are stored in different places,
4628                // so figure out what permission changed and persist the change.
4629                if (permissionsState.getInstallPermissionState(name) != null) {
4630                    scheduleWriteSettingsLocked();
4631                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4632                        || hadState) {
4633                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4634                }
4635            }
4636        }
4637    }
4638
4639    /**
4640     * Update the permission flags for all packages and runtime permissions of a user in order
4641     * to allow device or profile owner to remove POLICY_FIXED.
4642     */
4643    @Override
4644    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4645        if (!sUserManager.exists(userId)) {
4646            return;
4647        }
4648
4649        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4650
4651        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4652                true /* requireFullPermission */, true /* checkShell */,
4653                "updatePermissionFlagsForAllApps");
4654
4655        // Only the system can change system fixed flags.
4656        if (getCallingUid() != Process.SYSTEM_UID) {
4657            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4658            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4659        }
4660
4661        synchronized (mPackages) {
4662            boolean changed = false;
4663            final int packageCount = mPackages.size();
4664            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4665                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4666                SettingBase sb = (SettingBase) pkg.mExtras;
4667                if (sb == null) {
4668                    continue;
4669                }
4670                PermissionsState permissionsState = sb.getPermissionsState();
4671                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4672                        userId, flagMask, flagValues);
4673            }
4674            if (changed) {
4675                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4676            }
4677        }
4678    }
4679
4680    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4681        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4682                != PackageManager.PERMISSION_GRANTED
4683            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4684                != PackageManager.PERMISSION_GRANTED) {
4685            throw new SecurityException(message + " requires "
4686                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4687                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4688        }
4689    }
4690
4691    @Override
4692    public boolean shouldShowRequestPermissionRationale(String permissionName,
4693            String packageName, int userId) {
4694        if (UserHandle.getCallingUserId() != userId) {
4695            mContext.enforceCallingPermission(
4696                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4697                    "canShowRequestPermissionRationale for user " + userId);
4698        }
4699
4700        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4701        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4702            return false;
4703        }
4704
4705        if (checkPermission(permissionName, packageName, userId)
4706                == PackageManager.PERMISSION_GRANTED) {
4707            return false;
4708        }
4709
4710        final int flags;
4711
4712        final long identity = Binder.clearCallingIdentity();
4713        try {
4714            flags = getPermissionFlags(permissionName,
4715                    packageName, userId);
4716        } finally {
4717            Binder.restoreCallingIdentity(identity);
4718        }
4719
4720        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4721                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4722                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4723
4724        if ((flags & fixedFlags) != 0) {
4725            return false;
4726        }
4727
4728        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4729    }
4730
4731    @Override
4732    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4733        mContext.enforceCallingOrSelfPermission(
4734                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4735                "addOnPermissionsChangeListener");
4736
4737        synchronized (mPackages) {
4738            mOnPermissionChangeListeners.addListenerLocked(listener);
4739        }
4740    }
4741
4742    @Override
4743    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4744        synchronized (mPackages) {
4745            mOnPermissionChangeListeners.removeListenerLocked(listener);
4746        }
4747    }
4748
4749    @Override
4750    public boolean isProtectedBroadcast(String actionName) {
4751        synchronized (mPackages) {
4752            if (mProtectedBroadcasts.contains(actionName)) {
4753                return true;
4754            } else if (actionName != null) {
4755                // TODO: remove these terrible hacks
4756                if (actionName.startsWith("android.net.netmon.lingerExpired")
4757                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4758                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4759                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4760                    return true;
4761                }
4762            }
4763        }
4764        return false;
4765    }
4766
4767    @Override
4768    public int checkSignatures(String pkg1, String pkg2) {
4769        synchronized (mPackages) {
4770            final PackageParser.Package p1 = mPackages.get(pkg1);
4771            final PackageParser.Package p2 = mPackages.get(pkg2);
4772            if (p1 == null || p1.mExtras == null
4773                    || p2 == null || p2.mExtras == null) {
4774                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4775            }
4776            return compareSignatures(p1.mSignatures, p2.mSignatures);
4777        }
4778    }
4779
4780    @Override
4781    public int checkUidSignatures(int uid1, int uid2) {
4782        // Map to base uids.
4783        uid1 = UserHandle.getAppId(uid1);
4784        uid2 = UserHandle.getAppId(uid2);
4785        // reader
4786        synchronized (mPackages) {
4787            Signature[] s1;
4788            Signature[] s2;
4789            Object obj = mSettings.getUserIdLPr(uid1);
4790            if (obj != null) {
4791                if (obj instanceof SharedUserSetting) {
4792                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4793                } else if (obj instanceof PackageSetting) {
4794                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4795                } else {
4796                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4797                }
4798            } else {
4799                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4800            }
4801            obj = mSettings.getUserIdLPr(uid2);
4802            if (obj != null) {
4803                if (obj instanceof SharedUserSetting) {
4804                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4805                } else if (obj instanceof PackageSetting) {
4806                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4807                } else {
4808                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4809                }
4810            } else {
4811                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4812            }
4813            return compareSignatures(s1, s2);
4814        }
4815    }
4816
4817    /**
4818     * This method should typically only be used when granting or revoking
4819     * permissions, since the app may immediately restart after this call.
4820     * <p>
4821     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4822     * guard your work against the app being relaunched.
4823     */
4824    private void killUid(int appId, int userId, String reason) {
4825        final long identity = Binder.clearCallingIdentity();
4826        try {
4827            IActivityManager am = ActivityManager.getService();
4828            if (am != null) {
4829                try {
4830                    am.killUid(appId, userId, reason);
4831                } catch (RemoteException e) {
4832                    /* ignore - same process */
4833                }
4834            }
4835        } finally {
4836            Binder.restoreCallingIdentity(identity);
4837        }
4838    }
4839
4840    /**
4841     * Compares two sets of signatures. Returns:
4842     * <br />
4843     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4844     * <br />
4845     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4846     * <br />
4847     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4848     * <br />
4849     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4850     * <br />
4851     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4852     */
4853    static int compareSignatures(Signature[] s1, Signature[] s2) {
4854        if (s1 == null) {
4855            return s2 == null
4856                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4857                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4858        }
4859
4860        if (s2 == null) {
4861            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4862        }
4863
4864        if (s1.length != s2.length) {
4865            return PackageManager.SIGNATURE_NO_MATCH;
4866        }
4867
4868        // Since both signature sets are of size 1, we can compare without HashSets.
4869        if (s1.length == 1) {
4870            return s1[0].equals(s2[0]) ?
4871                    PackageManager.SIGNATURE_MATCH :
4872                    PackageManager.SIGNATURE_NO_MATCH;
4873        }
4874
4875        ArraySet<Signature> set1 = new ArraySet<Signature>();
4876        for (Signature sig : s1) {
4877            set1.add(sig);
4878        }
4879        ArraySet<Signature> set2 = new ArraySet<Signature>();
4880        for (Signature sig : s2) {
4881            set2.add(sig);
4882        }
4883        // Make sure s2 contains all signatures in s1.
4884        if (set1.equals(set2)) {
4885            return PackageManager.SIGNATURE_MATCH;
4886        }
4887        return PackageManager.SIGNATURE_NO_MATCH;
4888    }
4889
4890    /**
4891     * If the database version for this type of package (internal storage or
4892     * external storage) is less than the version where package signatures
4893     * were updated, return true.
4894     */
4895    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4896        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4897        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4898    }
4899
4900    /**
4901     * Used for backward compatibility to make sure any packages with
4902     * certificate chains get upgraded to the new style. {@code existingSigs}
4903     * will be in the old format (since they were stored on disk from before the
4904     * system upgrade) and {@code scannedSigs} will be in the newer format.
4905     */
4906    private int compareSignaturesCompat(PackageSignatures existingSigs,
4907            PackageParser.Package scannedPkg) {
4908        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4909            return PackageManager.SIGNATURE_NO_MATCH;
4910        }
4911
4912        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4913        for (Signature sig : existingSigs.mSignatures) {
4914            existingSet.add(sig);
4915        }
4916        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4917        for (Signature sig : scannedPkg.mSignatures) {
4918            try {
4919                Signature[] chainSignatures = sig.getChainSignatures();
4920                for (Signature chainSig : chainSignatures) {
4921                    scannedCompatSet.add(chainSig);
4922                }
4923            } catch (CertificateEncodingException e) {
4924                scannedCompatSet.add(sig);
4925            }
4926        }
4927        /*
4928         * Make sure the expanded scanned set contains all signatures in the
4929         * existing one.
4930         */
4931        if (scannedCompatSet.equals(existingSet)) {
4932            // Migrate the old signatures to the new scheme.
4933            existingSigs.assignSignatures(scannedPkg.mSignatures);
4934            // The new KeySets will be re-added later in the scanning process.
4935            synchronized (mPackages) {
4936                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4937            }
4938            return PackageManager.SIGNATURE_MATCH;
4939        }
4940        return PackageManager.SIGNATURE_NO_MATCH;
4941    }
4942
4943    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4944        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4945        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4946    }
4947
4948    private int compareSignaturesRecover(PackageSignatures existingSigs,
4949            PackageParser.Package scannedPkg) {
4950        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4951            return PackageManager.SIGNATURE_NO_MATCH;
4952        }
4953
4954        String msg = null;
4955        try {
4956            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4957                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4958                        + scannedPkg.packageName);
4959                return PackageManager.SIGNATURE_MATCH;
4960            }
4961        } catch (CertificateException e) {
4962            msg = e.getMessage();
4963        }
4964
4965        logCriticalInfo(Log.INFO,
4966                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4967        return PackageManager.SIGNATURE_NO_MATCH;
4968    }
4969
4970    @Override
4971    public List<String> getAllPackages() {
4972        synchronized (mPackages) {
4973            return new ArrayList<String>(mPackages.keySet());
4974        }
4975    }
4976
4977    @Override
4978    public String[] getPackagesForUid(int uid) {
4979        final int userId = UserHandle.getUserId(uid);
4980        uid = UserHandle.getAppId(uid);
4981        // reader
4982        synchronized (mPackages) {
4983            Object obj = mSettings.getUserIdLPr(uid);
4984            if (obj instanceof SharedUserSetting) {
4985                final SharedUserSetting sus = (SharedUserSetting) obj;
4986                final int N = sus.packages.size();
4987                String[] res = new String[N];
4988                final Iterator<PackageSetting> it = sus.packages.iterator();
4989                int i = 0;
4990                while (it.hasNext()) {
4991                    PackageSetting ps = it.next();
4992                    if (ps.getInstalled(userId)) {
4993                        res[i++] = ps.name;
4994                    } else {
4995                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4996                    }
4997                }
4998                return res;
4999            } else if (obj instanceof PackageSetting) {
5000                final PackageSetting ps = (PackageSetting) obj;
5001                return new String[] { ps.name };
5002            }
5003        }
5004        return null;
5005    }
5006
5007    @Override
5008    public String getNameForUid(int uid) {
5009        // reader
5010        synchronized (mPackages) {
5011            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5012            if (obj instanceof SharedUserSetting) {
5013                final SharedUserSetting sus = (SharedUserSetting) obj;
5014                return sus.name + ":" + sus.userId;
5015            } else if (obj instanceof PackageSetting) {
5016                final PackageSetting ps = (PackageSetting) obj;
5017                return ps.name;
5018            }
5019        }
5020        return null;
5021    }
5022
5023    @Override
5024    public int getUidForSharedUser(String sharedUserName) {
5025        if(sharedUserName == null) {
5026            return -1;
5027        }
5028        // reader
5029        synchronized (mPackages) {
5030            SharedUserSetting suid;
5031            try {
5032                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5033                if (suid != null) {
5034                    return suid.userId;
5035                }
5036            } catch (PackageManagerException ignore) {
5037                // can't happen, but, still need to catch it
5038            }
5039            return -1;
5040        }
5041    }
5042
5043    @Override
5044    public int getFlagsForUid(int uid) {
5045        synchronized (mPackages) {
5046            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5047            if (obj instanceof SharedUserSetting) {
5048                final SharedUserSetting sus = (SharedUserSetting) obj;
5049                return sus.pkgFlags;
5050            } else if (obj instanceof PackageSetting) {
5051                final PackageSetting ps = (PackageSetting) obj;
5052                return ps.pkgFlags;
5053            }
5054        }
5055        return 0;
5056    }
5057
5058    @Override
5059    public int getPrivateFlagsForUid(int uid) {
5060        synchronized (mPackages) {
5061            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5062            if (obj instanceof SharedUserSetting) {
5063                final SharedUserSetting sus = (SharedUserSetting) obj;
5064                return sus.pkgPrivateFlags;
5065            } else if (obj instanceof PackageSetting) {
5066                final PackageSetting ps = (PackageSetting) obj;
5067                return ps.pkgPrivateFlags;
5068            }
5069        }
5070        return 0;
5071    }
5072
5073    @Override
5074    public boolean isUidPrivileged(int uid) {
5075        uid = UserHandle.getAppId(uid);
5076        // reader
5077        synchronized (mPackages) {
5078            Object obj = mSettings.getUserIdLPr(uid);
5079            if (obj instanceof SharedUserSetting) {
5080                final SharedUserSetting sus = (SharedUserSetting) obj;
5081                final Iterator<PackageSetting> it = sus.packages.iterator();
5082                while (it.hasNext()) {
5083                    if (it.next().isPrivileged()) {
5084                        return true;
5085                    }
5086                }
5087            } else if (obj instanceof PackageSetting) {
5088                final PackageSetting ps = (PackageSetting) obj;
5089                return ps.isPrivileged();
5090            }
5091        }
5092        return false;
5093    }
5094
5095    @Override
5096    public String[] getAppOpPermissionPackages(String permissionName) {
5097        synchronized (mPackages) {
5098            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5099            if (pkgs == null) {
5100                return null;
5101            }
5102            return pkgs.toArray(new String[pkgs.size()]);
5103        }
5104    }
5105
5106    @Override
5107    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5108            int flags, int userId) {
5109        try {
5110            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5111
5112            if (!sUserManager.exists(userId)) return null;
5113            flags = updateFlagsForResolve(flags, userId, intent);
5114            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5115                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5116
5117            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5118            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5119                    flags, userId);
5120            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5121
5122            final ResolveInfo bestChoice =
5123                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5124            return bestChoice;
5125        } finally {
5126            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5127        }
5128    }
5129
5130    @Override
5131    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5132            IntentFilter filter, int match, ComponentName activity) {
5133        final int userId = UserHandle.getCallingUserId();
5134        if (DEBUG_PREFERRED) {
5135            Log.v(TAG, "setLastChosenActivity intent=" + intent
5136                + " resolvedType=" + resolvedType
5137                + " flags=" + flags
5138                + " filter=" + filter
5139                + " match=" + match
5140                + " activity=" + activity);
5141            filter.dump(new PrintStreamPrinter(System.out), "    ");
5142        }
5143        intent.setComponent(null);
5144        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5145                userId);
5146        // Find any earlier preferred or last chosen entries and nuke them
5147        findPreferredActivity(intent, resolvedType,
5148                flags, query, 0, false, true, false, userId);
5149        // Add the new activity as the last chosen for this filter
5150        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5151                "Setting last chosen");
5152    }
5153
5154    @Override
5155    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5156        final int userId = UserHandle.getCallingUserId();
5157        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5158        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5159                userId);
5160        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5161                false, false, false, userId);
5162    }
5163
5164    private boolean isEphemeralDisabled() {
5165        // ephemeral apps have been disabled across the board
5166        if (DISABLE_EPHEMERAL_APPS) {
5167            return true;
5168        }
5169        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5170        if (!mSystemReady) {
5171            return true;
5172        }
5173        // we can't get a content resolver until the system is ready; these checks must happen last
5174        final ContentResolver resolver = mContext.getContentResolver();
5175        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5176            return true;
5177        }
5178        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5179    }
5180
5181    private boolean isEphemeralAllowed(
5182            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5183            boolean skipPackageCheck) {
5184        // Short circuit and return early if possible.
5185        if (isEphemeralDisabled()) {
5186            return false;
5187        }
5188        final int callingUser = UserHandle.getCallingUserId();
5189        if (callingUser != UserHandle.USER_SYSTEM) {
5190            return false;
5191        }
5192        if (mEphemeralResolverConnection == null) {
5193            return false;
5194        }
5195        if (mEphemeralInstallerComponent == null) {
5196            return false;
5197        }
5198        if (intent.getComponent() != null) {
5199            return false;
5200        }
5201        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5202            return false;
5203        }
5204        if (!skipPackageCheck && intent.getPackage() != null) {
5205            return false;
5206        }
5207        final boolean isWebUri = hasWebURI(intent);
5208        if (!isWebUri || intent.getData().getHost() == null) {
5209            return false;
5210        }
5211        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5212        synchronized (mPackages) {
5213            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5214            for (int n = 0; n < count; n++) {
5215                ResolveInfo info = resolvedActivities.get(n);
5216                String packageName = info.activityInfo.packageName;
5217                PackageSetting ps = mSettings.mPackages.get(packageName);
5218                if (ps != null) {
5219                    // Try to get the status from User settings first
5220                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5221                    int status = (int) (packedStatus >> 32);
5222                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5223                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5224                        if (DEBUG_EPHEMERAL) {
5225                            Slog.v(TAG, "DENY ephemeral apps;"
5226                                + " pkg: " + packageName + ", status: " + status);
5227                        }
5228                        return false;
5229                    }
5230                }
5231            }
5232        }
5233        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5234        return true;
5235    }
5236
5237    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5238            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5239            int userId) {
5240        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5241                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5242                        callingPackage, userId));
5243        mHandler.sendMessage(msg);
5244    }
5245
5246    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5247            int flags, List<ResolveInfo> query, int userId) {
5248        if (query != null) {
5249            final int N = query.size();
5250            if (N == 1) {
5251                return query.get(0);
5252            } else if (N > 1) {
5253                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5254                // If there is more than one activity with the same priority,
5255                // then let the user decide between them.
5256                ResolveInfo r0 = query.get(0);
5257                ResolveInfo r1 = query.get(1);
5258                if (DEBUG_INTENT_MATCHING || debug) {
5259                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5260                            + r1.activityInfo.name + "=" + r1.priority);
5261                }
5262                // If the first activity has a higher priority, or a different
5263                // default, then it is always desirable to pick it.
5264                if (r0.priority != r1.priority
5265                        || r0.preferredOrder != r1.preferredOrder
5266                        || r0.isDefault != r1.isDefault) {
5267                    return query.get(0);
5268                }
5269                // If we have saved a preference for a preferred activity for
5270                // this Intent, use that.
5271                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5272                        flags, query, r0.priority, true, false, debug, userId);
5273                if (ri != null) {
5274                    return ri;
5275                }
5276                ri = new ResolveInfo(mResolveInfo);
5277                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5278                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5279                // If all of the options come from the same package, show the application's
5280                // label and icon instead of the generic resolver's.
5281                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5282                // and then throw away the ResolveInfo itself, meaning that the caller loses
5283                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5284                // a fallback for this case; we only set the target package's resources on
5285                // the ResolveInfo, not the ActivityInfo.
5286                final String intentPackage = intent.getPackage();
5287                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5288                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5289                    ri.resolvePackageName = intentPackage;
5290                    if (userNeedsBadging(userId)) {
5291                        ri.noResourceId = true;
5292                    } else {
5293                        ri.icon = appi.icon;
5294                    }
5295                    ri.iconResourceId = appi.icon;
5296                    ri.labelRes = appi.labelRes;
5297                }
5298                ri.activityInfo.applicationInfo = new ApplicationInfo(
5299                        ri.activityInfo.applicationInfo);
5300                if (userId != 0) {
5301                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5302                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5303                }
5304                // Make sure that the resolver is displayable in car mode
5305                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5306                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5307                return ri;
5308            }
5309        }
5310        return null;
5311    }
5312
5313    /**
5314     * Return true if the given list is not empty and all of its contents have
5315     * an activityInfo with the given package name.
5316     */
5317    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5318        if (ArrayUtils.isEmpty(list)) {
5319            return false;
5320        }
5321        for (int i = 0, N = list.size(); i < N; i++) {
5322            final ResolveInfo ri = list.get(i);
5323            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5324            if (ai == null || !packageName.equals(ai.packageName)) {
5325                return false;
5326            }
5327        }
5328        return true;
5329    }
5330
5331    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5332            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5333        final int N = query.size();
5334        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5335                .get(userId);
5336        // Get the list of persistent preferred activities that handle the intent
5337        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5338        List<PersistentPreferredActivity> pprefs = ppir != null
5339                ? ppir.queryIntent(intent, resolvedType,
5340                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5341                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5342                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5343                : null;
5344        if (pprefs != null && pprefs.size() > 0) {
5345            final int M = pprefs.size();
5346            for (int i=0; i<M; i++) {
5347                final PersistentPreferredActivity ppa = pprefs.get(i);
5348                if (DEBUG_PREFERRED || debug) {
5349                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5350                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5351                            + "\n  component=" + ppa.mComponent);
5352                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5353                }
5354                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5355                        flags | MATCH_DISABLED_COMPONENTS, userId);
5356                if (DEBUG_PREFERRED || debug) {
5357                    Slog.v(TAG, "Found persistent preferred activity:");
5358                    if (ai != null) {
5359                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5360                    } else {
5361                        Slog.v(TAG, "  null");
5362                    }
5363                }
5364                if (ai == null) {
5365                    // This previously registered persistent preferred activity
5366                    // component is no longer known. Ignore it and do NOT remove it.
5367                    continue;
5368                }
5369                for (int j=0; j<N; j++) {
5370                    final ResolveInfo ri = query.get(j);
5371                    if (!ri.activityInfo.applicationInfo.packageName
5372                            .equals(ai.applicationInfo.packageName)) {
5373                        continue;
5374                    }
5375                    if (!ri.activityInfo.name.equals(ai.name)) {
5376                        continue;
5377                    }
5378                    //  Found a persistent preference that can handle the intent.
5379                    if (DEBUG_PREFERRED || debug) {
5380                        Slog.v(TAG, "Returning persistent preferred activity: " +
5381                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5382                    }
5383                    return ri;
5384                }
5385            }
5386        }
5387        return null;
5388    }
5389
5390    // TODO: handle preferred activities missing while user has amnesia
5391    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5392            List<ResolveInfo> query, int priority, boolean always,
5393            boolean removeMatches, boolean debug, int userId) {
5394        if (!sUserManager.exists(userId)) return null;
5395        flags = updateFlagsForResolve(flags, userId, intent);
5396        // writer
5397        synchronized (mPackages) {
5398            if (intent.getSelector() != null) {
5399                intent = intent.getSelector();
5400            }
5401            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5402
5403            // Try to find a matching persistent preferred activity.
5404            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5405                    debug, userId);
5406
5407            // If a persistent preferred activity matched, use it.
5408            if (pri != null) {
5409                return pri;
5410            }
5411
5412            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5413            // Get the list of preferred activities that handle the intent
5414            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5415            List<PreferredActivity> prefs = pir != null
5416                    ? pir.queryIntent(intent, resolvedType,
5417                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5418                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5419                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5420                    : null;
5421            if (prefs != null && prefs.size() > 0) {
5422                boolean changed = false;
5423                try {
5424                    // First figure out how good the original match set is.
5425                    // We will only allow preferred activities that came
5426                    // from the same match quality.
5427                    int match = 0;
5428
5429                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5430
5431                    final int N = query.size();
5432                    for (int j=0; j<N; j++) {
5433                        final ResolveInfo ri = query.get(j);
5434                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5435                                + ": 0x" + Integer.toHexString(match));
5436                        if (ri.match > match) {
5437                            match = ri.match;
5438                        }
5439                    }
5440
5441                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5442                            + Integer.toHexString(match));
5443
5444                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5445                    final int M = prefs.size();
5446                    for (int i=0; i<M; i++) {
5447                        final PreferredActivity pa = prefs.get(i);
5448                        if (DEBUG_PREFERRED || debug) {
5449                            Slog.v(TAG, "Checking PreferredActivity ds="
5450                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5451                                    + "\n  component=" + pa.mPref.mComponent);
5452                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5453                        }
5454                        if (pa.mPref.mMatch != match) {
5455                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5456                                    + Integer.toHexString(pa.mPref.mMatch));
5457                            continue;
5458                        }
5459                        // If it's not an "always" type preferred activity and that's what we're
5460                        // looking for, skip it.
5461                        if (always && !pa.mPref.mAlways) {
5462                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5463                            continue;
5464                        }
5465                        final ActivityInfo ai = getActivityInfo(
5466                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5467                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5468                                userId);
5469                        if (DEBUG_PREFERRED || debug) {
5470                            Slog.v(TAG, "Found preferred activity:");
5471                            if (ai != null) {
5472                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5473                            } else {
5474                                Slog.v(TAG, "  null");
5475                            }
5476                        }
5477                        if (ai == null) {
5478                            // This previously registered preferred activity
5479                            // component is no longer known.  Most likely an update
5480                            // to the app was installed and in the new version this
5481                            // component no longer exists.  Clean it up by removing
5482                            // it from the preferred activities list, and skip it.
5483                            Slog.w(TAG, "Removing dangling preferred activity: "
5484                                    + pa.mPref.mComponent);
5485                            pir.removeFilter(pa);
5486                            changed = true;
5487                            continue;
5488                        }
5489                        for (int j=0; j<N; j++) {
5490                            final ResolveInfo ri = query.get(j);
5491                            if (!ri.activityInfo.applicationInfo.packageName
5492                                    .equals(ai.applicationInfo.packageName)) {
5493                                continue;
5494                            }
5495                            if (!ri.activityInfo.name.equals(ai.name)) {
5496                                continue;
5497                            }
5498
5499                            if (removeMatches) {
5500                                pir.removeFilter(pa);
5501                                changed = true;
5502                                if (DEBUG_PREFERRED) {
5503                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5504                                }
5505                                break;
5506                            }
5507
5508                            // Okay we found a previously set preferred or last chosen app.
5509                            // If the result set is different from when this
5510                            // was created, we need to clear it and re-ask the
5511                            // user their preference, if we're looking for an "always" type entry.
5512                            if (always && !pa.mPref.sameSet(query)) {
5513                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5514                                        + intent + " type " + resolvedType);
5515                                if (DEBUG_PREFERRED) {
5516                                    Slog.v(TAG, "Removing preferred activity since set changed "
5517                                            + pa.mPref.mComponent);
5518                                }
5519                                pir.removeFilter(pa);
5520                                // Re-add the filter as a "last chosen" entry (!always)
5521                                PreferredActivity lastChosen = new PreferredActivity(
5522                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5523                                pir.addFilter(lastChosen);
5524                                changed = true;
5525                                return null;
5526                            }
5527
5528                            // Yay! Either the set matched or we're looking for the last chosen
5529                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5530                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5531                            return ri;
5532                        }
5533                    }
5534                } finally {
5535                    if (changed) {
5536                        if (DEBUG_PREFERRED) {
5537                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5538                        }
5539                        scheduleWritePackageRestrictionsLocked(userId);
5540                    }
5541                }
5542            }
5543        }
5544        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5545        return null;
5546    }
5547
5548    /*
5549     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5550     */
5551    @Override
5552    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5553            int targetUserId) {
5554        mContext.enforceCallingOrSelfPermission(
5555                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5556        List<CrossProfileIntentFilter> matches =
5557                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5558        if (matches != null) {
5559            int size = matches.size();
5560            for (int i = 0; i < size; i++) {
5561                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5562            }
5563        }
5564        if (hasWebURI(intent)) {
5565            // cross-profile app linking works only towards the parent.
5566            final UserInfo parent = getProfileParent(sourceUserId);
5567            synchronized(mPackages) {
5568                int flags = updateFlagsForResolve(0, parent.id, intent);
5569                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5570                        intent, resolvedType, flags, sourceUserId, parent.id);
5571                return xpDomainInfo != null;
5572            }
5573        }
5574        return false;
5575    }
5576
5577    private UserInfo getProfileParent(int userId) {
5578        final long identity = Binder.clearCallingIdentity();
5579        try {
5580            return sUserManager.getProfileParent(userId);
5581        } finally {
5582            Binder.restoreCallingIdentity(identity);
5583        }
5584    }
5585
5586    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5587            String resolvedType, int userId) {
5588        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5589        if (resolver != null) {
5590            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5591                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5592        }
5593        return null;
5594    }
5595
5596    @Override
5597    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5598            String resolvedType, int flags, int userId) {
5599        try {
5600            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5601
5602            return new ParceledListSlice<>(
5603                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5604        } finally {
5605            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5606        }
5607    }
5608
5609    /**
5610     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5611     * ephemeral, returns {@code null}.
5612     */
5613    private String getEphemeralPackageName(int callingUid) {
5614        final int appId = UserHandle.getAppId(callingUid);
5615        synchronized (mPackages) {
5616            final Object obj = mSettings.getUserIdLPr(appId);
5617            if (obj instanceof PackageSetting) {
5618                final PackageSetting ps = (PackageSetting) obj;
5619                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5620            }
5621        }
5622        return null;
5623    }
5624
5625    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5626            String resolvedType, int flags, int userId) {
5627        if (!sUserManager.exists(userId)) return Collections.emptyList();
5628        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5629        flags = updateFlagsForResolve(flags, userId, intent);
5630        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5631                false /* requireFullPermission */, false /* checkShell */,
5632                "query intent activities");
5633        ComponentName comp = intent.getComponent();
5634        if (comp == null) {
5635            if (intent.getSelector() != null) {
5636                intent = intent.getSelector();
5637                comp = intent.getComponent();
5638            }
5639        }
5640
5641        if (comp != null) {
5642            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5643            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5644            if (ai != null) {
5645                // When specifying an explicit component, we prevent the activity from being
5646                // used when either 1) the calling package is normal and the activity is within
5647                // an ephemeral application or 2) the calling package is ephemeral and the
5648                // activity is not visible to ephemeral applications.
5649                boolean matchEphemeral =
5650                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5651                boolean ephemeralVisibleOnly =
5652                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5653                boolean blockResolution =
5654                        (!matchEphemeral && ephemeralPkgName == null
5655                                && (ai.applicationInfo.privateFlags
5656                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5657                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5658                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5659                if (!blockResolution) {
5660                    final ResolveInfo ri = new ResolveInfo();
5661                    ri.activityInfo = ai;
5662                    list.add(ri);
5663                }
5664            }
5665            return list;
5666        }
5667
5668        // reader
5669        boolean sortResult = false;
5670        boolean addEphemeral = false;
5671        List<ResolveInfo> result;
5672        final String pkgName = intent.getPackage();
5673        synchronized (mPackages) {
5674            if (pkgName == null) {
5675                List<CrossProfileIntentFilter> matchingFilters =
5676                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5677                // Check for results that need to skip the current profile.
5678                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5679                        resolvedType, flags, userId);
5680                if (xpResolveInfo != null) {
5681                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5682                    xpResult.add(xpResolveInfo);
5683                    return filterForEphemeral(
5684                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5685                }
5686
5687                // Check for results in the current profile.
5688                result = filterIfNotSystemUser(mActivities.queryIntent(
5689                        intent, resolvedType, flags, userId), userId);
5690                addEphemeral =
5691                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5692
5693                // Check for cross profile results.
5694                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5695                xpResolveInfo = queryCrossProfileIntents(
5696                        matchingFilters, intent, resolvedType, flags, userId,
5697                        hasNonNegativePriorityResult);
5698                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5699                    boolean isVisibleToUser = filterIfNotSystemUser(
5700                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5701                    if (isVisibleToUser) {
5702                        result.add(xpResolveInfo);
5703                        sortResult = true;
5704                    }
5705                }
5706                if (hasWebURI(intent)) {
5707                    CrossProfileDomainInfo xpDomainInfo = null;
5708                    final UserInfo parent = getProfileParent(userId);
5709                    if (parent != null) {
5710                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5711                                flags, userId, parent.id);
5712                    }
5713                    if (xpDomainInfo != null) {
5714                        if (xpResolveInfo != null) {
5715                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5716                            // in the result.
5717                            result.remove(xpResolveInfo);
5718                        }
5719                        if (result.size() == 0 && !addEphemeral) {
5720                            // No result in current profile, but found candidate in parent user.
5721                            // And we are not going to add emphemeral app, so we can return the
5722                            // result straight away.
5723                            result.add(xpDomainInfo.resolveInfo);
5724                            return filterForEphemeral(result, ephemeralPkgName);
5725                        }
5726                    } else if (result.size() <= 1 && !addEphemeral) {
5727                        // No result in parent user and <= 1 result in current profile, and we
5728                        // are not going to add emphemeral app, so we can return the result without
5729                        // further processing.
5730                        return filterForEphemeral(result, ephemeralPkgName);
5731                    }
5732                    // We have more than one candidate (combining results from current and parent
5733                    // profile), so we need filtering and sorting.
5734                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5735                            intent, flags, result, xpDomainInfo, userId);
5736                    sortResult = true;
5737                }
5738            } else {
5739                final PackageParser.Package pkg = mPackages.get(pkgName);
5740                if (pkg != null) {
5741                    result = filterForEphemeral(filterIfNotSystemUser(
5742                            mActivities.queryIntentForPackage(
5743                                    intent, resolvedType, flags, pkg.activities, userId),
5744                            userId), ephemeralPkgName);
5745                } else {
5746                    // the caller wants to resolve for a particular package; however, there
5747                    // were no installed results, so, try to find an ephemeral result
5748                    addEphemeral = isEphemeralAllowed(
5749                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5750                    result = new ArrayList<ResolveInfo>();
5751                }
5752            }
5753        }
5754        if (addEphemeral) {
5755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5756            final EphemeralRequest requestObject = new EphemeralRequest(
5757                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5758                    null /*launchIntent*/, null /*callingPackage*/, userId);
5759            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5760                    mContext, mEphemeralResolverConnection, requestObject);
5761            if (intentInfo != null) {
5762                if (DEBUG_EPHEMERAL) {
5763                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5764                }
5765                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5766                ephemeralInstaller.ephemeralResponse = intentInfo;
5767                // make sure this resolver is the default
5768                ephemeralInstaller.isDefault = true;
5769                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5770                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5771                // add a non-generic filter
5772                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5773                ephemeralInstaller.filter.addDataPath(
5774                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5775                result.add(ephemeralInstaller);
5776            }
5777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5778        }
5779        if (sortResult) {
5780            Collections.sort(result, mResolvePrioritySorter);
5781        }
5782        return filterForEphemeral(result, ephemeralPkgName);
5783    }
5784
5785    private static class CrossProfileDomainInfo {
5786        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5787        ResolveInfo resolveInfo;
5788        /* Best domain verification status of the activities found in the other profile */
5789        int bestDomainVerificationStatus;
5790    }
5791
5792    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5793            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5794        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5795                sourceUserId)) {
5796            return null;
5797        }
5798        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5799                resolvedType, flags, parentUserId);
5800
5801        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5802            return null;
5803        }
5804        CrossProfileDomainInfo result = null;
5805        int size = resultTargetUser.size();
5806        for (int i = 0; i < size; i++) {
5807            ResolveInfo riTargetUser = resultTargetUser.get(i);
5808            // Intent filter verification is only for filters that specify a host. So don't return
5809            // those that handle all web uris.
5810            if (riTargetUser.handleAllWebDataURI) {
5811                continue;
5812            }
5813            String packageName = riTargetUser.activityInfo.packageName;
5814            PackageSetting ps = mSettings.mPackages.get(packageName);
5815            if (ps == null) {
5816                continue;
5817            }
5818            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5819            int status = (int)(verificationState >> 32);
5820            if (result == null) {
5821                result = new CrossProfileDomainInfo();
5822                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5823                        sourceUserId, parentUserId);
5824                result.bestDomainVerificationStatus = status;
5825            } else {
5826                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5827                        result.bestDomainVerificationStatus);
5828            }
5829        }
5830        // Don't consider matches with status NEVER across profiles.
5831        if (result != null && result.bestDomainVerificationStatus
5832                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5833            return null;
5834        }
5835        return result;
5836    }
5837
5838    /**
5839     * Verification statuses are ordered from the worse to the best, except for
5840     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5841     */
5842    private int bestDomainVerificationStatus(int status1, int status2) {
5843        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5844            return status2;
5845        }
5846        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5847            return status1;
5848        }
5849        return (int) MathUtils.max(status1, status2);
5850    }
5851
5852    private boolean isUserEnabled(int userId) {
5853        long callingId = Binder.clearCallingIdentity();
5854        try {
5855            UserInfo userInfo = sUserManager.getUserInfo(userId);
5856            return userInfo != null && userInfo.isEnabled();
5857        } finally {
5858            Binder.restoreCallingIdentity(callingId);
5859        }
5860    }
5861
5862    /**
5863     * Filter out activities with systemUserOnly flag set, when current user is not System.
5864     *
5865     * @return filtered list
5866     */
5867    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5868        if (userId == UserHandle.USER_SYSTEM) {
5869            return resolveInfos;
5870        }
5871        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5872            ResolveInfo info = resolveInfos.get(i);
5873            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5874                resolveInfos.remove(i);
5875            }
5876        }
5877        return resolveInfos;
5878    }
5879
5880    /**
5881     * Filters out ephemeral activities.
5882     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5883     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5884     *
5885     * @param resolveInfos The pre-filtered list of resolved activities
5886     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5887     *          is performed.
5888     * @return A filtered list of resolved activities.
5889     */
5890    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5891            String ephemeralPkgName) {
5892        if (ephemeralPkgName == null) {
5893            return resolveInfos;
5894        }
5895        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5896            ResolveInfo info = resolveInfos.get(i);
5897            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5898            // allow activities that are defined in the provided package
5899            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5900                continue;
5901            }
5902            // allow activities that have been explicitly exposed to ephemeral apps
5903            if (!isEphemeralApp
5904                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5905                continue;
5906            }
5907            resolveInfos.remove(i);
5908        }
5909        return resolveInfos;
5910    }
5911
5912    /**
5913     * @param resolveInfos list of resolve infos in descending priority order
5914     * @return if the list contains a resolve info with non-negative priority
5915     */
5916    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5917        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5918    }
5919
5920    private static boolean hasWebURI(Intent intent) {
5921        if (intent.getData() == null) {
5922            return false;
5923        }
5924        final String scheme = intent.getScheme();
5925        if (TextUtils.isEmpty(scheme)) {
5926            return false;
5927        }
5928        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5929    }
5930
5931    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5932            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5933            int userId) {
5934        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5935
5936        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5937            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5938                    candidates.size());
5939        }
5940
5941        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5942        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5943        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5944        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5945        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5946        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5947
5948        synchronized (mPackages) {
5949            final int count = candidates.size();
5950            // First, try to use linked apps. Partition the candidates into four lists:
5951            // one for the final results, one for the "do not use ever", one for "undefined status"
5952            // and finally one for "browser app type".
5953            for (int n=0; n<count; n++) {
5954                ResolveInfo info = candidates.get(n);
5955                String packageName = info.activityInfo.packageName;
5956                PackageSetting ps = mSettings.mPackages.get(packageName);
5957                if (ps != null) {
5958                    // Add to the special match all list (Browser use case)
5959                    if (info.handleAllWebDataURI) {
5960                        matchAllList.add(info);
5961                        continue;
5962                    }
5963                    // Try to get the status from User settings first
5964                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5965                    int status = (int)(packedStatus >> 32);
5966                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5967                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5968                        if (DEBUG_DOMAIN_VERIFICATION) {
5969                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5970                                    + " : linkgen=" + linkGeneration);
5971                        }
5972                        // Use link-enabled generation as preferredOrder, i.e.
5973                        // prefer newly-enabled over earlier-enabled.
5974                        info.preferredOrder = linkGeneration;
5975                        alwaysList.add(info);
5976                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5977                        if (DEBUG_DOMAIN_VERIFICATION) {
5978                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5979                        }
5980                        neverList.add(info);
5981                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5982                        if (DEBUG_DOMAIN_VERIFICATION) {
5983                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5984                        }
5985                        alwaysAskList.add(info);
5986                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5987                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5988                        if (DEBUG_DOMAIN_VERIFICATION) {
5989                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5990                        }
5991                        undefinedList.add(info);
5992                    }
5993                }
5994            }
5995
5996            // We'll want to include browser possibilities in a few cases
5997            boolean includeBrowser = false;
5998
5999            // First try to add the "always" resolution(s) for the current user, if any
6000            if (alwaysList.size() > 0) {
6001                result.addAll(alwaysList);
6002            } else {
6003                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6004                result.addAll(undefinedList);
6005                // Maybe add one for the other profile.
6006                if (xpDomainInfo != null && (
6007                        xpDomainInfo.bestDomainVerificationStatus
6008                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6009                    result.add(xpDomainInfo.resolveInfo);
6010                }
6011                includeBrowser = true;
6012            }
6013
6014            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6015            // If there were 'always' entries their preferred order has been set, so we also
6016            // back that off to make the alternatives equivalent
6017            if (alwaysAskList.size() > 0) {
6018                for (ResolveInfo i : result) {
6019                    i.preferredOrder = 0;
6020                }
6021                result.addAll(alwaysAskList);
6022                includeBrowser = true;
6023            }
6024
6025            if (includeBrowser) {
6026                // Also add browsers (all of them or only the default one)
6027                if (DEBUG_DOMAIN_VERIFICATION) {
6028                    Slog.v(TAG, "   ...including browsers in candidate set");
6029                }
6030                if ((matchFlags & MATCH_ALL) != 0) {
6031                    result.addAll(matchAllList);
6032                } else {
6033                    // Browser/generic handling case.  If there's a default browser, go straight
6034                    // to that (but only if there is no other higher-priority match).
6035                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6036                    int maxMatchPrio = 0;
6037                    ResolveInfo defaultBrowserMatch = null;
6038                    final int numCandidates = matchAllList.size();
6039                    for (int n = 0; n < numCandidates; n++) {
6040                        ResolveInfo info = matchAllList.get(n);
6041                        // track the highest overall match priority...
6042                        if (info.priority > maxMatchPrio) {
6043                            maxMatchPrio = info.priority;
6044                        }
6045                        // ...and the highest-priority default browser match
6046                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6047                            if (defaultBrowserMatch == null
6048                                    || (defaultBrowserMatch.priority < info.priority)) {
6049                                if (debug) {
6050                                    Slog.v(TAG, "Considering default browser match " + info);
6051                                }
6052                                defaultBrowserMatch = info;
6053                            }
6054                        }
6055                    }
6056                    if (defaultBrowserMatch != null
6057                            && defaultBrowserMatch.priority >= maxMatchPrio
6058                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6059                    {
6060                        if (debug) {
6061                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6062                        }
6063                        result.add(defaultBrowserMatch);
6064                    } else {
6065                        result.addAll(matchAllList);
6066                    }
6067                }
6068
6069                // If there is nothing selected, add all candidates and remove the ones that the user
6070                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6071                if (result.size() == 0) {
6072                    result.addAll(candidates);
6073                    result.removeAll(neverList);
6074                }
6075            }
6076        }
6077        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6078            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6079                    result.size());
6080            for (ResolveInfo info : result) {
6081                Slog.v(TAG, "  + " + info.activityInfo);
6082            }
6083        }
6084        return result;
6085    }
6086
6087    // Returns a packed value as a long:
6088    //
6089    // high 'int'-sized word: link status: undefined/ask/never/always.
6090    // low 'int'-sized word: relative priority among 'always' results.
6091    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6092        long result = ps.getDomainVerificationStatusForUser(userId);
6093        // if none available, get the master status
6094        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6095            if (ps.getIntentFilterVerificationInfo() != null) {
6096                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6097            }
6098        }
6099        return result;
6100    }
6101
6102    private ResolveInfo querySkipCurrentProfileIntents(
6103            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6104            int flags, int sourceUserId) {
6105        if (matchingFilters != null) {
6106            int size = matchingFilters.size();
6107            for (int i = 0; i < size; i ++) {
6108                CrossProfileIntentFilter filter = matchingFilters.get(i);
6109                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6110                    // Checking if there are activities in the target user that can handle the
6111                    // intent.
6112                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6113                            resolvedType, flags, sourceUserId);
6114                    if (resolveInfo != null) {
6115                        return resolveInfo;
6116                    }
6117                }
6118            }
6119        }
6120        return null;
6121    }
6122
6123    // Return matching ResolveInfo in target user if any.
6124    private ResolveInfo queryCrossProfileIntents(
6125            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6126            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6127        if (matchingFilters != null) {
6128            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6129            // match the same intent. For performance reasons, it is better not to
6130            // run queryIntent twice for the same userId
6131            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6132            int size = matchingFilters.size();
6133            for (int i = 0; i < size; i++) {
6134                CrossProfileIntentFilter filter = matchingFilters.get(i);
6135                int targetUserId = filter.getTargetUserId();
6136                boolean skipCurrentProfile =
6137                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6138                boolean skipCurrentProfileIfNoMatchFound =
6139                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6140                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6141                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6142                    // Checking if there are activities in the target user that can handle the
6143                    // intent.
6144                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6145                            resolvedType, flags, sourceUserId);
6146                    if (resolveInfo != null) return resolveInfo;
6147                    alreadyTriedUserIds.put(targetUserId, true);
6148                }
6149            }
6150        }
6151        return null;
6152    }
6153
6154    /**
6155     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6156     * will forward the intent to the filter's target user.
6157     * Otherwise, returns null.
6158     */
6159    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6160            String resolvedType, int flags, int sourceUserId) {
6161        int targetUserId = filter.getTargetUserId();
6162        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6163                resolvedType, flags, targetUserId);
6164        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6165            // If all the matches in the target profile are suspended, return null.
6166            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6167                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6168                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6169                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6170                            targetUserId);
6171                }
6172            }
6173        }
6174        return null;
6175    }
6176
6177    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6178            int sourceUserId, int targetUserId) {
6179        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6180        long ident = Binder.clearCallingIdentity();
6181        boolean targetIsProfile;
6182        try {
6183            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6184        } finally {
6185            Binder.restoreCallingIdentity(ident);
6186        }
6187        String className;
6188        if (targetIsProfile) {
6189            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6190        } else {
6191            className = FORWARD_INTENT_TO_PARENT;
6192        }
6193        ComponentName forwardingActivityComponentName = new ComponentName(
6194                mAndroidApplication.packageName, className);
6195        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6196                sourceUserId);
6197        if (!targetIsProfile) {
6198            forwardingActivityInfo.showUserIcon = targetUserId;
6199            forwardingResolveInfo.noResourceId = true;
6200        }
6201        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6202        forwardingResolveInfo.priority = 0;
6203        forwardingResolveInfo.preferredOrder = 0;
6204        forwardingResolveInfo.match = 0;
6205        forwardingResolveInfo.isDefault = true;
6206        forwardingResolveInfo.filter = filter;
6207        forwardingResolveInfo.targetUserId = targetUserId;
6208        return forwardingResolveInfo;
6209    }
6210
6211    @Override
6212    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6213            Intent[] specifics, String[] specificTypes, Intent intent,
6214            String resolvedType, int flags, int userId) {
6215        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6216                specificTypes, intent, resolvedType, flags, userId));
6217    }
6218
6219    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6220            Intent[] specifics, String[] specificTypes, Intent intent,
6221            String resolvedType, int flags, int userId) {
6222        if (!sUserManager.exists(userId)) return Collections.emptyList();
6223        flags = updateFlagsForResolve(flags, userId, intent);
6224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6225                false /* requireFullPermission */, false /* checkShell */,
6226                "query intent activity options");
6227        final String resultsAction = intent.getAction();
6228
6229        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6230                | PackageManager.GET_RESOLVED_FILTER, userId);
6231
6232        if (DEBUG_INTENT_MATCHING) {
6233            Log.v(TAG, "Query " + intent + ": " + results);
6234        }
6235
6236        int specificsPos = 0;
6237        int N;
6238
6239        // todo: note that the algorithm used here is O(N^2).  This
6240        // isn't a problem in our current environment, but if we start running
6241        // into situations where we have more than 5 or 10 matches then this
6242        // should probably be changed to something smarter...
6243
6244        // First we go through and resolve each of the specific items
6245        // that were supplied, taking care of removing any corresponding
6246        // duplicate items in the generic resolve list.
6247        if (specifics != null) {
6248            for (int i=0; i<specifics.length; i++) {
6249                final Intent sintent = specifics[i];
6250                if (sintent == null) {
6251                    continue;
6252                }
6253
6254                if (DEBUG_INTENT_MATCHING) {
6255                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6256                }
6257
6258                String action = sintent.getAction();
6259                if (resultsAction != null && resultsAction.equals(action)) {
6260                    // If this action was explicitly requested, then don't
6261                    // remove things that have it.
6262                    action = null;
6263                }
6264
6265                ResolveInfo ri = null;
6266                ActivityInfo ai = null;
6267
6268                ComponentName comp = sintent.getComponent();
6269                if (comp == null) {
6270                    ri = resolveIntent(
6271                        sintent,
6272                        specificTypes != null ? specificTypes[i] : null,
6273                            flags, userId);
6274                    if (ri == null) {
6275                        continue;
6276                    }
6277                    if (ri == mResolveInfo) {
6278                        // ACK!  Must do something better with this.
6279                    }
6280                    ai = ri.activityInfo;
6281                    comp = new ComponentName(ai.applicationInfo.packageName,
6282                            ai.name);
6283                } else {
6284                    ai = getActivityInfo(comp, flags, userId);
6285                    if (ai == null) {
6286                        continue;
6287                    }
6288                }
6289
6290                // Look for any generic query activities that are duplicates
6291                // of this specific one, and remove them from the results.
6292                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6293                N = results.size();
6294                int j;
6295                for (j=specificsPos; j<N; j++) {
6296                    ResolveInfo sri = results.get(j);
6297                    if ((sri.activityInfo.name.equals(comp.getClassName())
6298                            && sri.activityInfo.applicationInfo.packageName.equals(
6299                                    comp.getPackageName()))
6300                        || (action != null && sri.filter.matchAction(action))) {
6301                        results.remove(j);
6302                        if (DEBUG_INTENT_MATCHING) Log.v(
6303                            TAG, "Removing duplicate item from " + j
6304                            + " due to specific " + specificsPos);
6305                        if (ri == null) {
6306                            ri = sri;
6307                        }
6308                        j--;
6309                        N--;
6310                    }
6311                }
6312
6313                // Add this specific item to its proper place.
6314                if (ri == null) {
6315                    ri = new ResolveInfo();
6316                    ri.activityInfo = ai;
6317                }
6318                results.add(specificsPos, ri);
6319                ri.specificIndex = i;
6320                specificsPos++;
6321            }
6322        }
6323
6324        // Now we go through the remaining generic results and remove any
6325        // duplicate actions that are found here.
6326        N = results.size();
6327        for (int i=specificsPos; i<N-1; i++) {
6328            final ResolveInfo rii = results.get(i);
6329            if (rii.filter == null) {
6330                continue;
6331            }
6332
6333            // Iterate over all of the actions of this result's intent
6334            // filter...  typically this should be just one.
6335            final Iterator<String> it = rii.filter.actionsIterator();
6336            if (it == null) {
6337                continue;
6338            }
6339            while (it.hasNext()) {
6340                final String action = it.next();
6341                if (resultsAction != null && resultsAction.equals(action)) {
6342                    // If this action was explicitly requested, then don't
6343                    // remove things that have it.
6344                    continue;
6345                }
6346                for (int j=i+1; j<N; j++) {
6347                    final ResolveInfo rij = results.get(j);
6348                    if (rij.filter != null && rij.filter.hasAction(action)) {
6349                        results.remove(j);
6350                        if (DEBUG_INTENT_MATCHING) Log.v(
6351                            TAG, "Removing duplicate item from " + j
6352                            + " due to action " + action + " at " + i);
6353                        j--;
6354                        N--;
6355                    }
6356                }
6357            }
6358
6359            // If the caller didn't request filter information, drop it now
6360            // so we don't have to marshall/unmarshall it.
6361            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6362                rii.filter = null;
6363            }
6364        }
6365
6366        // Filter out the caller activity if so requested.
6367        if (caller != null) {
6368            N = results.size();
6369            for (int i=0; i<N; i++) {
6370                ActivityInfo ainfo = results.get(i).activityInfo;
6371                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6372                        && caller.getClassName().equals(ainfo.name)) {
6373                    results.remove(i);
6374                    break;
6375                }
6376            }
6377        }
6378
6379        // If the caller didn't request filter information,
6380        // drop them now so we don't have to
6381        // marshall/unmarshall it.
6382        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6383            N = results.size();
6384            for (int i=0; i<N; i++) {
6385                results.get(i).filter = null;
6386            }
6387        }
6388
6389        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6390        return results;
6391    }
6392
6393    @Override
6394    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6395            String resolvedType, int flags, int userId) {
6396        return new ParceledListSlice<>(
6397                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6398    }
6399
6400    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6401            String resolvedType, int flags, int userId) {
6402        if (!sUserManager.exists(userId)) return Collections.emptyList();
6403        flags = updateFlagsForResolve(flags, userId, intent);
6404        ComponentName comp = intent.getComponent();
6405        if (comp == null) {
6406            if (intent.getSelector() != null) {
6407                intent = intent.getSelector();
6408                comp = intent.getComponent();
6409            }
6410        }
6411        if (comp != null) {
6412            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6413            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6414            if (ai != null) {
6415                ResolveInfo ri = new ResolveInfo();
6416                ri.activityInfo = ai;
6417                list.add(ri);
6418            }
6419            return list;
6420        }
6421
6422        // reader
6423        synchronized (mPackages) {
6424            String pkgName = intent.getPackage();
6425            if (pkgName == null) {
6426                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6427            }
6428            final PackageParser.Package pkg = mPackages.get(pkgName);
6429            if (pkg != null) {
6430                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6431                        userId);
6432            }
6433            return Collections.emptyList();
6434        }
6435    }
6436
6437    @Override
6438    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6439        if (!sUserManager.exists(userId)) return null;
6440        flags = updateFlagsForResolve(flags, userId, intent);
6441        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6442        if (query != null) {
6443            if (query.size() >= 1) {
6444                // If there is more than one service with the same priority,
6445                // just arbitrarily pick the first one.
6446                return query.get(0);
6447            }
6448        }
6449        return null;
6450    }
6451
6452    @Override
6453    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6454            String resolvedType, int flags, int userId) {
6455        return new ParceledListSlice<>(
6456                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6457    }
6458
6459    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6460            String resolvedType, int flags, int userId) {
6461        if (!sUserManager.exists(userId)) return Collections.emptyList();
6462        flags = updateFlagsForResolve(flags, userId, intent);
6463        ComponentName comp = intent.getComponent();
6464        if (comp == null) {
6465            if (intent.getSelector() != null) {
6466                intent = intent.getSelector();
6467                comp = intent.getComponent();
6468            }
6469        }
6470        if (comp != null) {
6471            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6472            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6473            if (si != null) {
6474                final ResolveInfo ri = new ResolveInfo();
6475                ri.serviceInfo = si;
6476                list.add(ri);
6477            }
6478            return list;
6479        }
6480
6481        // reader
6482        synchronized (mPackages) {
6483            String pkgName = intent.getPackage();
6484            if (pkgName == null) {
6485                return mServices.queryIntent(intent, resolvedType, flags, userId);
6486            }
6487            final PackageParser.Package pkg = mPackages.get(pkgName);
6488            if (pkg != null) {
6489                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6490                        userId);
6491            }
6492            return Collections.emptyList();
6493        }
6494    }
6495
6496    @Override
6497    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6498            String resolvedType, int flags, int userId) {
6499        return new ParceledListSlice<>(
6500                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6501    }
6502
6503    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6504            Intent intent, String resolvedType, int flags, int userId) {
6505        if (!sUserManager.exists(userId)) return Collections.emptyList();
6506        flags = updateFlagsForResolve(flags, userId, intent);
6507        ComponentName comp = intent.getComponent();
6508        if (comp == null) {
6509            if (intent.getSelector() != null) {
6510                intent = intent.getSelector();
6511                comp = intent.getComponent();
6512            }
6513        }
6514        if (comp != null) {
6515            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6516            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6517            if (pi != null) {
6518                final ResolveInfo ri = new ResolveInfo();
6519                ri.providerInfo = pi;
6520                list.add(ri);
6521            }
6522            return list;
6523        }
6524
6525        // reader
6526        synchronized (mPackages) {
6527            String pkgName = intent.getPackage();
6528            if (pkgName == null) {
6529                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6530            }
6531            final PackageParser.Package pkg = mPackages.get(pkgName);
6532            if (pkg != null) {
6533                return mProviders.queryIntentForPackage(
6534                        intent, resolvedType, flags, pkg.providers, userId);
6535            }
6536            return Collections.emptyList();
6537        }
6538    }
6539
6540    @Override
6541    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6542        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6543        flags = updateFlagsForPackage(flags, userId, null);
6544        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6546                true /* requireFullPermission */, false /* checkShell */,
6547                "get installed packages");
6548
6549        // writer
6550        synchronized (mPackages) {
6551            ArrayList<PackageInfo> list;
6552            if (listUninstalled) {
6553                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6554                for (PackageSetting ps : mSettings.mPackages.values()) {
6555                    final PackageInfo pi;
6556                    if (ps.pkg != null) {
6557                        pi = generatePackageInfo(ps, flags, userId);
6558                    } else {
6559                        pi = generatePackageInfo(ps, flags, userId);
6560                    }
6561                    if (pi != null) {
6562                        list.add(pi);
6563                    }
6564                }
6565            } else {
6566                list = new ArrayList<PackageInfo>(mPackages.size());
6567                for (PackageParser.Package p : mPackages.values()) {
6568                    final PackageInfo pi =
6569                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6570                    if (pi != null) {
6571                        list.add(pi);
6572                    }
6573                }
6574            }
6575
6576            return new ParceledListSlice<PackageInfo>(list);
6577        }
6578    }
6579
6580    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6581            String[] permissions, boolean[] tmp, int flags, int userId) {
6582        int numMatch = 0;
6583        final PermissionsState permissionsState = ps.getPermissionsState();
6584        for (int i=0; i<permissions.length; i++) {
6585            final String permission = permissions[i];
6586            if (permissionsState.hasPermission(permission, userId)) {
6587                tmp[i] = true;
6588                numMatch++;
6589            } else {
6590                tmp[i] = false;
6591            }
6592        }
6593        if (numMatch == 0) {
6594            return;
6595        }
6596        final PackageInfo pi;
6597        if (ps.pkg != null) {
6598            pi = generatePackageInfo(ps, flags, userId);
6599        } else {
6600            pi = generatePackageInfo(ps, flags, userId);
6601        }
6602        // The above might return null in cases of uninstalled apps or install-state
6603        // skew across users/profiles.
6604        if (pi != null) {
6605            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6606                if (numMatch == permissions.length) {
6607                    pi.requestedPermissions = permissions;
6608                } else {
6609                    pi.requestedPermissions = new String[numMatch];
6610                    numMatch = 0;
6611                    for (int i=0; i<permissions.length; i++) {
6612                        if (tmp[i]) {
6613                            pi.requestedPermissions[numMatch] = permissions[i];
6614                            numMatch++;
6615                        }
6616                    }
6617                }
6618            }
6619            list.add(pi);
6620        }
6621    }
6622
6623    @Override
6624    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6625            String[] permissions, int flags, int userId) {
6626        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6627        flags = updateFlagsForPackage(flags, userId, permissions);
6628        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6629                true /* requireFullPermission */, false /* checkShell */,
6630                "get packages holding permissions");
6631        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6632
6633        // writer
6634        synchronized (mPackages) {
6635            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6636            boolean[] tmpBools = new boolean[permissions.length];
6637            if (listUninstalled) {
6638                for (PackageSetting ps : mSettings.mPackages.values()) {
6639                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6640                            userId);
6641                }
6642            } else {
6643                for (PackageParser.Package pkg : mPackages.values()) {
6644                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6645                    if (ps != null) {
6646                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6647                                userId);
6648                    }
6649                }
6650            }
6651
6652            return new ParceledListSlice<PackageInfo>(list);
6653        }
6654    }
6655
6656    @Override
6657    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6658        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6659        flags = updateFlagsForApplication(flags, userId, null);
6660        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6661
6662        // writer
6663        synchronized (mPackages) {
6664            ArrayList<ApplicationInfo> list;
6665            if (listUninstalled) {
6666                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6667                for (PackageSetting ps : mSettings.mPackages.values()) {
6668                    ApplicationInfo ai;
6669                    int effectiveFlags = flags;
6670                    if (ps.isSystem()) {
6671                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6672                    }
6673                    if (ps.pkg != null) {
6674                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6675                                ps.readUserState(userId), userId);
6676                    } else {
6677                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6678                                userId);
6679                    }
6680                    if (ai != null) {
6681                        list.add(ai);
6682                    }
6683                }
6684            } else {
6685                list = new ArrayList<ApplicationInfo>(mPackages.size());
6686                for (PackageParser.Package p : mPackages.values()) {
6687                    if (p.mExtras != null) {
6688                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6689                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6690                        if (ai != null) {
6691                            list.add(ai);
6692                        }
6693                    }
6694                }
6695            }
6696
6697            return new ParceledListSlice<ApplicationInfo>(list);
6698        }
6699    }
6700
6701    @Override
6702    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6703        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6704            return null;
6705        }
6706
6707        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6708                "getEphemeralApplications");
6709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6710                true /* requireFullPermission */, false /* checkShell */,
6711                "getEphemeralApplications");
6712        synchronized (mPackages) {
6713            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6714                    .getEphemeralApplicationsLPw(userId);
6715            if (ephemeralApps != null) {
6716                return new ParceledListSlice<>(ephemeralApps);
6717            }
6718        }
6719        return null;
6720    }
6721
6722    @Override
6723    public boolean isEphemeralApplication(String packageName, int userId) {
6724        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6725                true /* requireFullPermission */, false /* checkShell */,
6726                "isEphemeral");
6727        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6728            return false;
6729        }
6730
6731        if (!isCallerSameApp(packageName)) {
6732            return false;
6733        }
6734        synchronized (mPackages) {
6735            PackageParser.Package pkg = mPackages.get(packageName);
6736            if (pkg != null) {
6737                return pkg.applicationInfo.isEphemeralApp();
6738            }
6739        }
6740        return false;
6741    }
6742
6743    @Override
6744    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6745        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6746            return null;
6747        }
6748
6749        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6750                true /* requireFullPermission */, false /* checkShell */,
6751                "getCookie");
6752        if (!isCallerSameApp(packageName)) {
6753            return null;
6754        }
6755        synchronized (mPackages) {
6756            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6757                    packageName, userId);
6758        }
6759    }
6760
6761    @Override
6762    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6763        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6764            return true;
6765        }
6766
6767        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6768                true /* requireFullPermission */, true /* checkShell */,
6769                "setCookie");
6770        if (!isCallerSameApp(packageName)) {
6771            return false;
6772        }
6773        synchronized (mPackages) {
6774            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6775                    packageName, cookie, userId);
6776        }
6777    }
6778
6779    @Override
6780    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6781        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6782            return null;
6783        }
6784
6785        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6786                "getEphemeralApplicationIcon");
6787        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6788                true /* requireFullPermission */, false /* checkShell */,
6789                "getEphemeralApplicationIcon");
6790        synchronized (mPackages) {
6791            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6792                    packageName, userId);
6793        }
6794    }
6795
6796    private boolean isCallerSameApp(String packageName) {
6797        PackageParser.Package pkg = mPackages.get(packageName);
6798        return pkg != null
6799                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6800    }
6801
6802    @Override
6803    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6804        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6805    }
6806
6807    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6808        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6809
6810        // reader
6811        synchronized (mPackages) {
6812            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6813            final int userId = UserHandle.getCallingUserId();
6814            while (i.hasNext()) {
6815                final PackageParser.Package p = i.next();
6816                if (p.applicationInfo == null) continue;
6817
6818                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6819                        && !p.applicationInfo.isDirectBootAware();
6820                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6821                        && p.applicationInfo.isDirectBootAware();
6822
6823                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6824                        && (!mSafeMode || isSystemApp(p))
6825                        && (matchesUnaware || matchesAware)) {
6826                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6827                    if (ps != null) {
6828                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6829                                ps.readUserState(userId), userId);
6830                        if (ai != null) {
6831                            finalList.add(ai);
6832                        }
6833                    }
6834                }
6835            }
6836        }
6837
6838        return finalList;
6839    }
6840
6841    @Override
6842    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6843        if (!sUserManager.exists(userId)) return null;
6844        flags = updateFlagsForComponent(flags, userId, name);
6845        // reader
6846        synchronized (mPackages) {
6847            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6848            PackageSetting ps = provider != null
6849                    ? mSettings.mPackages.get(provider.owner.packageName)
6850                    : null;
6851            return ps != null
6852                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6853                    ? PackageParser.generateProviderInfo(provider, flags,
6854                            ps.readUserState(userId), userId)
6855                    : null;
6856        }
6857    }
6858
6859    /**
6860     * @deprecated
6861     */
6862    @Deprecated
6863    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6864        // reader
6865        synchronized (mPackages) {
6866            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6867                    .entrySet().iterator();
6868            final int userId = UserHandle.getCallingUserId();
6869            while (i.hasNext()) {
6870                Map.Entry<String, PackageParser.Provider> entry = i.next();
6871                PackageParser.Provider p = entry.getValue();
6872                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6873
6874                if (ps != null && p.syncable
6875                        && (!mSafeMode || (p.info.applicationInfo.flags
6876                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6877                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6878                            ps.readUserState(userId), userId);
6879                    if (info != null) {
6880                        outNames.add(entry.getKey());
6881                        outInfo.add(info);
6882                    }
6883                }
6884            }
6885        }
6886    }
6887
6888    @Override
6889    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6890            int uid, int flags) {
6891        final int userId = processName != null ? UserHandle.getUserId(uid)
6892                : UserHandle.getCallingUserId();
6893        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6894        flags = updateFlagsForComponent(flags, userId, processName);
6895
6896        ArrayList<ProviderInfo> finalList = null;
6897        // reader
6898        synchronized (mPackages) {
6899            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6900            while (i.hasNext()) {
6901                final PackageParser.Provider p = i.next();
6902                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6903                if (ps != null && p.info.authority != null
6904                        && (processName == null
6905                                || (p.info.processName.equals(processName)
6906                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6907                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6908                    if (finalList == null) {
6909                        finalList = new ArrayList<ProviderInfo>(3);
6910                    }
6911                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6912                            ps.readUserState(userId), userId);
6913                    if (info != null) {
6914                        finalList.add(info);
6915                    }
6916                }
6917            }
6918        }
6919
6920        if (finalList != null) {
6921            Collections.sort(finalList, mProviderInitOrderSorter);
6922            return new ParceledListSlice<ProviderInfo>(finalList);
6923        }
6924
6925        return ParceledListSlice.emptyList();
6926    }
6927
6928    @Override
6929    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6930        // reader
6931        synchronized (mPackages) {
6932            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6933            return PackageParser.generateInstrumentationInfo(i, flags);
6934        }
6935    }
6936
6937    @Override
6938    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6939            String targetPackage, int flags) {
6940        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6941    }
6942
6943    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6944            int flags) {
6945        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6946
6947        // reader
6948        synchronized (mPackages) {
6949            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6950            while (i.hasNext()) {
6951                final PackageParser.Instrumentation p = i.next();
6952                if (targetPackage == null
6953                        || targetPackage.equals(p.info.targetPackage)) {
6954                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6955                            flags);
6956                    if (ii != null) {
6957                        finalList.add(ii);
6958                    }
6959                }
6960            }
6961        }
6962
6963        return finalList;
6964    }
6965
6966    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6967        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6968        if (overlays == null) {
6969            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6970            return;
6971        }
6972        for (PackageParser.Package opkg : overlays.values()) {
6973            // Not much to do if idmap fails: we already logged the error
6974            // and we certainly don't want to abort installation of pkg simply
6975            // because an overlay didn't fit properly. For these reasons,
6976            // ignore the return value of createIdmapForPackagePairLI.
6977            createIdmapForPackagePairLI(pkg, opkg);
6978        }
6979    }
6980
6981    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6982            PackageParser.Package opkg) {
6983        if (!opkg.mTrustedOverlay) {
6984            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6985                    opkg.baseCodePath + ": overlay not trusted");
6986            return false;
6987        }
6988        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6989        if (overlaySet == null) {
6990            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6991                    opkg.baseCodePath + " but target package has no known overlays");
6992            return false;
6993        }
6994        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6995        // TODO: generate idmap for split APKs
6996        try {
6997            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6998        } catch (InstallerException e) {
6999            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7000                    + opkg.baseCodePath);
7001            return false;
7002        }
7003        PackageParser.Package[] overlayArray =
7004            overlaySet.values().toArray(new PackageParser.Package[0]);
7005        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7006            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7007                return p1.mOverlayPriority - p2.mOverlayPriority;
7008            }
7009        };
7010        Arrays.sort(overlayArray, cmp);
7011
7012        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7013        int i = 0;
7014        for (PackageParser.Package p : overlayArray) {
7015            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7016        }
7017        return true;
7018    }
7019
7020    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7021        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7022        try {
7023            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7024        } finally {
7025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7026        }
7027    }
7028
7029    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7030        final File[] files = dir.listFiles();
7031        if (ArrayUtils.isEmpty(files)) {
7032            Log.d(TAG, "No files in app dir " + dir);
7033            return;
7034        }
7035
7036        if (DEBUG_PACKAGE_SCANNING) {
7037            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7038                    + " flags=0x" + Integer.toHexString(parseFlags));
7039        }
7040        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7041                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7042
7043        // Submit files for parsing in parallel
7044        int fileCount = 0;
7045        for (File file : files) {
7046            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7047                    && !PackageInstallerService.isStageName(file.getName());
7048            if (!isPackage) {
7049                // Ignore entries which are not packages
7050                continue;
7051            }
7052            parallelPackageParser.submit(file, parseFlags);
7053            fileCount++;
7054        }
7055
7056        // Process results one by one
7057        for (; fileCount > 0; fileCount--) {
7058            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7059            Throwable throwable = parseResult.throwable;
7060            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7061
7062            if (throwable == null) {
7063                try {
7064                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7065                            currentTime, null);
7066                } catch (PackageManagerException e) {
7067                    errorCode = e.error;
7068                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7069                }
7070            } else if (throwable instanceof PackageParser.PackageParserException) {
7071                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7072                        throwable;
7073                errorCode = e.error;
7074                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7075            } else {
7076                throw new IllegalStateException("Unexpected exception occurred while parsing "
7077                        + parseResult.scanFile, throwable);
7078            }
7079
7080            // Delete invalid userdata apps
7081            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7082                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7083                logCriticalInfo(Log.WARN,
7084                        "Deleting invalid package at " + parseResult.scanFile);
7085                removeCodePathLI(parseResult.scanFile);
7086            }
7087        }
7088        parallelPackageParser.close();
7089    }
7090
7091    private static File getSettingsProblemFile() {
7092        File dataDir = Environment.getDataDirectory();
7093        File systemDir = new File(dataDir, "system");
7094        File fname = new File(systemDir, "uiderrors.txt");
7095        return fname;
7096    }
7097
7098    static void reportSettingsProblem(int priority, String msg) {
7099        logCriticalInfo(priority, msg);
7100    }
7101
7102    static void logCriticalInfo(int priority, String msg) {
7103        Slog.println(priority, TAG, msg);
7104        EventLogTags.writePmCriticalInfo(msg);
7105        try {
7106            File fname = getSettingsProblemFile();
7107            FileOutputStream out = new FileOutputStream(fname, true);
7108            PrintWriter pw = new FastPrintWriter(out);
7109            SimpleDateFormat formatter = new SimpleDateFormat();
7110            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7111            pw.println(dateString + ": " + msg);
7112            pw.close();
7113            FileUtils.setPermissions(
7114                    fname.toString(),
7115                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7116                    -1, -1);
7117        } catch (java.io.IOException e) {
7118        }
7119    }
7120
7121    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7122        if (srcFile.isDirectory()) {
7123            final File baseFile = new File(pkg.baseCodePath);
7124            long maxModifiedTime = baseFile.lastModified();
7125            if (pkg.splitCodePaths != null) {
7126                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7127                    final File splitFile = new File(pkg.splitCodePaths[i]);
7128                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7129                }
7130            }
7131            return maxModifiedTime;
7132        }
7133        return srcFile.lastModified();
7134    }
7135
7136    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7137            final int policyFlags) throws PackageManagerException {
7138        // When upgrading from pre-N MR1, verify the package time stamp using the package
7139        // directory and not the APK file.
7140        final long lastModifiedTime = mIsPreNMR1Upgrade
7141                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7142        if (ps != null
7143                && ps.codePath.equals(srcFile)
7144                && ps.timeStamp == lastModifiedTime
7145                && !isCompatSignatureUpdateNeeded(pkg)
7146                && !isRecoverSignatureUpdateNeeded(pkg)) {
7147            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7148            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7149            ArraySet<PublicKey> signingKs;
7150            synchronized (mPackages) {
7151                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7152            }
7153            if (ps.signatures.mSignatures != null
7154                    && ps.signatures.mSignatures.length != 0
7155                    && signingKs != null) {
7156                // Optimization: reuse the existing cached certificates
7157                // if the package appears to be unchanged.
7158                pkg.mSignatures = ps.signatures.mSignatures;
7159                pkg.mSigningKeys = signingKs;
7160                return;
7161            }
7162
7163            Slog.w(TAG, "PackageSetting for " + ps.name
7164                    + " is missing signatures.  Collecting certs again to recover them.");
7165        } else {
7166            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7167        }
7168
7169        try {
7170            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7171            PackageParser.collectCertificates(pkg, policyFlags);
7172        } catch (PackageParserException e) {
7173            throw PackageManagerException.from(e);
7174        } finally {
7175            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7176        }
7177    }
7178
7179    /**
7180     *  Traces a package scan.
7181     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7182     */
7183    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7184            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7185        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7186        try {
7187            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7188        } finally {
7189            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7190        }
7191    }
7192
7193    /**
7194     *  Scans a package and returns the newly parsed package.
7195     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7196     */
7197    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7198            long currentTime, UserHandle user) throws PackageManagerException {
7199        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7200        PackageParser pp = new PackageParser();
7201        pp.setSeparateProcesses(mSeparateProcesses);
7202        pp.setOnlyCoreApps(mOnlyCore);
7203        pp.setDisplayMetrics(mMetrics);
7204
7205        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7206            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7207        }
7208
7209        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7210        final PackageParser.Package pkg;
7211        try {
7212            pkg = pp.parsePackage(scanFile, parseFlags);
7213        } catch (PackageParserException e) {
7214            throw PackageManagerException.from(e);
7215        } finally {
7216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7217        }
7218
7219        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7220    }
7221
7222    /**
7223     *  Scans a package and returns the newly parsed package.
7224     *  @throws PackageManagerException on a parse error.
7225     */
7226    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7227            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7228            throws PackageManagerException {
7229        // If the package has children and this is the first dive in the function
7230        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7231        // packages (parent and children) would be successfully scanned before the
7232        // actual scan since scanning mutates internal state and we want to atomically
7233        // install the package and its children.
7234        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7235            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7236                scanFlags |= SCAN_CHECK_ONLY;
7237            }
7238        } else {
7239            scanFlags &= ~SCAN_CHECK_ONLY;
7240        }
7241
7242        // Scan the parent
7243        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7244                scanFlags, currentTime, user);
7245
7246        // Scan the children
7247        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7248        for (int i = 0; i < childCount; i++) {
7249            PackageParser.Package childPackage = pkg.childPackages.get(i);
7250            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7251                    currentTime, user);
7252        }
7253
7254
7255        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7256            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7257        }
7258
7259        return scannedPkg;
7260    }
7261
7262    /**
7263     *  Scans a package and returns the newly parsed package.
7264     *  @throws PackageManagerException on a parse error.
7265     */
7266    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7267            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7268            throws PackageManagerException {
7269        PackageSetting ps = null;
7270        PackageSetting updatedPkg;
7271        // reader
7272        synchronized (mPackages) {
7273            // Look to see if we already know about this package.
7274            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7275            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7276                // This package has been renamed to its original name.  Let's
7277                // use that.
7278                ps = mSettings.getPackageLPr(oldName);
7279            }
7280            // If there was no original package, see one for the real package name.
7281            if (ps == null) {
7282                ps = mSettings.getPackageLPr(pkg.packageName);
7283            }
7284            // Check to see if this package could be hiding/updating a system
7285            // package.  Must look for it either under the original or real
7286            // package name depending on our state.
7287            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7288            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7289
7290            // If this is a package we don't know about on the system partition, we
7291            // may need to remove disabled child packages on the system partition
7292            // or may need to not add child packages if the parent apk is updated
7293            // on the data partition and no longer defines this child package.
7294            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7295                // If this is a parent package for an updated system app and this system
7296                // app got an OTA update which no longer defines some of the child packages
7297                // we have to prune them from the disabled system packages.
7298                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7299                if (disabledPs != null) {
7300                    final int scannedChildCount = (pkg.childPackages != null)
7301                            ? pkg.childPackages.size() : 0;
7302                    final int disabledChildCount = disabledPs.childPackageNames != null
7303                            ? disabledPs.childPackageNames.size() : 0;
7304                    for (int i = 0; i < disabledChildCount; i++) {
7305                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7306                        boolean disabledPackageAvailable = false;
7307                        for (int j = 0; j < scannedChildCount; j++) {
7308                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7309                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7310                                disabledPackageAvailable = true;
7311                                break;
7312                            }
7313                         }
7314                         if (!disabledPackageAvailable) {
7315                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7316                         }
7317                    }
7318                }
7319            }
7320        }
7321
7322        boolean updatedPkgBetter = false;
7323        // First check if this is a system package that may involve an update
7324        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7325            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7326            // it needs to drop FLAG_PRIVILEGED.
7327            if (locationIsPrivileged(scanFile)) {
7328                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7329            } else {
7330                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7331            }
7332
7333            if (ps != null && !ps.codePath.equals(scanFile)) {
7334                // The path has changed from what was last scanned...  check the
7335                // version of the new path against what we have stored to determine
7336                // what to do.
7337                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7338                if (pkg.mVersionCode <= ps.versionCode) {
7339                    // The system package has been updated and the code path does not match
7340                    // Ignore entry. Skip it.
7341                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7342                            + " ignored: updated version " + ps.versionCode
7343                            + " better than this " + pkg.mVersionCode);
7344                    if (!updatedPkg.codePath.equals(scanFile)) {
7345                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7346                                + ps.name + " changing from " + updatedPkg.codePathString
7347                                + " to " + scanFile);
7348                        updatedPkg.codePath = scanFile;
7349                        updatedPkg.codePathString = scanFile.toString();
7350                        updatedPkg.resourcePath = scanFile;
7351                        updatedPkg.resourcePathString = scanFile.toString();
7352                    }
7353                    updatedPkg.pkg = pkg;
7354                    updatedPkg.versionCode = pkg.mVersionCode;
7355
7356                    // Update the disabled system child packages to point to the package too.
7357                    final int childCount = updatedPkg.childPackageNames != null
7358                            ? updatedPkg.childPackageNames.size() : 0;
7359                    for (int i = 0; i < childCount; i++) {
7360                        String childPackageName = updatedPkg.childPackageNames.get(i);
7361                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7362                                childPackageName);
7363                        if (updatedChildPkg != null) {
7364                            updatedChildPkg.pkg = pkg;
7365                            updatedChildPkg.versionCode = pkg.mVersionCode;
7366                        }
7367                    }
7368
7369                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7370                            + scanFile + " ignored: updated version " + ps.versionCode
7371                            + " better than this " + pkg.mVersionCode);
7372                } else {
7373                    // The current app on the system partition is better than
7374                    // what we have updated to on the data partition; switch
7375                    // back to the system partition version.
7376                    // At this point, its safely assumed that package installation for
7377                    // apps in system partition will go through. If not there won't be a working
7378                    // version of the app
7379                    // writer
7380                    synchronized (mPackages) {
7381                        // Just remove the loaded entries from package lists.
7382                        mPackages.remove(ps.name);
7383                    }
7384
7385                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7386                            + " reverting from " + ps.codePathString
7387                            + ": new version " + pkg.mVersionCode
7388                            + " better than installed " + ps.versionCode);
7389
7390                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7391                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7392                    synchronized (mInstallLock) {
7393                        args.cleanUpResourcesLI();
7394                    }
7395                    synchronized (mPackages) {
7396                        mSettings.enableSystemPackageLPw(ps.name);
7397                    }
7398                    updatedPkgBetter = true;
7399                }
7400            }
7401        }
7402
7403        if (updatedPkg != null) {
7404            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7405            // initially
7406            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7407
7408            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7409            // flag set initially
7410            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7411                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7412            }
7413        }
7414
7415        // Verify certificates against what was last scanned
7416        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7417
7418        /*
7419         * A new system app appeared, but we already had a non-system one of the
7420         * same name installed earlier.
7421         */
7422        boolean shouldHideSystemApp = false;
7423        if (updatedPkg == null && ps != null
7424                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7425            /*
7426             * Check to make sure the signatures match first. If they don't,
7427             * wipe the installed application and its data.
7428             */
7429            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7430                    != PackageManager.SIGNATURE_MATCH) {
7431                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7432                        + " signatures don't match existing userdata copy; removing");
7433                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7434                        "scanPackageInternalLI")) {
7435                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7436                }
7437                ps = null;
7438            } else {
7439                /*
7440                 * If the newly-added system app is an older version than the
7441                 * already installed version, hide it. It will be scanned later
7442                 * and re-added like an update.
7443                 */
7444                if (pkg.mVersionCode <= ps.versionCode) {
7445                    shouldHideSystemApp = true;
7446                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7447                            + " but new version " + pkg.mVersionCode + " better than installed "
7448                            + ps.versionCode + "; hiding system");
7449                } else {
7450                    /*
7451                     * The newly found system app is a newer version that the
7452                     * one previously installed. Simply remove the
7453                     * already-installed application and replace it with our own
7454                     * while keeping the application data.
7455                     */
7456                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7457                            + " reverting from " + ps.codePathString + ": new version "
7458                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7459                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7460                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7461                    synchronized (mInstallLock) {
7462                        args.cleanUpResourcesLI();
7463                    }
7464                }
7465            }
7466        }
7467
7468        // The apk is forward locked (not public) if its code and resources
7469        // are kept in different files. (except for app in either system or
7470        // vendor path).
7471        // TODO grab this value from PackageSettings
7472        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7473            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7474                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7475            }
7476        }
7477
7478        // TODO: extend to support forward-locked splits
7479        String resourcePath = null;
7480        String baseResourcePath = null;
7481        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7482            if (ps != null && ps.resourcePathString != null) {
7483                resourcePath = ps.resourcePathString;
7484                baseResourcePath = ps.resourcePathString;
7485            } else {
7486                // Should not happen at all. Just log an error.
7487                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7488            }
7489        } else {
7490            resourcePath = pkg.codePath;
7491            baseResourcePath = pkg.baseCodePath;
7492        }
7493
7494        // Set application objects path explicitly.
7495        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7496        pkg.setApplicationInfoCodePath(pkg.codePath);
7497        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7498        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7499        pkg.setApplicationInfoResourcePath(resourcePath);
7500        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7501        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7502
7503        // Note that we invoke the following method only if we are about to unpack an application
7504        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7505                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7506
7507        /*
7508         * If the system app should be overridden by a previously installed
7509         * data, hide the system app now and let the /data/app scan pick it up
7510         * again.
7511         */
7512        if (shouldHideSystemApp) {
7513            synchronized (mPackages) {
7514                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7515            }
7516        }
7517
7518        return scannedPkg;
7519    }
7520
7521    private static String fixProcessName(String defProcessName,
7522            String processName) {
7523        if (processName == null) {
7524            return defProcessName;
7525        }
7526        return processName;
7527    }
7528
7529    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7530            throws PackageManagerException {
7531        if (pkgSetting.signatures.mSignatures != null) {
7532            // Already existing package. Make sure signatures match
7533            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7534                    == PackageManager.SIGNATURE_MATCH;
7535            if (!match) {
7536                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7537                        == PackageManager.SIGNATURE_MATCH;
7538            }
7539            if (!match) {
7540                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7541                        == PackageManager.SIGNATURE_MATCH;
7542            }
7543            if (!match) {
7544                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7545                        + pkg.packageName + " signatures do not match the "
7546                        + "previously installed version; ignoring!");
7547            }
7548        }
7549
7550        // Check for shared user signatures
7551        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7552            // Already existing package. Make sure signatures match
7553            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7554                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7555            if (!match) {
7556                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7557                        == PackageManager.SIGNATURE_MATCH;
7558            }
7559            if (!match) {
7560                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7561                        == PackageManager.SIGNATURE_MATCH;
7562            }
7563            if (!match) {
7564                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7565                        "Package " + pkg.packageName
7566                        + " has no signatures that match those in shared user "
7567                        + pkgSetting.sharedUser.name + "; ignoring!");
7568            }
7569        }
7570    }
7571
7572    /**
7573     * Enforces that only the system UID or root's UID can call a method exposed
7574     * via Binder.
7575     *
7576     * @param message used as message if SecurityException is thrown
7577     * @throws SecurityException if the caller is not system or root
7578     */
7579    private static final void enforceSystemOrRoot(String message) {
7580        final int uid = Binder.getCallingUid();
7581        if (uid != Process.SYSTEM_UID && uid != 0) {
7582            throw new SecurityException(message);
7583        }
7584    }
7585
7586    @Override
7587    public void performFstrimIfNeeded() {
7588        enforceSystemOrRoot("Only the system can request fstrim");
7589
7590        // Before everything else, see whether we need to fstrim.
7591        try {
7592            IStorageManager sm = PackageHelper.getStorageManager();
7593            if (sm != null) {
7594                boolean doTrim = false;
7595                final long interval = android.provider.Settings.Global.getLong(
7596                        mContext.getContentResolver(),
7597                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7598                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7599                if (interval > 0) {
7600                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7601                    if (timeSinceLast > interval) {
7602                        doTrim = true;
7603                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7604                                + "; running immediately");
7605                    }
7606                }
7607                if (doTrim) {
7608                    final boolean dexOptDialogShown;
7609                    synchronized (mPackages) {
7610                        dexOptDialogShown = mDexOptDialogShown;
7611                    }
7612                    if (!isFirstBoot() && dexOptDialogShown) {
7613                        try {
7614                            ActivityManager.getService().showBootMessage(
7615                                    mContext.getResources().getString(
7616                                            R.string.android_upgrading_fstrim), true);
7617                        } catch (RemoteException e) {
7618                        }
7619                    }
7620                    sm.runMaintenance();
7621                }
7622            } else {
7623                Slog.e(TAG, "storageManager service unavailable!");
7624            }
7625        } catch (RemoteException e) {
7626            // Can't happen; StorageManagerService is local
7627        }
7628    }
7629
7630    @Override
7631    public void updatePackagesIfNeeded() {
7632        enforceSystemOrRoot("Only the system can request package update");
7633
7634        // We need to re-extract after an OTA.
7635        boolean causeUpgrade = isUpgrade();
7636
7637        // First boot or factory reset.
7638        // Note: we also handle devices that are upgrading to N right now as if it is their
7639        //       first boot, as they do not have profile data.
7640        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7641
7642        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7643        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7644
7645        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7646            return;
7647        }
7648
7649        List<PackageParser.Package> pkgs;
7650        synchronized (mPackages) {
7651            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7652        }
7653
7654        final long startTime = System.nanoTime();
7655        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7656                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7657
7658        final int elapsedTimeSeconds =
7659                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7660
7661        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7662        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7663        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7664        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7665        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7666    }
7667
7668    /**
7669     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7670     * containing statistics about the invocation. The array consists of three elements,
7671     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7672     * and {@code numberOfPackagesFailed}.
7673     */
7674    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7675            String compilerFilter) {
7676
7677        int numberOfPackagesVisited = 0;
7678        int numberOfPackagesOptimized = 0;
7679        int numberOfPackagesSkipped = 0;
7680        int numberOfPackagesFailed = 0;
7681        final int numberOfPackagesToDexopt = pkgs.size();
7682
7683        for (PackageParser.Package pkg : pkgs) {
7684            numberOfPackagesVisited++;
7685
7686            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7687                if (DEBUG_DEXOPT) {
7688                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7689                }
7690                numberOfPackagesSkipped++;
7691                continue;
7692            }
7693
7694            if (DEBUG_DEXOPT) {
7695                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7696                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7697            }
7698
7699            if (showDialog) {
7700                try {
7701                    ActivityManager.getService().showBootMessage(
7702                            mContext.getResources().getString(R.string.android_upgrading_apk,
7703                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7704                } catch (RemoteException e) {
7705                }
7706                synchronized (mPackages) {
7707                    mDexOptDialogShown = true;
7708                }
7709            }
7710
7711            // If the OTA updates a system app which was previously preopted to a non-preopted state
7712            // the app might end up being verified at runtime. That's because by default the apps
7713            // are verify-profile but for preopted apps there's no profile.
7714            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7715            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7716            // filter (by default interpret-only).
7717            // Note that at this stage unused apps are already filtered.
7718            if (isSystemApp(pkg) &&
7719                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7720                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7721                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7722            }
7723
7724            // checkProfiles is false to avoid merging profiles during boot which
7725            // might interfere with background compilation (b/28612421).
7726            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7727            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7728            // trade-off worth doing to save boot time work.
7729            int dexOptStatus = performDexOptTraced(pkg.packageName,
7730                    false /* checkProfiles */,
7731                    compilerFilter,
7732                    false /* force */);
7733            switch (dexOptStatus) {
7734                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7735                    numberOfPackagesOptimized++;
7736                    break;
7737                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7738                    numberOfPackagesSkipped++;
7739                    break;
7740                case PackageDexOptimizer.DEX_OPT_FAILED:
7741                    numberOfPackagesFailed++;
7742                    break;
7743                default:
7744                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7745                    break;
7746            }
7747        }
7748
7749        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7750                numberOfPackagesFailed };
7751    }
7752
7753    @Override
7754    public void notifyPackageUse(String packageName, int reason) {
7755        synchronized (mPackages) {
7756            PackageParser.Package p = mPackages.get(packageName);
7757            if (p == null) {
7758                return;
7759            }
7760            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7761        }
7762    }
7763
7764    @Override
7765    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7766        int userId = UserHandle.getCallingUserId();
7767        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7768        if (ai == null) {
7769            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7770                + loadingPackageName + ", user=" + userId);
7771            return;
7772        }
7773        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7774    }
7775
7776    // TODO: this is not used nor needed. Delete it.
7777    @Override
7778    public boolean performDexOptIfNeeded(String packageName) {
7779        int dexOptStatus = performDexOptTraced(packageName,
7780                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7781        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7782    }
7783
7784    @Override
7785    public boolean performDexOpt(String packageName,
7786            boolean checkProfiles, int compileReason, boolean force) {
7787        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7788                getCompilerFilterForReason(compileReason), force);
7789        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7790    }
7791
7792    @Override
7793    public boolean performDexOptMode(String packageName,
7794            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7795        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7796                targetCompilerFilter, force);
7797        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7798    }
7799
7800    private int performDexOptTraced(String packageName,
7801                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7803        try {
7804            return performDexOptInternal(packageName, checkProfiles,
7805                    targetCompilerFilter, force);
7806        } finally {
7807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7808        }
7809    }
7810
7811    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7812    // if the package can now be considered up to date for the given filter.
7813    private int performDexOptInternal(String packageName,
7814                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7815        PackageParser.Package p;
7816        synchronized (mPackages) {
7817            p = mPackages.get(packageName);
7818            if (p == null) {
7819                // Package could not be found. Report failure.
7820                return PackageDexOptimizer.DEX_OPT_FAILED;
7821            }
7822            mPackageUsage.maybeWriteAsync(mPackages);
7823            mCompilerStats.maybeWriteAsync();
7824        }
7825        long callingId = Binder.clearCallingIdentity();
7826        try {
7827            synchronized (mInstallLock) {
7828                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7829                        targetCompilerFilter, force);
7830            }
7831        } finally {
7832            Binder.restoreCallingIdentity(callingId);
7833        }
7834    }
7835
7836    public ArraySet<String> getOptimizablePackages() {
7837        ArraySet<String> pkgs = new ArraySet<String>();
7838        synchronized (mPackages) {
7839            for (PackageParser.Package p : mPackages.values()) {
7840                if (PackageDexOptimizer.canOptimizePackage(p)) {
7841                    pkgs.add(p.packageName);
7842                }
7843            }
7844        }
7845        return pkgs;
7846    }
7847
7848    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7849            boolean checkProfiles, String targetCompilerFilter,
7850            boolean force) {
7851        // Select the dex optimizer based on the force parameter.
7852        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7853        //       allocate an object here.
7854        PackageDexOptimizer pdo = force
7855                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7856                : mPackageDexOptimizer;
7857
7858        // Optimize all dependencies first. Note: we ignore the return value and march on
7859        // on errors.
7860        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7861        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7862        if (!deps.isEmpty()) {
7863            for (PackageParser.Package depPackage : deps) {
7864                // TODO: Analyze and investigate if we (should) profile libraries.
7865                // Currently this will do a full compilation of the library by default.
7866                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7867                        false /* checkProfiles */,
7868                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7869                        getOrCreateCompilerPackageStats(depPackage));
7870            }
7871        }
7872        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7873                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7874    }
7875
7876    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7877        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7878            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7879            Set<String> collectedNames = new HashSet<>();
7880            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7881
7882            retValue.remove(p);
7883
7884            return retValue;
7885        } else {
7886            return Collections.emptyList();
7887        }
7888    }
7889
7890    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7891            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7892        if (!collectedNames.contains(p.packageName)) {
7893            collectedNames.add(p.packageName);
7894            collected.add(p);
7895
7896            if (p.usesLibraries != null) {
7897                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7898            }
7899            if (p.usesOptionalLibraries != null) {
7900                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7901                        collectedNames);
7902            }
7903        }
7904    }
7905
7906    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7907            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7908        for (String libName : libs) {
7909            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7910            if (libPkg != null) {
7911                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7912            }
7913        }
7914    }
7915
7916    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7917        synchronized (mPackages) {
7918            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7919            if (lib != null && lib.apk != null) {
7920                return mPackages.get(lib.apk);
7921            }
7922        }
7923        return null;
7924    }
7925
7926    public void shutdown() {
7927        mPackageUsage.writeNow(mPackages);
7928        mCompilerStats.writeNow();
7929    }
7930
7931    @Override
7932    public void dumpProfiles(String packageName) {
7933        PackageParser.Package pkg;
7934        synchronized (mPackages) {
7935            pkg = mPackages.get(packageName);
7936            if (pkg == null) {
7937                throw new IllegalArgumentException("Unknown package: " + packageName);
7938            }
7939        }
7940        /* Only the shell, root, or the app user should be able to dump profiles. */
7941        int callingUid = Binder.getCallingUid();
7942        if (callingUid != Process.SHELL_UID &&
7943            callingUid != Process.ROOT_UID &&
7944            callingUid != pkg.applicationInfo.uid) {
7945            throw new SecurityException("dumpProfiles");
7946        }
7947
7948        synchronized (mInstallLock) {
7949            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7950            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7951            try {
7952                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7953                String codePaths = TextUtils.join(";", allCodePaths);
7954                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7955            } catch (InstallerException e) {
7956                Slog.w(TAG, "Failed to dump profiles", e);
7957            }
7958            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7959        }
7960    }
7961
7962    @Override
7963    public void forceDexOpt(String packageName) {
7964        enforceSystemOrRoot("forceDexOpt");
7965
7966        PackageParser.Package pkg;
7967        synchronized (mPackages) {
7968            pkg = mPackages.get(packageName);
7969            if (pkg == null) {
7970                throw new IllegalArgumentException("Unknown package: " + packageName);
7971            }
7972        }
7973
7974        synchronized (mInstallLock) {
7975            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7976
7977            // Whoever is calling forceDexOpt wants a fully compiled package.
7978            // Don't use profiles since that may cause compilation to be skipped.
7979            final int res = performDexOptInternalWithDependenciesLI(pkg,
7980                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7981                    true /* force */);
7982
7983            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7984            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7985                throw new IllegalStateException("Failed to dexopt: " + res);
7986            }
7987        }
7988    }
7989
7990    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7991        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7992            Slog.w(TAG, "Unable to update from " + oldPkg.name
7993                    + " to " + newPkg.packageName
7994                    + ": old package not in system partition");
7995            return false;
7996        } else if (mPackages.get(oldPkg.name) != null) {
7997            Slog.w(TAG, "Unable to update from " + oldPkg.name
7998                    + " to " + newPkg.packageName
7999                    + ": old package still exists");
8000            return false;
8001        }
8002        return true;
8003    }
8004
8005    void removeCodePathLI(File codePath) {
8006        if (codePath.isDirectory()) {
8007            try {
8008                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8009            } catch (InstallerException e) {
8010                Slog.w(TAG, "Failed to remove code path", e);
8011            }
8012        } else {
8013            codePath.delete();
8014        }
8015    }
8016
8017    private int[] resolveUserIds(int userId) {
8018        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8019    }
8020
8021    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8022        if (pkg == null) {
8023            Slog.wtf(TAG, "Package was null!", new Throwable());
8024            return;
8025        }
8026        clearAppDataLeafLIF(pkg, userId, flags);
8027        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8028        for (int i = 0; i < childCount; i++) {
8029            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8030        }
8031    }
8032
8033    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8034        final PackageSetting ps;
8035        synchronized (mPackages) {
8036            ps = mSettings.mPackages.get(pkg.packageName);
8037        }
8038        for (int realUserId : resolveUserIds(userId)) {
8039            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8040            try {
8041                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8042                        ceDataInode);
8043            } catch (InstallerException e) {
8044                Slog.w(TAG, String.valueOf(e));
8045            }
8046        }
8047    }
8048
8049    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8050        if (pkg == null) {
8051            Slog.wtf(TAG, "Package was null!", new Throwable());
8052            return;
8053        }
8054        destroyAppDataLeafLIF(pkg, userId, flags);
8055        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8056        for (int i = 0; i < childCount; i++) {
8057            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8058        }
8059    }
8060
8061    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8062        final PackageSetting ps;
8063        synchronized (mPackages) {
8064            ps = mSettings.mPackages.get(pkg.packageName);
8065        }
8066        for (int realUserId : resolveUserIds(userId)) {
8067            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8068            try {
8069                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8070                        ceDataInode);
8071            } catch (InstallerException e) {
8072                Slog.w(TAG, String.valueOf(e));
8073            }
8074        }
8075    }
8076
8077    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8078        if (pkg == null) {
8079            Slog.wtf(TAG, "Package was null!", new Throwable());
8080            return;
8081        }
8082        destroyAppProfilesLeafLIF(pkg);
8083        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8084        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8085        for (int i = 0; i < childCount; i++) {
8086            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8087            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8088                    true /* removeBaseMarker */);
8089        }
8090    }
8091
8092    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8093            boolean removeBaseMarker) {
8094        if (pkg.isForwardLocked()) {
8095            return;
8096        }
8097
8098        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8099            try {
8100                path = PackageManagerServiceUtils.realpath(new File(path));
8101            } catch (IOException e) {
8102                // TODO: Should we return early here ?
8103                Slog.w(TAG, "Failed to get canonical path", e);
8104                continue;
8105            }
8106
8107            final String useMarker = path.replace('/', '@');
8108            for (int realUserId : resolveUserIds(userId)) {
8109                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8110                if (removeBaseMarker) {
8111                    File foreignUseMark = new File(profileDir, useMarker);
8112                    if (foreignUseMark.exists()) {
8113                        if (!foreignUseMark.delete()) {
8114                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8115                                    + pkg.packageName);
8116                        }
8117                    }
8118                }
8119
8120                File[] markers = profileDir.listFiles();
8121                if (markers != null) {
8122                    final String searchString = "@" + pkg.packageName + "@";
8123                    // We also delete all markers that contain the package name we're
8124                    // uninstalling. These are associated with secondary dex-files belonging
8125                    // to the package. Reconstructing the path of these dex files is messy
8126                    // in general.
8127                    for (File marker : markers) {
8128                        if (marker.getName().indexOf(searchString) > 0) {
8129                            if (!marker.delete()) {
8130                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8131                                    + pkg.packageName);
8132                            }
8133                        }
8134                    }
8135                }
8136            }
8137        }
8138    }
8139
8140    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8141        try {
8142            mInstaller.destroyAppProfiles(pkg.packageName);
8143        } catch (InstallerException e) {
8144            Slog.w(TAG, String.valueOf(e));
8145        }
8146    }
8147
8148    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8149        if (pkg == null) {
8150            Slog.wtf(TAG, "Package was null!", new Throwable());
8151            return;
8152        }
8153        clearAppProfilesLeafLIF(pkg);
8154        // We don't remove the base foreign use marker when clearing profiles because
8155        // we will rename it when the app is updated. Unlike the actual profile contents,
8156        // the foreign use marker is good across installs.
8157        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8158        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8159        for (int i = 0; i < childCount; i++) {
8160            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8161        }
8162    }
8163
8164    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8165        try {
8166            mInstaller.clearAppProfiles(pkg.packageName);
8167        } catch (InstallerException e) {
8168            Slog.w(TAG, String.valueOf(e));
8169        }
8170    }
8171
8172    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8173            long lastUpdateTime) {
8174        // Set parent install/update time
8175        PackageSetting ps = (PackageSetting) pkg.mExtras;
8176        if (ps != null) {
8177            ps.firstInstallTime = firstInstallTime;
8178            ps.lastUpdateTime = lastUpdateTime;
8179        }
8180        // Set children install/update time
8181        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8182        for (int i = 0; i < childCount; i++) {
8183            PackageParser.Package childPkg = pkg.childPackages.get(i);
8184            ps = (PackageSetting) childPkg.mExtras;
8185            if (ps != null) {
8186                ps.firstInstallTime = firstInstallTime;
8187                ps.lastUpdateTime = lastUpdateTime;
8188            }
8189        }
8190    }
8191
8192    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8193            PackageParser.Package changingLib) {
8194        if (file.path != null) {
8195            usesLibraryFiles.add(file.path);
8196            return;
8197        }
8198        PackageParser.Package p = mPackages.get(file.apk);
8199        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8200            // If we are doing this while in the middle of updating a library apk,
8201            // then we need to make sure to use that new apk for determining the
8202            // dependencies here.  (We haven't yet finished committing the new apk
8203            // to the package manager state.)
8204            if (p == null || p.packageName.equals(changingLib.packageName)) {
8205                p = changingLib;
8206            }
8207        }
8208        if (p != null) {
8209            usesLibraryFiles.addAll(p.getAllCodePaths());
8210        }
8211    }
8212
8213    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8214            PackageParser.Package changingLib) throws PackageManagerException {
8215        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8216            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8217            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8218            for (int i=0; i<N; i++) {
8219                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8220                if (file == null) {
8221                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8222                            "Package " + pkg.packageName + " requires unavailable shared library "
8223                            + pkg.usesLibraries.get(i) + "; failing!");
8224                }
8225                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8226            }
8227            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8228            for (int i=0; i<N; i++) {
8229                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8230                if (file == null) {
8231                    Slog.w(TAG, "Package " + pkg.packageName
8232                            + " desires unavailable shared library "
8233                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8234                } else {
8235                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8236                }
8237            }
8238            N = usesLibraryFiles.size();
8239            if (N > 0) {
8240                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8241            } else {
8242                pkg.usesLibraryFiles = null;
8243            }
8244        }
8245    }
8246
8247    private static boolean hasString(List<String> list, List<String> which) {
8248        if (list == null) {
8249            return false;
8250        }
8251        for (int i=list.size()-1; i>=0; i--) {
8252            for (int j=which.size()-1; j>=0; j--) {
8253                if (which.get(j).equals(list.get(i))) {
8254                    return true;
8255                }
8256            }
8257        }
8258        return false;
8259    }
8260
8261    private void updateAllSharedLibrariesLPw() {
8262        for (PackageParser.Package pkg : mPackages.values()) {
8263            try {
8264                updateSharedLibrariesLPr(pkg, null);
8265            } catch (PackageManagerException e) {
8266                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8267            }
8268        }
8269    }
8270
8271    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8272            PackageParser.Package changingPkg) {
8273        ArrayList<PackageParser.Package> res = null;
8274        for (PackageParser.Package pkg : mPackages.values()) {
8275            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8276                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8277                if (res == null) {
8278                    res = new ArrayList<PackageParser.Package>();
8279                }
8280                res.add(pkg);
8281                try {
8282                    updateSharedLibrariesLPr(pkg, changingPkg);
8283                } catch (PackageManagerException e) {
8284                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8285                }
8286            }
8287        }
8288        return res;
8289    }
8290
8291    /**
8292     * Derive the value of the {@code cpuAbiOverride} based on the provided
8293     * value and an optional stored value from the package settings.
8294     */
8295    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8296        String cpuAbiOverride = null;
8297
8298        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8299            cpuAbiOverride = null;
8300        } else if (abiOverride != null) {
8301            cpuAbiOverride = abiOverride;
8302        } else if (settings != null) {
8303            cpuAbiOverride = settings.cpuAbiOverrideString;
8304        }
8305
8306        return cpuAbiOverride;
8307    }
8308
8309    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8310            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8311                    throws PackageManagerException {
8312        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8313        // If the package has children and this is the first dive in the function
8314        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8315        // whether all packages (parent and children) would be successfully scanned
8316        // before the actual scan since scanning mutates internal state and we want
8317        // to atomically install the package and its children.
8318        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8319            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8320                scanFlags |= SCAN_CHECK_ONLY;
8321            }
8322        } else {
8323            scanFlags &= ~SCAN_CHECK_ONLY;
8324        }
8325
8326        final PackageParser.Package scannedPkg;
8327        try {
8328            // Scan the parent
8329            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8330            // Scan the children
8331            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8332            for (int i = 0; i < childCount; i++) {
8333                PackageParser.Package childPkg = pkg.childPackages.get(i);
8334                scanPackageLI(childPkg, policyFlags,
8335                        scanFlags, currentTime, user);
8336            }
8337        } finally {
8338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8339        }
8340
8341        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8342            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8343        }
8344
8345        return scannedPkg;
8346    }
8347
8348    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8349            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8350        boolean success = false;
8351        try {
8352            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8353                    currentTime, user);
8354            success = true;
8355            return res;
8356        } finally {
8357            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8358                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8359                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8360                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8361                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8362            }
8363        }
8364    }
8365
8366    /**
8367     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8368     */
8369    private static boolean apkHasCode(String fileName) {
8370        StrictJarFile jarFile = null;
8371        try {
8372            jarFile = new StrictJarFile(fileName,
8373                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8374            return jarFile.findEntry("classes.dex") != null;
8375        } catch (IOException ignore) {
8376        } finally {
8377            try {
8378                if (jarFile != null) {
8379                    jarFile.close();
8380                }
8381            } catch (IOException ignore) {}
8382        }
8383        return false;
8384    }
8385
8386    /**
8387     * Enforces code policy for the package. This ensures that if an APK has
8388     * declared hasCode="true" in its manifest that the APK actually contains
8389     * code.
8390     *
8391     * @throws PackageManagerException If bytecode could not be found when it should exist
8392     */
8393    private static void assertCodePolicy(PackageParser.Package pkg)
8394            throws PackageManagerException {
8395        final boolean shouldHaveCode =
8396                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8397        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8398            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8399                    "Package " + pkg.baseCodePath + " code is missing");
8400        }
8401
8402        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8403            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8404                final boolean splitShouldHaveCode =
8405                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8406                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8407                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8408                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8409                }
8410            }
8411        }
8412    }
8413
8414    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8415            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8416                    throws PackageManagerException {
8417        if (DEBUG_PACKAGE_SCANNING) {
8418            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8419                Log.d(TAG, "Scanning package " + pkg.packageName);
8420        }
8421
8422        applyPolicy(pkg, policyFlags);
8423
8424        assertPackageIsValid(pkg, policyFlags, scanFlags);
8425
8426        // Initialize package source and resource directories
8427        final File scanFile = new File(pkg.codePath);
8428        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8429        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8430
8431        SharedUserSetting suid = null;
8432        PackageSetting pkgSetting = null;
8433
8434        // Getting the package setting may have a side-effect, so if we
8435        // are only checking if scan would succeed, stash a copy of the
8436        // old setting to restore at the end.
8437        PackageSetting nonMutatedPs = null;
8438
8439        // We keep references to the derived CPU Abis from settings in oder to reuse
8440        // them in the case where we're not upgrading or booting for the first time.
8441        String primaryCpuAbiFromSettings = null;
8442        String secondaryCpuAbiFromSettings = null;
8443
8444        // writer
8445        synchronized (mPackages) {
8446            if (pkg.mSharedUserId != null) {
8447                // SIDE EFFECTS; may potentially allocate a new shared user
8448                suid = mSettings.getSharedUserLPw(
8449                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8450                if (DEBUG_PACKAGE_SCANNING) {
8451                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8452                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8453                                + "): packages=" + suid.packages);
8454                }
8455            }
8456
8457            // Check if we are renaming from an original package name.
8458            PackageSetting origPackage = null;
8459            String realName = null;
8460            if (pkg.mOriginalPackages != null) {
8461                // This package may need to be renamed to a previously
8462                // installed name.  Let's check on that...
8463                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8464                if (pkg.mOriginalPackages.contains(renamed)) {
8465                    // This package had originally been installed as the
8466                    // original name, and we have already taken care of
8467                    // transitioning to the new one.  Just update the new
8468                    // one to continue using the old name.
8469                    realName = pkg.mRealPackage;
8470                    if (!pkg.packageName.equals(renamed)) {
8471                        // Callers into this function may have already taken
8472                        // care of renaming the package; only do it here if
8473                        // it is not already done.
8474                        pkg.setPackageName(renamed);
8475                    }
8476                } else {
8477                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8478                        if ((origPackage = mSettings.getPackageLPr(
8479                                pkg.mOriginalPackages.get(i))) != null) {
8480                            // We do have the package already installed under its
8481                            // original name...  should we use it?
8482                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8483                                // New package is not compatible with original.
8484                                origPackage = null;
8485                                continue;
8486                            } else if (origPackage.sharedUser != null) {
8487                                // Make sure uid is compatible between packages.
8488                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8489                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8490                                            + " to " + pkg.packageName + ": old uid "
8491                                            + origPackage.sharedUser.name
8492                                            + " differs from " + pkg.mSharedUserId);
8493                                    origPackage = null;
8494                                    continue;
8495                                }
8496                                // TODO: Add case when shared user id is added [b/28144775]
8497                            } else {
8498                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8499                                        + pkg.packageName + " to old name " + origPackage.name);
8500                            }
8501                            break;
8502                        }
8503                    }
8504                }
8505            }
8506
8507            if (mTransferedPackages.contains(pkg.packageName)) {
8508                Slog.w(TAG, "Package " + pkg.packageName
8509                        + " was transferred to another, but its .apk remains");
8510            }
8511
8512            // See comments in nonMutatedPs declaration
8513            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8514                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8515                if (foundPs != null) {
8516                    nonMutatedPs = new PackageSetting(foundPs);
8517                }
8518            }
8519
8520            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8521                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8522                if (foundPs != null) {
8523                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8524                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8525                }
8526            }
8527
8528            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8529            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8530                PackageManagerService.reportSettingsProblem(Log.WARN,
8531                        "Package " + pkg.packageName + " shared user changed from "
8532                                + (pkgSetting.sharedUser != null
8533                                        ? pkgSetting.sharedUser.name : "<nothing>")
8534                                + " to "
8535                                + (suid != null ? suid.name : "<nothing>")
8536                                + "; replacing with new");
8537                pkgSetting = null;
8538            }
8539            final PackageSetting oldPkgSetting =
8540                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8541            final PackageSetting disabledPkgSetting =
8542                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8543            if (pkgSetting == null) {
8544                final String parentPackageName = (pkg.parentPackage != null)
8545                        ? pkg.parentPackage.packageName : null;
8546                // REMOVE SharedUserSetting from method; update in a separate call
8547                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8548                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8549                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8550                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8551                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8552                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8553                        UserManagerService.getInstance());
8554                // SIDE EFFECTS; updates system state; move elsewhere
8555                if (origPackage != null) {
8556                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8557                }
8558                mSettings.addUserToSettingLPw(pkgSetting);
8559            } else {
8560                // REMOVE SharedUserSetting from method; update in a separate call.
8561                //
8562                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8563                // secondaryCpuAbi are not known at this point so we always update them
8564                // to null here, only to reset them at a later point.
8565                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8566                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8567                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8568                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8569                        UserManagerService.getInstance());
8570            }
8571            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8572            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8573
8574            // SIDE EFFECTS; modifies system state; move elsewhere
8575            if (pkgSetting.origPackage != null) {
8576                // If we are first transitioning from an original package,
8577                // fix up the new package's name now.  We need to do this after
8578                // looking up the package under its new name, so getPackageLP
8579                // can take care of fiddling things correctly.
8580                pkg.setPackageName(origPackage.name);
8581
8582                // File a report about this.
8583                String msg = "New package " + pkgSetting.realName
8584                        + " renamed to replace old package " + pkgSetting.name;
8585                reportSettingsProblem(Log.WARN, msg);
8586
8587                // Make a note of it.
8588                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8589                    mTransferedPackages.add(origPackage.name);
8590                }
8591
8592                // No longer need to retain this.
8593                pkgSetting.origPackage = null;
8594            }
8595
8596            // SIDE EFFECTS; modifies system state; move elsewhere
8597            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8598                // Make a note of it.
8599                mTransferedPackages.add(pkg.packageName);
8600            }
8601
8602            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8603                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8604            }
8605
8606            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8607                // Check all shared libraries and map to their actual file path.
8608                // We only do this here for apps not on a system dir, because those
8609                // are the only ones that can fail an install due to this.  We
8610                // will take care of the system apps by updating all of their
8611                // library paths after the scan is done.
8612                updateSharedLibrariesLPr(pkg, null);
8613            }
8614
8615            if (mFoundPolicyFile) {
8616                SELinuxMMAC.assignSeinfoValue(pkg);
8617            }
8618
8619            pkg.applicationInfo.uid = pkgSetting.appId;
8620            pkg.mExtras = pkgSetting;
8621            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8622                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8623                    // We just determined the app is signed correctly, so bring
8624                    // over the latest parsed certs.
8625                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8626                } else {
8627                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8628                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8629                                "Package " + pkg.packageName + " upgrade keys do not match the "
8630                                + "previously installed version");
8631                    } else {
8632                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8633                        String msg = "System package " + pkg.packageName
8634                                + " signature changed; retaining data.";
8635                        reportSettingsProblem(Log.WARN, msg);
8636                    }
8637                }
8638            } else {
8639                try {
8640                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8641                    verifySignaturesLP(pkgSetting, pkg);
8642                    // We just determined the app is signed correctly, so bring
8643                    // over the latest parsed certs.
8644                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8645                } catch (PackageManagerException e) {
8646                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8647                        throw e;
8648                    }
8649                    // The signature has changed, but this package is in the system
8650                    // image...  let's recover!
8651                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8652                    // However...  if this package is part of a shared user, but it
8653                    // doesn't match the signature of the shared user, let's fail.
8654                    // What this means is that you can't change the signatures
8655                    // associated with an overall shared user, which doesn't seem all
8656                    // that unreasonable.
8657                    if (pkgSetting.sharedUser != null) {
8658                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8659                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8660                            throw new PackageManagerException(
8661                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8662                                    "Signature mismatch for shared user: "
8663                                            + pkgSetting.sharedUser);
8664                        }
8665                    }
8666                    // File a report about this.
8667                    String msg = "System package " + pkg.packageName
8668                            + " signature changed; retaining data.";
8669                    reportSettingsProblem(Log.WARN, msg);
8670                }
8671            }
8672
8673            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8674                // This package wants to adopt ownership of permissions from
8675                // another package.
8676                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8677                    final String origName = pkg.mAdoptPermissions.get(i);
8678                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8679                    if (orig != null) {
8680                        if (verifyPackageUpdateLPr(orig, pkg)) {
8681                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8682                                    + pkg.packageName);
8683                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8684                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8685                        }
8686                    }
8687                }
8688            }
8689        }
8690
8691        pkg.applicationInfo.processName = fixProcessName(
8692                pkg.applicationInfo.packageName,
8693                pkg.applicationInfo.processName);
8694
8695        if (pkg != mPlatformPackage) {
8696            // Get all of our default paths setup
8697            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8698        }
8699
8700        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8701
8702        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8703            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8704                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8705                derivePackageAbi(
8706                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8707                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8708
8709                // Some system apps still use directory structure for native libraries
8710                // in which case we might end up not detecting abi solely based on apk
8711                // structure. Try to detect abi based on directory structure.
8712                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8713                        pkg.applicationInfo.primaryCpuAbi == null) {
8714                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8715                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8716                }
8717            } else {
8718                // This is not a first boot or an upgrade, don't bother deriving the
8719                // ABI during the scan. Instead, trust the value that was stored in the
8720                // package setting.
8721                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8722                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8723
8724                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8725
8726                if (DEBUG_ABI_SELECTION) {
8727                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8728                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8729                        pkg.applicationInfo.secondaryCpuAbi);
8730                }
8731            }
8732        } else {
8733            if ((scanFlags & SCAN_MOVE) != 0) {
8734                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8735                // but we already have this packages package info in the PackageSetting. We just
8736                // use that and derive the native library path based on the new codepath.
8737                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8738                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8739            }
8740
8741            // Set native library paths again. For moves, the path will be updated based on the
8742            // ABIs we've determined above. For non-moves, the path will be updated based on the
8743            // ABIs we determined during compilation, but the path will depend on the final
8744            // package path (after the rename away from the stage path).
8745            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8746        }
8747
8748        // This is a special case for the "system" package, where the ABI is
8749        // dictated by the zygote configuration (and init.rc). We should keep track
8750        // of this ABI so that we can deal with "normal" applications that run under
8751        // the same UID correctly.
8752        if (mPlatformPackage == pkg) {
8753            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8754                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8755        }
8756
8757        // If there's a mismatch between the abi-override in the package setting
8758        // and the abiOverride specified for the install. Warn about this because we
8759        // would've already compiled the app without taking the package setting into
8760        // account.
8761        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8762            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8763                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8764                        " for package " + pkg.packageName);
8765            }
8766        }
8767
8768        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8769        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8770        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8771
8772        // Copy the derived override back to the parsed package, so that we can
8773        // update the package settings accordingly.
8774        pkg.cpuAbiOverride = cpuAbiOverride;
8775
8776        if (DEBUG_ABI_SELECTION) {
8777            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8778                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8779                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8780        }
8781
8782        // Push the derived path down into PackageSettings so we know what to
8783        // clean up at uninstall time.
8784        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8785
8786        if (DEBUG_ABI_SELECTION) {
8787            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8788                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8789                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8790        }
8791
8792        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8793        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8794            // We don't do this here during boot because we can do it all
8795            // at once after scanning all existing packages.
8796            //
8797            // We also do this *before* we perform dexopt on this package, so that
8798            // we can avoid redundant dexopts, and also to make sure we've got the
8799            // code and package path correct.
8800            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8801        }
8802
8803        if (mFactoryTest && pkg.requestedPermissions.contains(
8804                android.Manifest.permission.FACTORY_TEST)) {
8805            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8806        }
8807
8808        if (isSystemApp(pkg)) {
8809            pkgSetting.isOrphaned = true;
8810        }
8811
8812        // Take care of first install / last update times.
8813        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8814        if (currentTime != 0) {
8815            if (pkgSetting.firstInstallTime == 0) {
8816                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8817            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8818                pkgSetting.lastUpdateTime = currentTime;
8819            }
8820        } else if (pkgSetting.firstInstallTime == 0) {
8821            // We need *something*.  Take time time stamp of the file.
8822            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8823        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8824            if (scanFileTime != pkgSetting.timeStamp) {
8825                // A package on the system image has changed; consider this
8826                // to be an update.
8827                pkgSetting.lastUpdateTime = scanFileTime;
8828            }
8829        }
8830        pkgSetting.setTimeStamp(scanFileTime);
8831
8832        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8833            if (nonMutatedPs != null) {
8834                synchronized (mPackages) {
8835                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8836                }
8837            }
8838        } else {
8839            // Modify state for the given package setting
8840            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8841                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8842        }
8843        return pkg;
8844    }
8845
8846    /**
8847     * Applies policy to the parsed package based upon the given policy flags.
8848     * Ensures the package is in a good state.
8849     * <p>
8850     * Implementation detail: This method must NOT have any side effect. It would
8851     * ideally be static, but, it requires locks to read system state.
8852     */
8853    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8854        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8855            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8856            if (pkg.applicationInfo.isDirectBootAware()) {
8857                // we're direct boot aware; set for all components
8858                for (PackageParser.Service s : pkg.services) {
8859                    s.info.encryptionAware = s.info.directBootAware = true;
8860                }
8861                for (PackageParser.Provider p : pkg.providers) {
8862                    p.info.encryptionAware = p.info.directBootAware = true;
8863                }
8864                for (PackageParser.Activity a : pkg.activities) {
8865                    a.info.encryptionAware = a.info.directBootAware = true;
8866                }
8867                for (PackageParser.Activity r : pkg.receivers) {
8868                    r.info.encryptionAware = r.info.directBootAware = true;
8869                }
8870            }
8871        } else {
8872            // Only allow system apps to be flagged as core apps.
8873            pkg.coreApp = false;
8874            // clear flags not applicable to regular apps
8875            pkg.applicationInfo.privateFlags &=
8876                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8877            pkg.applicationInfo.privateFlags &=
8878                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8879        }
8880        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8881
8882        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8883            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8884        }
8885
8886        if (!isSystemApp(pkg)) {
8887            // Only system apps can use these features.
8888            pkg.mOriginalPackages = null;
8889            pkg.mRealPackage = null;
8890            pkg.mAdoptPermissions = null;
8891        }
8892    }
8893
8894    /**
8895     * Asserts the parsed package is valid according to teh given policy. If the
8896     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8897     * <p>
8898     * Implementation detail: This method must NOT have any side effects. It would
8899     * ideally be static, but, it requires locks to read system state.
8900     *
8901     * @throws PackageManagerException If the package fails any of the validation checks
8902     */
8903    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8904            throws PackageManagerException {
8905        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8906            assertCodePolicy(pkg);
8907        }
8908
8909        if (pkg.applicationInfo.getCodePath() == null ||
8910                pkg.applicationInfo.getResourcePath() == null) {
8911            // Bail out. The resource and code paths haven't been set.
8912            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8913                    "Code and resource paths haven't been set correctly");
8914        }
8915
8916        // Make sure we're not adding any bogus keyset info
8917        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8918        ksms.assertScannedPackageValid(pkg);
8919
8920        synchronized (mPackages) {
8921            // The special "android" package can only be defined once
8922            if (pkg.packageName.equals("android")) {
8923                if (mAndroidApplication != null) {
8924                    Slog.w(TAG, "*************************************************");
8925                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8926                    Slog.w(TAG, " codePath=" + pkg.codePath);
8927                    Slog.w(TAG, "*************************************************");
8928                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8929                            "Core android package being redefined.  Skipping.");
8930                }
8931            }
8932
8933            // A package name must be unique; don't allow duplicates
8934            if (mPackages.containsKey(pkg.packageName)
8935                    || mSharedLibraries.containsKey(pkg.packageName)) {
8936                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8937                        "Application package " + pkg.packageName
8938                        + " already installed.  Skipping duplicate.");
8939            }
8940
8941            // Only privileged apps and updated privileged apps can add child packages.
8942            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8943                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8944                    throw new PackageManagerException("Only privileged apps can add child "
8945                            + "packages. Ignoring package " + pkg.packageName);
8946                }
8947                final int childCount = pkg.childPackages.size();
8948                for (int i = 0; i < childCount; i++) {
8949                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8950                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8951                            childPkg.packageName)) {
8952                        throw new PackageManagerException("Can't override child of "
8953                                + "another disabled app. Ignoring package " + pkg.packageName);
8954                    }
8955                }
8956            }
8957
8958            // If we're only installing presumed-existing packages, require that the
8959            // scanned APK is both already known and at the path previously established
8960            // for it.  Previously unknown packages we pick up normally, but if we have an
8961            // a priori expectation about this package's install presence, enforce it.
8962            // With a singular exception for new system packages. When an OTA contains
8963            // a new system package, we allow the codepath to change from a system location
8964            // to the user-installed location. If we don't allow this change, any newer,
8965            // user-installed version of the application will be ignored.
8966            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8967                if (mExpectingBetter.containsKey(pkg.packageName)) {
8968                    logCriticalInfo(Log.WARN,
8969                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8970                } else {
8971                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8972                    if (known != null) {
8973                        if (DEBUG_PACKAGE_SCANNING) {
8974                            Log.d(TAG, "Examining " + pkg.codePath
8975                                    + " and requiring known paths " + known.codePathString
8976                                    + " & " + known.resourcePathString);
8977                        }
8978                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8979                                || !pkg.applicationInfo.getResourcePath().equals(
8980                                        known.resourcePathString)) {
8981                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8982                                    "Application package " + pkg.packageName
8983                                    + " found at " + pkg.applicationInfo.getCodePath()
8984                                    + " but expected at " + known.codePathString
8985                                    + "; ignoring.");
8986                        }
8987                    }
8988                }
8989            }
8990
8991            // Verify that this new package doesn't have any content providers
8992            // that conflict with existing packages.  Only do this if the
8993            // package isn't already installed, since we don't want to break
8994            // things that are installed.
8995            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8996                final int N = pkg.providers.size();
8997                int i;
8998                for (i=0; i<N; i++) {
8999                    PackageParser.Provider p = pkg.providers.get(i);
9000                    if (p.info.authority != null) {
9001                        String names[] = p.info.authority.split(";");
9002                        for (int j = 0; j < names.length; j++) {
9003                            if (mProvidersByAuthority.containsKey(names[j])) {
9004                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9005                                final String otherPackageName =
9006                                        ((other != null && other.getComponentName() != null) ?
9007                                                other.getComponentName().getPackageName() : "?");
9008                                throw new PackageManagerException(
9009                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9010                                        "Can't install because provider name " + names[j]
9011                                                + " (in package " + pkg.applicationInfo.packageName
9012                                                + ") is already used by " + otherPackageName);
9013                            }
9014                        }
9015                    }
9016                }
9017            }
9018        }
9019    }
9020
9021    /**
9022     * Adds a scanned package to the system. When this method is finished, the package will
9023     * be available for query, resolution, etc...
9024     */
9025    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9026            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9027        final String pkgName = pkg.packageName;
9028        if (mCustomResolverComponentName != null &&
9029                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9030            setUpCustomResolverActivity(pkg);
9031        }
9032
9033        if (pkg.packageName.equals("android")) {
9034            synchronized (mPackages) {
9035                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9036                    // Set up information for our fall-back user intent resolution activity.
9037                    mPlatformPackage = pkg;
9038                    pkg.mVersionCode = mSdkVersion;
9039                    mAndroidApplication = pkg.applicationInfo;
9040
9041                    if (!mResolverReplaced) {
9042                        mResolveActivity.applicationInfo = mAndroidApplication;
9043                        mResolveActivity.name = ResolverActivity.class.getName();
9044                        mResolveActivity.packageName = mAndroidApplication.packageName;
9045                        mResolveActivity.processName = "system:ui";
9046                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9047                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9048                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9049                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9050                        mResolveActivity.exported = true;
9051                        mResolveActivity.enabled = true;
9052                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9053                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9054                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9055                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9056                                | ActivityInfo.CONFIG_ORIENTATION
9057                                | ActivityInfo.CONFIG_KEYBOARD
9058                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9059                        mResolveInfo.activityInfo = mResolveActivity;
9060                        mResolveInfo.priority = 0;
9061                        mResolveInfo.preferredOrder = 0;
9062                        mResolveInfo.match = 0;
9063                        mResolveComponentName = new ComponentName(
9064                                mAndroidApplication.packageName, mResolveActivity.name);
9065                    }
9066                }
9067            }
9068        }
9069
9070        ArrayList<PackageParser.Package> clientLibPkgs = null;
9071        // writer
9072        synchronized (mPackages) {
9073            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9074                // Only system apps can add new shared libraries.
9075                if (pkg.libraryNames != null) {
9076                    for (int i=0; i<pkg.libraryNames.size(); i++) {
9077                        String name = pkg.libraryNames.get(i);
9078                        boolean allowed = false;
9079                        if (pkg.isUpdatedSystemApp()) {
9080                            // New library entries can only be added through the
9081                            // system image.  This is important to get rid of a lot
9082                            // of nasty edge cases: for example if we allowed a non-
9083                            // system update of the app to add a library, then uninstalling
9084                            // the update would make the library go away, and assumptions
9085                            // we made such as through app install filtering would now
9086                            // have allowed apps on the device which aren't compatible
9087                            // with it.  Better to just have the restriction here, be
9088                            // conservative, and create many fewer cases that can negatively
9089                            // impact the user experience.
9090                            final PackageSetting sysPs = mSettings
9091                                    .getDisabledSystemPkgLPr(pkg.packageName);
9092                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9093                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
9094                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9095                                        allowed = true;
9096                                        break;
9097                                    }
9098                                }
9099                            }
9100                        } else {
9101                            allowed = true;
9102                        }
9103                        if (allowed) {
9104                            if (!mSharedLibraries.containsKey(name)) {
9105                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
9106                            } else if (!name.equals(pkg.packageName)) {
9107                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9108                                        + name + " already exists; skipping");
9109                            }
9110                        } else {
9111                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9112                                    + name + " that is not declared on system image; skipping");
9113                        }
9114                    }
9115                    if ((scanFlags & SCAN_BOOTING) == 0) {
9116                        // If we are not booting, we need to update any applications
9117                        // that are clients of our shared library.  If we are booting,
9118                        // this will all be done once the scan is complete.
9119                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9120                    }
9121                }
9122            }
9123        }
9124
9125        if ((scanFlags & SCAN_BOOTING) != 0) {
9126            // No apps can run during boot scan, so they don't need to be frozen
9127        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9128            // Caller asked to not kill app, so it's probably not frozen
9129        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9130            // Caller asked us to ignore frozen check for some reason; they
9131            // probably didn't know the package name
9132        } else {
9133            // We're doing major surgery on this package, so it better be frozen
9134            // right now to keep it from launching
9135            checkPackageFrozen(pkgName);
9136        }
9137
9138        // Also need to kill any apps that are dependent on the library.
9139        if (clientLibPkgs != null) {
9140            for (int i=0; i<clientLibPkgs.size(); i++) {
9141                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9142                killApplication(clientPkg.applicationInfo.packageName,
9143                        clientPkg.applicationInfo.uid, "update lib");
9144            }
9145        }
9146
9147        // writer
9148        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9149
9150        boolean createIdmapFailed = false;
9151        synchronized (mPackages) {
9152            // We don't expect installation to fail beyond this point
9153
9154            if (pkgSetting.pkg != null) {
9155                // Note that |user| might be null during the initial boot scan. If a codePath
9156                // for an app has changed during a boot scan, it's due to an app update that's
9157                // part of the system partition and marker changes must be applied to all users.
9158                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9159                final int[] userIds = resolveUserIds(userId);
9160                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9161            }
9162
9163            // Add the new setting to mSettings
9164            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9165            // Add the new setting to mPackages
9166            mPackages.put(pkg.applicationInfo.packageName, pkg);
9167            // Make sure we don't accidentally delete its data.
9168            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9169            while (iter.hasNext()) {
9170                PackageCleanItem item = iter.next();
9171                if (pkgName.equals(item.packageName)) {
9172                    iter.remove();
9173                }
9174            }
9175
9176            // Add the package's KeySets to the global KeySetManagerService
9177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9178            ksms.addScannedPackageLPw(pkg);
9179
9180            int N = pkg.providers.size();
9181            StringBuilder r = null;
9182            int i;
9183            for (i=0; i<N; i++) {
9184                PackageParser.Provider p = pkg.providers.get(i);
9185                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9186                        p.info.processName);
9187                mProviders.addProvider(p);
9188                p.syncable = p.info.isSyncable;
9189                if (p.info.authority != null) {
9190                    String names[] = p.info.authority.split(";");
9191                    p.info.authority = null;
9192                    for (int j = 0; j < names.length; j++) {
9193                        if (j == 1 && p.syncable) {
9194                            // We only want the first authority for a provider to possibly be
9195                            // syncable, so if we already added this provider using a different
9196                            // authority clear the syncable flag. We copy the provider before
9197                            // changing it because the mProviders object contains a reference
9198                            // to a provider that we don't want to change.
9199                            // Only do this for the second authority since the resulting provider
9200                            // object can be the same for all future authorities for this provider.
9201                            p = new PackageParser.Provider(p);
9202                            p.syncable = false;
9203                        }
9204                        if (!mProvidersByAuthority.containsKey(names[j])) {
9205                            mProvidersByAuthority.put(names[j], p);
9206                            if (p.info.authority == null) {
9207                                p.info.authority = names[j];
9208                            } else {
9209                                p.info.authority = p.info.authority + ";" + names[j];
9210                            }
9211                            if (DEBUG_PACKAGE_SCANNING) {
9212                                if (chatty)
9213                                    Log.d(TAG, "Registered content provider: " + names[j]
9214                                            + ", className = " + p.info.name + ", isSyncable = "
9215                                            + p.info.isSyncable);
9216                            }
9217                        } else {
9218                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9219                            Slog.w(TAG, "Skipping provider name " + names[j] +
9220                                    " (in package " + pkg.applicationInfo.packageName +
9221                                    "): name already used by "
9222                                    + ((other != null && other.getComponentName() != null)
9223                                            ? other.getComponentName().getPackageName() : "?"));
9224                        }
9225                    }
9226                }
9227                if (chatty) {
9228                    if (r == null) {
9229                        r = new StringBuilder(256);
9230                    } else {
9231                        r.append(' ');
9232                    }
9233                    r.append(p.info.name);
9234                }
9235            }
9236            if (r != null) {
9237                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9238            }
9239
9240            N = pkg.services.size();
9241            r = null;
9242            for (i=0; i<N; i++) {
9243                PackageParser.Service s = pkg.services.get(i);
9244                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9245                        s.info.processName);
9246                mServices.addService(s);
9247                if (chatty) {
9248                    if (r == null) {
9249                        r = new StringBuilder(256);
9250                    } else {
9251                        r.append(' ');
9252                    }
9253                    r.append(s.info.name);
9254                }
9255            }
9256            if (r != null) {
9257                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9258            }
9259
9260            N = pkg.receivers.size();
9261            r = null;
9262            for (i=0; i<N; i++) {
9263                PackageParser.Activity a = pkg.receivers.get(i);
9264                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9265                        a.info.processName);
9266                mReceivers.addActivity(a, "receiver");
9267                if (chatty) {
9268                    if (r == null) {
9269                        r = new StringBuilder(256);
9270                    } else {
9271                        r.append(' ');
9272                    }
9273                    r.append(a.info.name);
9274                }
9275            }
9276            if (r != null) {
9277                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9278            }
9279
9280            N = pkg.activities.size();
9281            r = null;
9282            for (i=0; i<N; i++) {
9283                PackageParser.Activity a = pkg.activities.get(i);
9284                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9285                        a.info.processName);
9286                mActivities.addActivity(a, "activity");
9287                if (chatty) {
9288                    if (r == null) {
9289                        r = new StringBuilder(256);
9290                    } else {
9291                        r.append(' ');
9292                    }
9293                    r.append(a.info.name);
9294                }
9295            }
9296            if (r != null) {
9297                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9298            }
9299
9300            N = pkg.permissionGroups.size();
9301            r = null;
9302            for (i=0; i<N; i++) {
9303                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9304                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9305                final String curPackageName = cur == null ? null : cur.info.packageName;
9306                // Dont allow ephemeral apps to define new permission groups.
9307                if (pkg.applicationInfo.isEphemeralApp()) {
9308                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9309                            + pg.info.packageName
9310                            + " ignored: ephemeral apps cannot define new permission groups.");
9311                    continue;
9312                }
9313                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9314                if (cur == null || isPackageUpdate) {
9315                    mPermissionGroups.put(pg.info.name, pg);
9316                    if (chatty) {
9317                        if (r == null) {
9318                            r = new StringBuilder(256);
9319                        } else {
9320                            r.append(' ');
9321                        }
9322                        if (isPackageUpdate) {
9323                            r.append("UPD:");
9324                        }
9325                        r.append(pg.info.name);
9326                    }
9327                } else {
9328                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9329                            + pg.info.packageName + " ignored: original from "
9330                            + cur.info.packageName);
9331                    if (chatty) {
9332                        if (r == null) {
9333                            r = new StringBuilder(256);
9334                        } else {
9335                            r.append(' ');
9336                        }
9337                        r.append("DUP:");
9338                        r.append(pg.info.name);
9339                    }
9340                }
9341            }
9342            if (r != null) {
9343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9344            }
9345
9346            N = pkg.permissions.size();
9347            r = null;
9348            for (i=0; i<N; i++) {
9349                PackageParser.Permission p = pkg.permissions.get(i);
9350
9351                // Dont allow ephemeral apps to define new permissions.
9352                if (pkg.applicationInfo.isEphemeralApp()) {
9353                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9354                            + p.info.packageName
9355                            + " ignored: ephemeral apps cannot define new permissions.");
9356                    continue;
9357                }
9358
9359                // Assume by default that we did not install this permission into the system.
9360                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9361
9362                // Now that permission groups have a special meaning, we ignore permission
9363                // groups for legacy apps to prevent unexpected behavior. In particular,
9364                // permissions for one app being granted to someone just becase they happen
9365                // to be in a group defined by another app (before this had no implications).
9366                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9367                    p.group = mPermissionGroups.get(p.info.group);
9368                    // Warn for a permission in an unknown group.
9369                    if (p.info.group != null && p.group == null) {
9370                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9371                                + p.info.packageName + " in an unknown group " + p.info.group);
9372                    }
9373                }
9374
9375                ArrayMap<String, BasePermission> permissionMap =
9376                        p.tree ? mSettings.mPermissionTrees
9377                                : mSettings.mPermissions;
9378                BasePermission bp = permissionMap.get(p.info.name);
9379
9380                // Allow system apps to redefine non-system permissions
9381                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9382                    final boolean currentOwnerIsSystem = (bp.perm != null
9383                            && isSystemApp(bp.perm.owner));
9384                    if (isSystemApp(p.owner)) {
9385                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9386                            // It's a built-in permission and no owner, take ownership now
9387                            bp.packageSetting = pkgSetting;
9388                            bp.perm = p;
9389                            bp.uid = pkg.applicationInfo.uid;
9390                            bp.sourcePackage = p.info.packageName;
9391                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9392                        } else if (!currentOwnerIsSystem) {
9393                            String msg = "New decl " + p.owner + " of permission  "
9394                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9395                            reportSettingsProblem(Log.WARN, msg);
9396                            bp = null;
9397                        }
9398                    }
9399                }
9400
9401                if (bp == null) {
9402                    bp = new BasePermission(p.info.name, p.info.packageName,
9403                            BasePermission.TYPE_NORMAL);
9404                    permissionMap.put(p.info.name, bp);
9405                }
9406
9407                if (bp.perm == null) {
9408                    if (bp.sourcePackage == null
9409                            || bp.sourcePackage.equals(p.info.packageName)) {
9410                        BasePermission tree = findPermissionTreeLP(p.info.name);
9411                        if (tree == null
9412                                || tree.sourcePackage.equals(p.info.packageName)) {
9413                            bp.packageSetting = pkgSetting;
9414                            bp.perm = p;
9415                            bp.uid = pkg.applicationInfo.uid;
9416                            bp.sourcePackage = p.info.packageName;
9417                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9418                            if (chatty) {
9419                                if (r == null) {
9420                                    r = new StringBuilder(256);
9421                                } else {
9422                                    r.append(' ');
9423                                }
9424                                r.append(p.info.name);
9425                            }
9426                        } else {
9427                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9428                                    + p.info.packageName + " ignored: base tree "
9429                                    + tree.name + " is from package "
9430                                    + tree.sourcePackage);
9431                        }
9432                    } else {
9433                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9434                                + p.info.packageName + " ignored: original from "
9435                                + bp.sourcePackage);
9436                    }
9437                } else if (chatty) {
9438                    if (r == null) {
9439                        r = new StringBuilder(256);
9440                    } else {
9441                        r.append(' ');
9442                    }
9443                    r.append("DUP:");
9444                    r.append(p.info.name);
9445                }
9446                if (bp.perm == p) {
9447                    bp.protectionLevel = p.info.protectionLevel;
9448                }
9449            }
9450
9451            if (r != null) {
9452                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9453            }
9454
9455            N = pkg.instrumentation.size();
9456            r = null;
9457            for (i=0; i<N; i++) {
9458                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9459                a.info.packageName = pkg.applicationInfo.packageName;
9460                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9461                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9462                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9463                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9464                a.info.dataDir = pkg.applicationInfo.dataDir;
9465                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9466                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9467                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9468                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9469                mInstrumentation.put(a.getComponentName(), a);
9470                if (chatty) {
9471                    if (r == null) {
9472                        r = new StringBuilder(256);
9473                    } else {
9474                        r.append(' ');
9475                    }
9476                    r.append(a.info.name);
9477                }
9478            }
9479            if (r != null) {
9480                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9481            }
9482
9483            if (pkg.protectedBroadcasts != null) {
9484                N = pkg.protectedBroadcasts.size();
9485                for (i=0; i<N; i++) {
9486                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9487                }
9488            }
9489
9490            // Create idmap files for pairs of (packages, overlay packages).
9491            // Note: "android", ie framework-res.apk, is handled by native layers.
9492            if (pkg.mOverlayTarget != null) {
9493                // This is an overlay package.
9494                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9495                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9496                        mOverlays.put(pkg.mOverlayTarget,
9497                                new ArrayMap<String, PackageParser.Package>());
9498                    }
9499                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9500                    map.put(pkg.packageName, pkg);
9501                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9502                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9503                        createIdmapFailed = true;
9504                    }
9505                }
9506            } else if (mOverlays.containsKey(pkg.packageName) &&
9507                    !pkg.packageName.equals("android")) {
9508                // This is a regular package, with one or more known overlay packages.
9509                createIdmapsForPackageLI(pkg);
9510            }
9511        }
9512
9513        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9514
9515        if (createIdmapFailed) {
9516            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9517                    "scanPackageLI failed to createIdmap");
9518        }
9519    }
9520
9521    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9522            PackageParser.Package update, int[] userIds) {
9523        if (existing.applicationInfo == null || update.applicationInfo == null) {
9524            // This isn't due to an app installation.
9525            return;
9526        }
9527
9528        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9529        final File newCodePath = new File(update.applicationInfo.getCodePath());
9530
9531        // The codePath hasn't changed, so there's nothing for us to do.
9532        if (Objects.equals(oldCodePath, newCodePath)) {
9533            return;
9534        }
9535
9536        File canonicalNewCodePath;
9537        try {
9538            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9539        } catch (IOException e) {
9540            Slog.w(TAG, "Failed to get canonical path.", e);
9541            return;
9542        }
9543
9544        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9545        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9546        // that the last component of the path (i.e, the name) doesn't need canonicalization
9547        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9548        // but may change in the future. Hopefully this function won't exist at that point.
9549        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9550                oldCodePath.getName());
9551
9552        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9553        // with "@".
9554        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9555        if (!oldMarkerPrefix.endsWith("@")) {
9556            oldMarkerPrefix += "@";
9557        }
9558        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9559        if (!newMarkerPrefix.endsWith("@")) {
9560            newMarkerPrefix += "@";
9561        }
9562
9563        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9564        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9565        for (String updatedPath : updatedPaths) {
9566            String updatedPathName = new File(updatedPath).getName();
9567            markerSuffixes.add(updatedPathName.replace('/', '@'));
9568        }
9569
9570        for (int userId : userIds) {
9571            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9572
9573            for (String markerSuffix : markerSuffixes) {
9574                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9575                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9576                if (oldForeignUseMark.exists()) {
9577                    try {
9578                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9579                                newForeignUseMark.getAbsolutePath());
9580                    } catch (ErrnoException e) {
9581                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9582                        oldForeignUseMark.delete();
9583                    }
9584                }
9585            }
9586        }
9587    }
9588
9589    /**
9590     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9591     * is derived purely on the basis of the contents of {@code scanFile} and
9592     * {@code cpuAbiOverride}.
9593     *
9594     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9595     */
9596    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9597                                 String cpuAbiOverride, boolean extractLibs,
9598                                 File appLib32InstallDir)
9599            throws PackageManagerException {
9600        // Give ourselves some initial paths; we'll come back for another
9601        // pass once we've determined ABI below.
9602        setNativeLibraryPaths(pkg, appLib32InstallDir);
9603
9604        // We would never need to extract libs for forward-locked and external packages,
9605        // since the container service will do it for us. We shouldn't attempt to
9606        // extract libs from system app when it was not updated.
9607        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9608                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9609            extractLibs = false;
9610        }
9611
9612        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9613        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9614
9615        NativeLibraryHelper.Handle handle = null;
9616        try {
9617            handle = NativeLibraryHelper.Handle.create(pkg);
9618            // TODO(multiArch): This can be null for apps that didn't go through the
9619            // usual installation process. We can calculate it again, like we
9620            // do during install time.
9621            //
9622            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9623            // unnecessary.
9624            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9625
9626            // Null out the abis so that they can be recalculated.
9627            pkg.applicationInfo.primaryCpuAbi = null;
9628            pkg.applicationInfo.secondaryCpuAbi = null;
9629            if (isMultiArch(pkg.applicationInfo)) {
9630                // Warn if we've set an abiOverride for multi-lib packages..
9631                // By definition, we need to copy both 32 and 64 bit libraries for
9632                // such packages.
9633                if (pkg.cpuAbiOverride != null
9634                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9635                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9636                }
9637
9638                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9639                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9640                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9641                    if (extractLibs) {
9642                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9643                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9644                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9645                                useIsaSpecificSubdirs);
9646                    } else {
9647                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9648                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9649                    }
9650                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9651                }
9652
9653                maybeThrowExceptionForMultiArchCopy(
9654                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9655
9656                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9657                    if (extractLibs) {
9658                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9659                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9660                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9661                                useIsaSpecificSubdirs);
9662                    } else {
9663                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9664                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9665                    }
9666                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9667                }
9668
9669                maybeThrowExceptionForMultiArchCopy(
9670                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9671
9672                if (abi64 >= 0) {
9673                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9674                }
9675
9676                if (abi32 >= 0) {
9677                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9678                    if (abi64 >= 0) {
9679                        if (pkg.use32bitAbi) {
9680                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9681                            pkg.applicationInfo.primaryCpuAbi = abi;
9682                        } else {
9683                            pkg.applicationInfo.secondaryCpuAbi = abi;
9684                        }
9685                    } else {
9686                        pkg.applicationInfo.primaryCpuAbi = abi;
9687                    }
9688                }
9689
9690            } else {
9691                String[] abiList = (cpuAbiOverride != null) ?
9692                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9693
9694                // Enable gross and lame hacks for apps that are built with old
9695                // SDK tools. We must scan their APKs for renderscript bitcode and
9696                // not launch them if it's present. Don't bother checking on devices
9697                // that don't have 64 bit support.
9698                boolean needsRenderScriptOverride = false;
9699                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9700                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9701                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9702                    needsRenderScriptOverride = true;
9703                }
9704
9705                final int copyRet;
9706                if (extractLibs) {
9707                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9708                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9709                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9710                } else {
9711                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9712                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9713                }
9714                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9715
9716                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9717                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9718                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9719                }
9720
9721                if (copyRet >= 0) {
9722                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9723                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9724                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9725                } else if (needsRenderScriptOverride) {
9726                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9727                }
9728            }
9729        } catch (IOException ioe) {
9730            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9731        } finally {
9732            IoUtils.closeQuietly(handle);
9733        }
9734
9735        // Now that we've calculated the ABIs and determined if it's an internal app,
9736        // we will go ahead and populate the nativeLibraryPath.
9737        setNativeLibraryPaths(pkg, appLib32InstallDir);
9738    }
9739
9740    /**
9741     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9742     * i.e, so that all packages can be run inside a single process if required.
9743     *
9744     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9745     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9746     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9747     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9748     * updating a package that belongs to a shared user.
9749     *
9750     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9751     * adds unnecessary complexity.
9752     */
9753    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9754            PackageParser.Package scannedPackage) {
9755        String requiredInstructionSet = null;
9756        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9757            requiredInstructionSet = VMRuntime.getInstructionSet(
9758                     scannedPackage.applicationInfo.primaryCpuAbi);
9759        }
9760
9761        PackageSetting requirer = null;
9762        for (PackageSetting ps : packagesForUser) {
9763            // If packagesForUser contains scannedPackage, we skip it. This will happen
9764            // when scannedPackage is an update of an existing package. Without this check,
9765            // we will never be able to change the ABI of any package belonging to a shared
9766            // user, even if it's compatible with other packages.
9767            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9768                if (ps.primaryCpuAbiString == null) {
9769                    continue;
9770                }
9771
9772                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9773                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9774                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9775                    // this but there's not much we can do.
9776                    String errorMessage = "Instruction set mismatch, "
9777                            + ((requirer == null) ? "[caller]" : requirer)
9778                            + " requires " + requiredInstructionSet + " whereas " + ps
9779                            + " requires " + instructionSet;
9780                    Slog.w(TAG, errorMessage);
9781                }
9782
9783                if (requiredInstructionSet == null) {
9784                    requiredInstructionSet = instructionSet;
9785                    requirer = ps;
9786                }
9787            }
9788        }
9789
9790        if (requiredInstructionSet != null) {
9791            String adjustedAbi;
9792            if (requirer != null) {
9793                // requirer != null implies that either scannedPackage was null or that scannedPackage
9794                // did not require an ABI, in which case we have to adjust scannedPackage to match
9795                // the ABI of the set (which is the same as requirer's ABI)
9796                adjustedAbi = requirer.primaryCpuAbiString;
9797                if (scannedPackage != null) {
9798                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9799                }
9800            } else {
9801                // requirer == null implies that we're updating all ABIs in the set to
9802                // match scannedPackage.
9803                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9804            }
9805
9806            for (PackageSetting ps : packagesForUser) {
9807                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9808                    if (ps.primaryCpuAbiString != null) {
9809                        continue;
9810                    }
9811
9812                    ps.primaryCpuAbiString = adjustedAbi;
9813                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9814                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9815                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9816                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9817                                + " (requirer="
9818                                + (requirer == null ? "null" : requirer.pkg.packageName)
9819                                + ", scannedPackage="
9820                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9821                                + ")");
9822                        try {
9823                            mInstaller.rmdex(ps.codePathString,
9824                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9825                        } catch (InstallerException ignored) {
9826                        }
9827                    }
9828                }
9829            }
9830        }
9831    }
9832
9833    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9834        synchronized (mPackages) {
9835            mResolverReplaced = true;
9836            // Set up information for custom user intent resolution activity.
9837            mResolveActivity.applicationInfo = pkg.applicationInfo;
9838            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9839            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9840            mResolveActivity.processName = pkg.applicationInfo.packageName;
9841            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9842            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9843                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9844            mResolveActivity.theme = 0;
9845            mResolveActivity.exported = true;
9846            mResolveActivity.enabled = true;
9847            mResolveInfo.activityInfo = mResolveActivity;
9848            mResolveInfo.priority = 0;
9849            mResolveInfo.preferredOrder = 0;
9850            mResolveInfo.match = 0;
9851            mResolveComponentName = mCustomResolverComponentName;
9852            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9853                    mResolveComponentName);
9854        }
9855    }
9856
9857    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9858        if (installerComponent == null) {
9859            if (DEBUG_EPHEMERAL) {
9860                Slog.d(TAG, "Clear ephemeral installer activity");
9861            }
9862            mEphemeralInstallerActivity.applicationInfo = null;
9863            return;
9864        }
9865
9866        if (DEBUG_EPHEMERAL) {
9867            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9868        }
9869        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9870        // Set up information for ephemeral installer activity
9871        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9872        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9873        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9874        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9875        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9876        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9877                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9878        mEphemeralInstallerActivity.theme = 0;
9879        mEphemeralInstallerActivity.exported = true;
9880        mEphemeralInstallerActivity.enabled = true;
9881        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9882        mEphemeralInstallerInfo.priority = 0;
9883        mEphemeralInstallerInfo.preferredOrder = 1;
9884        mEphemeralInstallerInfo.isDefault = true;
9885        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9886                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9887    }
9888
9889    private static String calculateBundledApkRoot(final String codePathString) {
9890        final File codePath = new File(codePathString);
9891        final File codeRoot;
9892        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9893            codeRoot = Environment.getRootDirectory();
9894        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9895            codeRoot = Environment.getOemDirectory();
9896        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9897            codeRoot = Environment.getVendorDirectory();
9898        } else {
9899            // Unrecognized code path; take its top real segment as the apk root:
9900            // e.g. /something/app/blah.apk => /something
9901            try {
9902                File f = codePath.getCanonicalFile();
9903                File parent = f.getParentFile();    // non-null because codePath is a file
9904                File tmp;
9905                while ((tmp = parent.getParentFile()) != null) {
9906                    f = parent;
9907                    parent = tmp;
9908                }
9909                codeRoot = f;
9910                Slog.w(TAG, "Unrecognized code path "
9911                        + codePath + " - using " + codeRoot);
9912            } catch (IOException e) {
9913                // Can't canonicalize the code path -- shenanigans?
9914                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9915                return Environment.getRootDirectory().getPath();
9916            }
9917        }
9918        return codeRoot.getPath();
9919    }
9920
9921    /**
9922     * Derive and set the location of native libraries for the given package,
9923     * which varies depending on where and how the package was installed.
9924     */
9925    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9926        final ApplicationInfo info = pkg.applicationInfo;
9927        final String codePath = pkg.codePath;
9928        final File codeFile = new File(codePath);
9929        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9930        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9931
9932        info.nativeLibraryRootDir = null;
9933        info.nativeLibraryRootRequiresIsa = false;
9934        info.nativeLibraryDir = null;
9935        info.secondaryNativeLibraryDir = null;
9936
9937        if (isApkFile(codeFile)) {
9938            // Monolithic install
9939            if (bundledApp) {
9940                // If "/system/lib64/apkname" exists, assume that is the per-package
9941                // native library directory to use; otherwise use "/system/lib/apkname".
9942                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9943                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9944                        getPrimaryInstructionSet(info));
9945
9946                // This is a bundled system app so choose the path based on the ABI.
9947                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9948                // is just the default path.
9949                final String apkName = deriveCodePathName(codePath);
9950                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9951                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9952                        apkName).getAbsolutePath();
9953
9954                if (info.secondaryCpuAbi != null) {
9955                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9956                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9957                            secondaryLibDir, apkName).getAbsolutePath();
9958                }
9959            } else if (asecApp) {
9960                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9961                        .getAbsolutePath();
9962            } else {
9963                final String apkName = deriveCodePathName(codePath);
9964                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9965                        .getAbsolutePath();
9966            }
9967
9968            info.nativeLibraryRootRequiresIsa = false;
9969            info.nativeLibraryDir = info.nativeLibraryRootDir;
9970        } else {
9971            // Cluster install
9972            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9973            info.nativeLibraryRootRequiresIsa = true;
9974
9975            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9976                    getPrimaryInstructionSet(info)).getAbsolutePath();
9977
9978            if (info.secondaryCpuAbi != null) {
9979                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9980                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9981            }
9982        }
9983    }
9984
9985    /**
9986     * Calculate the abis and roots for a bundled app. These can uniquely
9987     * be determined from the contents of the system partition, i.e whether
9988     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9989     * of this information, and instead assume that the system was built
9990     * sensibly.
9991     */
9992    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9993                                           PackageSetting pkgSetting) {
9994        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9995
9996        // If "/system/lib64/apkname" exists, assume that is the per-package
9997        // native library directory to use; otherwise use "/system/lib/apkname".
9998        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9999        setBundledAppAbi(pkg, apkRoot, apkName);
10000        // pkgSetting might be null during rescan following uninstall of updates
10001        // to a bundled app, so accommodate that possibility.  The settings in
10002        // that case will be established later from the parsed package.
10003        //
10004        // If the settings aren't null, sync them up with what we've just derived.
10005        // note that apkRoot isn't stored in the package settings.
10006        if (pkgSetting != null) {
10007            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10008            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10009        }
10010    }
10011
10012    /**
10013     * Deduces the ABI of a bundled app and sets the relevant fields on the
10014     * parsed pkg object.
10015     *
10016     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10017     *        under which system libraries are installed.
10018     * @param apkName the name of the installed package.
10019     */
10020    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10021        final File codeFile = new File(pkg.codePath);
10022
10023        final boolean has64BitLibs;
10024        final boolean has32BitLibs;
10025        if (isApkFile(codeFile)) {
10026            // Monolithic install
10027            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10028            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10029        } else {
10030            // Cluster install
10031            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10032            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10033                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10034                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10035                has64BitLibs = (new File(rootDir, isa)).exists();
10036            } else {
10037                has64BitLibs = false;
10038            }
10039            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10040                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10041                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10042                has32BitLibs = (new File(rootDir, isa)).exists();
10043            } else {
10044                has32BitLibs = false;
10045            }
10046        }
10047
10048        if (has64BitLibs && !has32BitLibs) {
10049            // The package has 64 bit libs, but not 32 bit libs. Its primary
10050            // ABI should be 64 bit. We can safely assume here that the bundled
10051            // native libraries correspond to the most preferred ABI in the list.
10052
10053            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10054            pkg.applicationInfo.secondaryCpuAbi = null;
10055        } else if (has32BitLibs && !has64BitLibs) {
10056            // The package has 32 bit libs but not 64 bit libs. Its primary
10057            // ABI should be 32 bit.
10058
10059            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10060            pkg.applicationInfo.secondaryCpuAbi = null;
10061        } else if (has32BitLibs && has64BitLibs) {
10062            // The application has both 64 and 32 bit bundled libraries. We check
10063            // here that the app declares multiArch support, and warn if it doesn't.
10064            //
10065            // We will be lenient here and record both ABIs. The primary will be the
10066            // ABI that's higher on the list, i.e, a device that's configured to prefer
10067            // 64 bit apps will see a 64 bit primary ABI,
10068
10069            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10070                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10071            }
10072
10073            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10074                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10075                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10076            } else {
10077                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10078                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10079            }
10080        } else {
10081            pkg.applicationInfo.primaryCpuAbi = null;
10082            pkg.applicationInfo.secondaryCpuAbi = null;
10083        }
10084    }
10085
10086    private void killApplication(String pkgName, int appId, String reason) {
10087        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10088    }
10089
10090    private void killApplication(String pkgName, int appId, int userId, String reason) {
10091        // Request the ActivityManager to kill the process(only for existing packages)
10092        // so that we do not end up in a confused state while the user is still using the older
10093        // version of the application while the new one gets installed.
10094        final long token = Binder.clearCallingIdentity();
10095        try {
10096            IActivityManager am = ActivityManager.getService();
10097            if (am != null) {
10098                try {
10099                    am.killApplication(pkgName, appId, userId, reason);
10100                } catch (RemoteException e) {
10101                }
10102            }
10103        } finally {
10104            Binder.restoreCallingIdentity(token);
10105        }
10106    }
10107
10108    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10109        // Remove the parent package setting
10110        PackageSetting ps = (PackageSetting) pkg.mExtras;
10111        if (ps != null) {
10112            removePackageLI(ps, chatty);
10113        }
10114        // Remove the child package setting
10115        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10116        for (int i = 0; i < childCount; i++) {
10117            PackageParser.Package childPkg = pkg.childPackages.get(i);
10118            ps = (PackageSetting) childPkg.mExtras;
10119            if (ps != null) {
10120                removePackageLI(ps, chatty);
10121            }
10122        }
10123    }
10124
10125    void removePackageLI(PackageSetting ps, boolean chatty) {
10126        if (DEBUG_INSTALL) {
10127            if (chatty)
10128                Log.d(TAG, "Removing package " + ps.name);
10129        }
10130
10131        // writer
10132        synchronized (mPackages) {
10133            mPackages.remove(ps.name);
10134            final PackageParser.Package pkg = ps.pkg;
10135            if (pkg != null) {
10136                cleanPackageDataStructuresLILPw(pkg, chatty);
10137            }
10138        }
10139    }
10140
10141    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10142        if (DEBUG_INSTALL) {
10143            if (chatty)
10144                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10145        }
10146
10147        // writer
10148        synchronized (mPackages) {
10149            // Remove the parent package
10150            mPackages.remove(pkg.applicationInfo.packageName);
10151            cleanPackageDataStructuresLILPw(pkg, chatty);
10152
10153            // Remove the child packages
10154            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10155            for (int i = 0; i < childCount; i++) {
10156                PackageParser.Package childPkg = pkg.childPackages.get(i);
10157                mPackages.remove(childPkg.applicationInfo.packageName);
10158                cleanPackageDataStructuresLILPw(childPkg, chatty);
10159            }
10160        }
10161    }
10162
10163    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10164        int N = pkg.providers.size();
10165        StringBuilder r = null;
10166        int i;
10167        for (i=0; i<N; i++) {
10168            PackageParser.Provider p = pkg.providers.get(i);
10169            mProviders.removeProvider(p);
10170            if (p.info.authority == null) {
10171
10172                /* There was another ContentProvider with this authority when
10173                 * this app was installed so this authority is null,
10174                 * Ignore it as we don't have to unregister the provider.
10175                 */
10176                continue;
10177            }
10178            String names[] = p.info.authority.split(";");
10179            for (int j = 0; j < names.length; j++) {
10180                if (mProvidersByAuthority.get(names[j]) == p) {
10181                    mProvidersByAuthority.remove(names[j]);
10182                    if (DEBUG_REMOVE) {
10183                        if (chatty)
10184                            Log.d(TAG, "Unregistered content provider: " + names[j]
10185                                    + ", className = " + p.info.name + ", isSyncable = "
10186                                    + p.info.isSyncable);
10187                    }
10188                }
10189            }
10190            if (DEBUG_REMOVE && chatty) {
10191                if (r == null) {
10192                    r = new StringBuilder(256);
10193                } else {
10194                    r.append(' ');
10195                }
10196                r.append(p.info.name);
10197            }
10198        }
10199        if (r != null) {
10200            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10201        }
10202
10203        N = pkg.services.size();
10204        r = null;
10205        for (i=0; i<N; i++) {
10206            PackageParser.Service s = pkg.services.get(i);
10207            mServices.removeService(s);
10208            if (chatty) {
10209                if (r == null) {
10210                    r = new StringBuilder(256);
10211                } else {
10212                    r.append(' ');
10213                }
10214                r.append(s.info.name);
10215            }
10216        }
10217        if (r != null) {
10218            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10219        }
10220
10221        N = pkg.receivers.size();
10222        r = null;
10223        for (i=0; i<N; i++) {
10224            PackageParser.Activity a = pkg.receivers.get(i);
10225            mReceivers.removeActivity(a, "receiver");
10226            if (DEBUG_REMOVE && chatty) {
10227                if (r == null) {
10228                    r = new StringBuilder(256);
10229                } else {
10230                    r.append(' ');
10231                }
10232                r.append(a.info.name);
10233            }
10234        }
10235        if (r != null) {
10236            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10237        }
10238
10239        N = pkg.activities.size();
10240        r = null;
10241        for (i=0; i<N; i++) {
10242            PackageParser.Activity a = pkg.activities.get(i);
10243            mActivities.removeActivity(a, "activity");
10244            if (DEBUG_REMOVE && chatty) {
10245                if (r == null) {
10246                    r = new StringBuilder(256);
10247                } else {
10248                    r.append(' ');
10249                }
10250                r.append(a.info.name);
10251            }
10252        }
10253        if (r != null) {
10254            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10255        }
10256
10257        N = pkg.permissions.size();
10258        r = null;
10259        for (i=0; i<N; i++) {
10260            PackageParser.Permission p = pkg.permissions.get(i);
10261            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10262            if (bp == null) {
10263                bp = mSettings.mPermissionTrees.get(p.info.name);
10264            }
10265            if (bp != null && bp.perm == p) {
10266                bp.perm = null;
10267                if (DEBUG_REMOVE && chatty) {
10268                    if (r == null) {
10269                        r = new StringBuilder(256);
10270                    } else {
10271                        r.append(' ');
10272                    }
10273                    r.append(p.info.name);
10274                }
10275            }
10276            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10277                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10278                if (appOpPkgs != null) {
10279                    appOpPkgs.remove(pkg.packageName);
10280                }
10281            }
10282        }
10283        if (r != null) {
10284            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10285        }
10286
10287        N = pkg.requestedPermissions.size();
10288        r = null;
10289        for (i=0; i<N; i++) {
10290            String perm = pkg.requestedPermissions.get(i);
10291            BasePermission bp = mSettings.mPermissions.get(perm);
10292            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10293                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10294                if (appOpPkgs != null) {
10295                    appOpPkgs.remove(pkg.packageName);
10296                    if (appOpPkgs.isEmpty()) {
10297                        mAppOpPermissionPackages.remove(perm);
10298                    }
10299                }
10300            }
10301        }
10302        if (r != null) {
10303            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10304        }
10305
10306        N = pkg.instrumentation.size();
10307        r = null;
10308        for (i=0; i<N; i++) {
10309            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10310            mInstrumentation.remove(a.getComponentName());
10311            if (DEBUG_REMOVE && chatty) {
10312                if (r == null) {
10313                    r = new StringBuilder(256);
10314                } else {
10315                    r.append(' ');
10316                }
10317                r.append(a.info.name);
10318            }
10319        }
10320        if (r != null) {
10321            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10322        }
10323
10324        r = null;
10325        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10326            // Only system apps can hold shared libraries.
10327            if (pkg.libraryNames != null) {
10328                for (i=0; i<pkg.libraryNames.size(); i++) {
10329                    String name = pkg.libraryNames.get(i);
10330                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10331                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10332                        mSharedLibraries.remove(name);
10333                        if (DEBUG_REMOVE && chatty) {
10334                            if (r == null) {
10335                                r = new StringBuilder(256);
10336                            } else {
10337                                r.append(' ');
10338                            }
10339                            r.append(name);
10340                        }
10341                    }
10342                }
10343            }
10344        }
10345        if (r != null) {
10346            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10347        }
10348    }
10349
10350    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10351        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10352            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10353                return true;
10354            }
10355        }
10356        return false;
10357    }
10358
10359    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10360    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10361    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10362
10363    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10364        // Update the parent permissions
10365        updatePermissionsLPw(pkg.packageName, pkg, flags);
10366        // Update the child permissions
10367        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10368        for (int i = 0; i < childCount; i++) {
10369            PackageParser.Package childPkg = pkg.childPackages.get(i);
10370            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10371        }
10372    }
10373
10374    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10375            int flags) {
10376        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10377        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10378    }
10379
10380    private void updatePermissionsLPw(String changingPkg,
10381            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10382        // Make sure there are no dangling permission trees.
10383        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10384        while (it.hasNext()) {
10385            final BasePermission bp = it.next();
10386            if (bp.packageSetting == null) {
10387                // We may not yet have parsed the package, so just see if
10388                // we still know about its settings.
10389                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10390            }
10391            if (bp.packageSetting == null) {
10392                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10393                        + " from package " + bp.sourcePackage);
10394                it.remove();
10395            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10396                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10397                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10398                            + " from package " + bp.sourcePackage);
10399                    flags |= UPDATE_PERMISSIONS_ALL;
10400                    it.remove();
10401                }
10402            }
10403        }
10404
10405        // Make sure all dynamic permissions have been assigned to a package,
10406        // and make sure there are no dangling permissions.
10407        it = mSettings.mPermissions.values().iterator();
10408        while (it.hasNext()) {
10409            final BasePermission bp = it.next();
10410            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10411                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10412                        + bp.name + " pkg=" + bp.sourcePackage
10413                        + " info=" + bp.pendingInfo);
10414                if (bp.packageSetting == null && bp.pendingInfo != null) {
10415                    final BasePermission tree = findPermissionTreeLP(bp.name);
10416                    if (tree != null && tree.perm != null) {
10417                        bp.packageSetting = tree.packageSetting;
10418                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10419                                new PermissionInfo(bp.pendingInfo));
10420                        bp.perm.info.packageName = tree.perm.info.packageName;
10421                        bp.perm.info.name = bp.name;
10422                        bp.uid = tree.uid;
10423                    }
10424                }
10425            }
10426            if (bp.packageSetting == null) {
10427                // We may not yet have parsed the package, so just see if
10428                // we still know about its settings.
10429                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10430            }
10431            if (bp.packageSetting == null) {
10432                Slog.w(TAG, "Removing dangling permission: " + bp.name
10433                        + " from package " + bp.sourcePackage);
10434                it.remove();
10435            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10436                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10437                    Slog.i(TAG, "Removing old permission: " + bp.name
10438                            + " from package " + bp.sourcePackage);
10439                    flags |= UPDATE_PERMISSIONS_ALL;
10440                    it.remove();
10441                }
10442            }
10443        }
10444
10445        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10446        // Now update the permissions for all packages, in particular
10447        // replace the granted permissions of the system packages.
10448        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10449            for (PackageParser.Package pkg : mPackages.values()) {
10450                if (pkg != pkgInfo) {
10451                    // Only replace for packages on requested volume
10452                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10453                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10454                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10455                    grantPermissionsLPw(pkg, replace, changingPkg);
10456                }
10457            }
10458        }
10459
10460        if (pkgInfo != null) {
10461            // Only replace for packages on requested volume
10462            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10463            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10464                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10465            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10466        }
10467        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10468    }
10469
10470    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10471            String packageOfInterest) {
10472        // IMPORTANT: There are two types of permissions: install and runtime.
10473        // Install time permissions are granted when the app is installed to
10474        // all device users and users added in the future. Runtime permissions
10475        // are granted at runtime explicitly to specific users. Normal and signature
10476        // protected permissions are install time permissions. Dangerous permissions
10477        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10478        // otherwise they are runtime permissions. This function does not manage
10479        // runtime permissions except for the case an app targeting Lollipop MR1
10480        // being upgraded to target a newer SDK, in which case dangerous permissions
10481        // are transformed from install time to runtime ones.
10482
10483        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10484        if (ps == null) {
10485            return;
10486        }
10487
10488        PermissionsState permissionsState = ps.getPermissionsState();
10489        PermissionsState origPermissions = permissionsState;
10490
10491        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10492
10493        boolean runtimePermissionsRevoked = false;
10494        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10495
10496        boolean changedInstallPermission = false;
10497
10498        if (replace) {
10499            ps.installPermissionsFixed = false;
10500            if (!ps.isSharedUser()) {
10501                origPermissions = new PermissionsState(permissionsState);
10502                permissionsState.reset();
10503            } else {
10504                // We need to know only about runtime permission changes since the
10505                // calling code always writes the install permissions state but
10506                // the runtime ones are written only if changed. The only cases of
10507                // changed runtime permissions here are promotion of an install to
10508                // runtime and revocation of a runtime from a shared user.
10509                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10510                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10511                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10512                    runtimePermissionsRevoked = true;
10513                }
10514            }
10515        }
10516
10517        permissionsState.setGlobalGids(mGlobalGids);
10518
10519        final int N = pkg.requestedPermissions.size();
10520        for (int i=0; i<N; i++) {
10521            final String name = pkg.requestedPermissions.get(i);
10522            final BasePermission bp = mSettings.mPermissions.get(name);
10523
10524            if (DEBUG_INSTALL) {
10525                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10526            }
10527
10528            if (bp == null || bp.packageSetting == null) {
10529                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10530                    Slog.w(TAG, "Unknown permission " + name
10531                            + " in package " + pkg.packageName);
10532                }
10533                continue;
10534            }
10535
10536
10537            // Limit ephemeral apps to ephemeral allowed permissions.
10538            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10539                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10540                        + pkg.packageName);
10541                continue;
10542            }
10543
10544            final String perm = bp.name;
10545            boolean allowedSig = false;
10546            int grant = GRANT_DENIED;
10547
10548            // Keep track of app op permissions.
10549            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10550                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10551                if (pkgs == null) {
10552                    pkgs = new ArraySet<>();
10553                    mAppOpPermissionPackages.put(bp.name, pkgs);
10554                }
10555                pkgs.add(pkg.packageName);
10556            }
10557
10558            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10559            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10560                    >= Build.VERSION_CODES.M;
10561            switch (level) {
10562                case PermissionInfo.PROTECTION_NORMAL: {
10563                    // For all apps normal permissions are install time ones.
10564                    grant = GRANT_INSTALL;
10565                } break;
10566
10567                case PermissionInfo.PROTECTION_DANGEROUS: {
10568                    // If a permission review is required for legacy apps we represent
10569                    // their permissions as always granted runtime ones since we need
10570                    // to keep the review required permission flag per user while an
10571                    // install permission's state is shared across all users.
10572                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10573                        // For legacy apps dangerous permissions are install time ones.
10574                        grant = GRANT_INSTALL;
10575                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10576                        // For legacy apps that became modern, install becomes runtime.
10577                        grant = GRANT_UPGRADE;
10578                    } else if (mPromoteSystemApps
10579                            && isSystemApp(ps)
10580                            && mExistingSystemPackages.contains(ps.name)) {
10581                        // For legacy system apps, install becomes runtime.
10582                        // We cannot check hasInstallPermission() for system apps since those
10583                        // permissions were granted implicitly and not persisted pre-M.
10584                        grant = GRANT_UPGRADE;
10585                    } else {
10586                        // For modern apps keep runtime permissions unchanged.
10587                        grant = GRANT_RUNTIME;
10588                    }
10589                } break;
10590
10591                case PermissionInfo.PROTECTION_SIGNATURE: {
10592                    // For all apps signature permissions are install time ones.
10593                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10594                    if (allowedSig) {
10595                        grant = GRANT_INSTALL;
10596                    }
10597                } break;
10598            }
10599
10600            if (DEBUG_INSTALL) {
10601                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10602            }
10603
10604            if (grant != GRANT_DENIED) {
10605                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10606                    // If this is an existing, non-system package, then
10607                    // we can't add any new permissions to it.
10608                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10609                        // Except...  if this is a permission that was added
10610                        // to the platform (note: need to only do this when
10611                        // updating the platform).
10612                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10613                            grant = GRANT_DENIED;
10614                        }
10615                    }
10616                }
10617
10618                switch (grant) {
10619                    case GRANT_INSTALL: {
10620                        // Revoke this as runtime permission to handle the case of
10621                        // a runtime permission being downgraded to an install one.
10622                        // Also in permission review mode we keep dangerous permissions
10623                        // for legacy apps
10624                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10625                            if (origPermissions.getRuntimePermissionState(
10626                                    bp.name, userId) != null) {
10627                                // Revoke the runtime permission and clear the flags.
10628                                origPermissions.revokeRuntimePermission(bp, userId);
10629                                origPermissions.updatePermissionFlags(bp, userId,
10630                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10631                                // If we revoked a permission permission, we have to write.
10632                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10633                                        changedRuntimePermissionUserIds, userId);
10634                            }
10635                        }
10636                        // Grant an install permission.
10637                        if (permissionsState.grantInstallPermission(bp) !=
10638                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10639                            changedInstallPermission = true;
10640                        }
10641                    } break;
10642
10643                    case GRANT_RUNTIME: {
10644                        // Grant previously granted runtime permissions.
10645                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10646                            PermissionState permissionState = origPermissions
10647                                    .getRuntimePermissionState(bp.name, userId);
10648                            int flags = permissionState != null
10649                                    ? permissionState.getFlags() : 0;
10650                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10651                                // Don't propagate the permission in a permission review mode if
10652                                // the former was revoked, i.e. marked to not propagate on upgrade.
10653                                // Note that in a permission review mode install permissions are
10654                                // represented as constantly granted runtime ones since we need to
10655                                // keep a per user state associated with the permission. Also the
10656                                // revoke on upgrade flag is no longer applicable and is reset.
10657                                final boolean revokeOnUpgrade = (flags & PackageManager
10658                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10659                                if (revokeOnUpgrade) {
10660                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10661                                    // Since we changed the flags, we have to write.
10662                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10663                                            changedRuntimePermissionUserIds, userId);
10664                                }
10665                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10666                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
10667                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
10668                                        // If we cannot put the permission as it was,
10669                                        // we have to write.
10670                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10671                                                changedRuntimePermissionUserIds, userId);
10672                                    }
10673                                }
10674
10675                                // If the app supports runtime permissions no need for a review.
10676                                if (mPermissionReviewRequired
10677                                        && appSupportsRuntimePermissions
10678                                        && (flags & PackageManager
10679                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10680                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10681                                    // Since we changed the flags, we have to write.
10682                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10683                                            changedRuntimePermissionUserIds, userId);
10684                                }
10685                            } else if (mPermissionReviewRequired
10686                                    && !appSupportsRuntimePermissions) {
10687                                // For legacy apps that need a permission review, every new
10688                                // runtime permission is granted but it is pending a review.
10689                                // We also need to review only platform defined runtime
10690                                // permissions as these are the only ones the platform knows
10691                                // how to disable the API to simulate revocation as legacy
10692                                // apps don't expect to run with revoked permissions.
10693                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10694                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10695                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10696                                        // We changed the flags, hence have to write.
10697                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10698                                                changedRuntimePermissionUserIds, userId);
10699                                    }
10700                                }
10701                                if (permissionsState.grantRuntimePermission(bp, userId)
10702                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10703                                    // We changed the permission, hence have to write.
10704                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10705                                            changedRuntimePermissionUserIds, userId);
10706                                }
10707                            }
10708                            // Propagate the permission flags.
10709                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10710                        }
10711                    } break;
10712
10713                    case GRANT_UPGRADE: {
10714                        // Grant runtime permissions for a previously held install permission.
10715                        PermissionState permissionState = origPermissions
10716                                .getInstallPermissionState(bp.name);
10717                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10718
10719                        if (origPermissions.revokeInstallPermission(bp)
10720                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10721                            // We will be transferring the permission flags, so clear them.
10722                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10723                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10724                            changedInstallPermission = true;
10725                        }
10726
10727                        // If the permission is not to be promoted to runtime we ignore it and
10728                        // also its other flags as they are not applicable to install permissions.
10729                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10730                            for (int userId : currentUserIds) {
10731                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10732                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10733                                    // Transfer the permission flags.
10734                                    permissionsState.updatePermissionFlags(bp, userId,
10735                                            flags, flags);
10736                                    // If we granted the permission, we have to write.
10737                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10738                                            changedRuntimePermissionUserIds, userId);
10739                                }
10740                            }
10741                        }
10742                    } break;
10743
10744                    default: {
10745                        if (packageOfInterest == null
10746                                || packageOfInterest.equals(pkg.packageName)) {
10747                            Slog.w(TAG, "Not granting permission " + perm
10748                                    + " to package " + pkg.packageName
10749                                    + " because it was previously installed without");
10750                        }
10751                    } break;
10752                }
10753            } else {
10754                if (permissionsState.revokeInstallPermission(bp) !=
10755                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10756                    // Also drop the permission flags.
10757                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10758                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10759                    changedInstallPermission = true;
10760                    Slog.i(TAG, "Un-granting permission " + perm
10761                            + " from package " + pkg.packageName
10762                            + " (protectionLevel=" + bp.protectionLevel
10763                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10764                            + ")");
10765                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10766                    // Don't print warning for app op permissions, since it is fine for them
10767                    // not to be granted, there is a UI for the user to decide.
10768                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10769                        Slog.w(TAG, "Not granting permission " + perm
10770                                + " to package " + pkg.packageName
10771                                + " (protectionLevel=" + bp.protectionLevel
10772                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10773                                + ")");
10774                    }
10775                }
10776            }
10777        }
10778
10779        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10780                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10781            // This is the first that we have heard about this package, so the
10782            // permissions we have now selected are fixed until explicitly
10783            // changed.
10784            ps.installPermissionsFixed = true;
10785        }
10786
10787        // Persist the runtime permissions state for users with changes. If permissions
10788        // were revoked because no app in the shared user declares them we have to
10789        // write synchronously to avoid losing runtime permissions state.
10790        for (int userId : changedRuntimePermissionUserIds) {
10791            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10792        }
10793    }
10794
10795    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10796        boolean allowed = false;
10797        final int NP = PackageParser.NEW_PERMISSIONS.length;
10798        for (int ip=0; ip<NP; ip++) {
10799            final PackageParser.NewPermissionInfo npi
10800                    = PackageParser.NEW_PERMISSIONS[ip];
10801            if (npi.name.equals(perm)
10802                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10803                allowed = true;
10804                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10805                        + pkg.packageName);
10806                break;
10807            }
10808        }
10809        return allowed;
10810    }
10811
10812    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10813            BasePermission bp, PermissionsState origPermissions) {
10814        boolean privilegedPermission = (bp.protectionLevel
10815                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10816        boolean privappPermissionsDisable =
10817                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10818        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10819        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10820        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10821                && !platformPackage && platformPermission) {
10822            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10823                    .getPrivAppPermissions(pkg.packageName);
10824            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10825            if (!whitelisted) {
10826                Slog.w(TAG, "Privileged permission " + perm + " for package "
10827                        + pkg.packageName + " - not in privapp-permissions whitelist");
10828                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10829                    return false;
10830                }
10831            }
10832        }
10833        boolean allowed = (compareSignatures(
10834                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10835                        == PackageManager.SIGNATURE_MATCH)
10836                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10837                        == PackageManager.SIGNATURE_MATCH);
10838        if (!allowed && privilegedPermission) {
10839            if (isSystemApp(pkg)) {
10840                // For updated system applications, a system permission
10841                // is granted only if it had been defined by the original application.
10842                if (pkg.isUpdatedSystemApp()) {
10843                    final PackageSetting sysPs = mSettings
10844                            .getDisabledSystemPkgLPr(pkg.packageName);
10845                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10846                        // If the original was granted this permission, we take
10847                        // that grant decision as read and propagate it to the
10848                        // update.
10849                        if (sysPs.isPrivileged()) {
10850                            allowed = true;
10851                        }
10852                    } else {
10853                        // The system apk may have been updated with an older
10854                        // version of the one on the data partition, but which
10855                        // granted a new system permission that it didn't have
10856                        // before.  In this case we do want to allow the app to
10857                        // now get the new permission if the ancestral apk is
10858                        // privileged to get it.
10859                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10860                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10861                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10862                                    allowed = true;
10863                                    break;
10864                                }
10865                            }
10866                        }
10867                        // Also if a privileged parent package on the system image or any of
10868                        // its children requested a privileged permission, the updated child
10869                        // packages can also get the permission.
10870                        if (pkg.parentPackage != null) {
10871                            final PackageSetting disabledSysParentPs = mSettings
10872                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10873                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10874                                    && disabledSysParentPs.isPrivileged()) {
10875                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10876                                    allowed = true;
10877                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10878                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10879                                    for (int i = 0; i < count; i++) {
10880                                        PackageParser.Package disabledSysChildPkg =
10881                                                disabledSysParentPs.pkg.childPackages.get(i);
10882                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10883                                                perm)) {
10884                                            allowed = true;
10885                                            break;
10886                                        }
10887                                    }
10888                                }
10889                            }
10890                        }
10891                    }
10892                } else {
10893                    allowed = isPrivilegedApp(pkg);
10894                }
10895            }
10896        }
10897        if (!allowed) {
10898            if (!allowed && (bp.protectionLevel
10899                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10900                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10901                // If this was a previously normal/dangerous permission that got moved
10902                // to a system permission as part of the runtime permission redesign, then
10903                // we still want to blindly grant it to old apps.
10904                allowed = true;
10905            }
10906            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10907                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10908                // If this permission is to be granted to the system installer and
10909                // this app is an installer, then it gets the permission.
10910                allowed = true;
10911            }
10912            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10913                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10914                // If this permission is to be granted to the system verifier and
10915                // this app is a verifier, then it gets the permission.
10916                allowed = true;
10917            }
10918            if (!allowed && (bp.protectionLevel
10919                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10920                    && isSystemApp(pkg)) {
10921                // Any pre-installed system app is allowed to get this permission.
10922                allowed = true;
10923            }
10924            if (!allowed && (bp.protectionLevel
10925                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10926                // For development permissions, a development permission
10927                // is granted only if it was already granted.
10928                allowed = origPermissions.hasInstallPermission(perm);
10929            }
10930            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10931                    && pkg.packageName.equals(mSetupWizardPackage)) {
10932                // If this permission is to be granted to the system setup wizard and
10933                // this app is a setup wizard, then it gets the permission.
10934                allowed = true;
10935            }
10936        }
10937        return allowed;
10938    }
10939
10940    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10941        final int permCount = pkg.requestedPermissions.size();
10942        for (int j = 0; j < permCount; j++) {
10943            String requestedPermission = pkg.requestedPermissions.get(j);
10944            if (permission.equals(requestedPermission)) {
10945                return true;
10946            }
10947        }
10948        return false;
10949    }
10950
10951    final class ActivityIntentResolver
10952            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10954                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10955            if (!sUserManager.exists(userId)) return null;
10956            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10957                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10958                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10959            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10960                    isEphemeral, userId);
10961        }
10962
10963        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10964                int userId) {
10965            if (!sUserManager.exists(userId)) return null;
10966            mFlags = flags;
10967            return super.queryIntent(intent, resolvedType,
10968                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10969                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10970                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10971        }
10972
10973        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10974                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10975            if (!sUserManager.exists(userId)) return null;
10976            if (packageActivities == null) {
10977                return null;
10978            }
10979            mFlags = flags;
10980            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10981            final boolean vislbleToEphemeral =
10982                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10983            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10984            final int N = packageActivities.size();
10985            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10986                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10987
10988            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10989            for (int i = 0; i < N; ++i) {
10990                intentFilters = packageActivities.get(i).intents;
10991                if (intentFilters != null && intentFilters.size() > 0) {
10992                    PackageParser.ActivityIntentInfo[] array =
10993                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10994                    intentFilters.toArray(array);
10995                    listCut.add(array);
10996                }
10997            }
10998            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10999                    vislbleToEphemeral, isEphemeral, listCut, userId);
11000        }
11001
11002        /**
11003         * Finds a privileged activity that matches the specified activity names.
11004         */
11005        private PackageParser.Activity findMatchingActivity(
11006                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11007            for (PackageParser.Activity sysActivity : activityList) {
11008                if (sysActivity.info.name.equals(activityInfo.name)) {
11009                    return sysActivity;
11010                }
11011                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11012                    return sysActivity;
11013                }
11014                if (sysActivity.info.targetActivity != null) {
11015                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11016                        return sysActivity;
11017                    }
11018                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11019                        return sysActivity;
11020                    }
11021                }
11022            }
11023            return null;
11024        }
11025
11026        public class IterGenerator<E> {
11027            public Iterator<E> generate(ActivityIntentInfo info) {
11028                return null;
11029            }
11030        }
11031
11032        public class ActionIterGenerator extends IterGenerator<String> {
11033            @Override
11034            public Iterator<String> generate(ActivityIntentInfo info) {
11035                return info.actionsIterator();
11036            }
11037        }
11038
11039        public class CategoriesIterGenerator extends IterGenerator<String> {
11040            @Override
11041            public Iterator<String> generate(ActivityIntentInfo info) {
11042                return info.categoriesIterator();
11043            }
11044        }
11045
11046        public class SchemesIterGenerator extends IterGenerator<String> {
11047            @Override
11048            public Iterator<String> generate(ActivityIntentInfo info) {
11049                return info.schemesIterator();
11050            }
11051        }
11052
11053        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11054            @Override
11055            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11056                return info.authoritiesIterator();
11057            }
11058        }
11059
11060        /**
11061         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11062         * MODIFIED. Do not pass in a list that should not be changed.
11063         */
11064        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11065                IterGenerator<T> generator, Iterator<T> searchIterator) {
11066            // loop through the set of actions; every one must be found in the intent filter
11067            while (searchIterator.hasNext()) {
11068                // we must have at least one filter in the list to consider a match
11069                if (intentList.size() == 0) {
11070                    break;
11071                }
11072
11073                final T searchAction = searchIterator.next();
11074
11075                // loop through the set of intent filters
11076                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11077                while (intentIter.hasNext()) {
11078                    final ActivityIntentInfo intentInfo = intentIter.next();
11079                    boolean selectionFound = false;
11080
11081                    // loop through the intent filter's selection criteria; at least one
11082                    // of them must match the searched criteria
11083                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11084                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11085                        final T intentSelection = intentSelectionIter.next();
11086                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11087                            selectionFound = true;
11088                            break;
11089                        }
11090                    }
11091
11092                    // the selection criteria wasn't found in this filter's set; this filter
11093                    // is not a potential match
11094                    if (!selectionFound) {
11095                        intentIter.remove();
11096                    }
11097                }
11098            }
11099        }
11100
11101        private boolean isProtectedAction(ActivityIntentInfo filter) {
11102            final Iterator<String> actionsIter = filter.actionsIterator();
11103            while (actionsIter != null && actionsIter.hasNext()) {
11104                final String filterAction = actionsIter.next();
11105                if (PROTECTED_ACTIONS.contains(filterAction)) {
11106                    return true;
11107                }
11108            }
11109            return false;
11110        }
11111
11112        /**
11113         * Adjusts the priority of the given intent filter according to policy.
11114         * <p>
11115         * <ul>
11116         * <li>The priority for non privileged applications is capped to '0'</li>
11117         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11118         * <li>The priority for unbundled updates to privileged applications is capped to the
11119         *      priority defined on the system partition</li>
11120         * </ul>
11121         * <p>
11122         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11123         * allowed to obtain any priority on any action.
11124         */
11125        private void adjustPriority(
11126                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11127            // nothing to do; priority is fine as-is
11128            if (intent.getPriority() <= 0) {
11129                return;
11130            }
11131
11132            final ActivityInfo activityInfo = intent.activity.info;
11133            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11134
11135            final boolean privilegedApp =
11136                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11137            if (!privilegedApp) {
11138                // non-privileged applications can never define a priority >0
11139                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11140                        + " package: " + applicationInfo.packageName
11141                        + " activity: " + intent.activity.className
11142                        + " origPrio: " + intent.getPriority());
11143                intent.setPriority(0);
11144                return;
11145            }
11146
11147            if (systemActivities == null) {
11148                // the system package is not disabled; we're parsing the system partition
11149                if (isProtectedAction(intent)) {
11150                    if (mDeferProtectedFilters) {
11151                        // We can't deal with these just yet. No component should ever obtain a
11152                        // >0 priority for a protected actions, with ONE exception -- the setup
11153                        // wizard. The setup wizard, however, cannot be known until we're able to
11154                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11155                        // until all intent filters have been processed. Chicken, meet egg.
11156                        // Let the filter temporarily have a high priority and rectify the
11157                        // priorities after all system packages have been scanned.
11158                        mProtectedFilters.add(intent);
11159                        if (DEBUG_FILTERS) {
11160                            Slog.i(TAG, "Protected action; save for later;"
11161                                    + " package: " + applicationInfo.packageName
11162                                    + " activity: " + intent.activity.className
11163                                    + " origPrio: " + intent.getPriority());
11164                        }
11165                        return;
11166                    } else {
11167                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11168                            Slog.i(TAG, "No setup wizard;"
11169                                + " All protected intents capped to priority 0");
11170                        }
11171                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11172                            if (DEBUG_FILTERS) {
11173                                Slog.i(TAG, "Found setup wizard;"
11174                                    + " allow priority " + intent.getPriority() + ";"
11175                                    + " package: " + intent.activity.info.packageName
11176                                    + " activity: " + intent.activity.className
11177                                    + " priority: " + intent.getPriority());
11178                            }
11179                            // setup wizard gets whatever it wants
11180                            return;
11181                        }
11182                        Slog.w(TAG, "Protected action; cap priority to 0;"
11183                                + " package: " + intent.activity.info.packageName
11184                                + " activity: " + intent.activity.className
11185                                + " origPrio: " + intent.getPriority());
11186                        intent.setPriority(0);
11187                        return;
11188                    }
11189                }
11190                // privileged apps on the system image get whatever priority they request
11191                return;
11192            }
11193
11194            // privileged app unbundled update ... try to find the same activity
11195            final PackageParser.Activity foundActivity =
11196                    findMatchingActivity(systemActivities, activityInfo);
11197            if (foundActivity == null) {
11198                // this is a new activity; it cannot obtain >0 priority
11199                if (DEBUG_FILTERS) {
11200                    Slog.i(TAG, "New activity; cap priority to 0;"
11201                            + " package: " + applicationInfo.packageName
11202                            + " activity: " + intent.activity.className
11203                            + " origPrio: " + intent.getPriority());
11204                }
11205                intent.setPriority(0);
11206                return;
11207            }
11208
11209            // found activity, now check for filter equivalence
11210
11211            // a shallow copy is enough; we modify the list, not its contents
11212            final List<ActivityIntentInfo> intentListCopy =
11213                    new ArrayList<>(foundActivity.intents);
11214            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11215
11216            // find matching action subsets
11217            final Iterator<String> actionsIterator = intent.actionsIterator();
11218            if (actionsIterator != null) {
11219                getIntentListSubset(
11220                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11221                if (intentListCopy.size() == 0) {
11222                    // no more intents to match; we're not equivalent
11223                    if (DEBUG_FILTERS) {
11224                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11225                                + " package: " + applicationInfo.packageName
11226                                + " activity: " + intent.activity.className
11227                                + " origPrio: " + intent.getPriority());
11228                    }
11229                    intent.setPriority(0);
11230                    return;
11231                }
11232            }
11233
11234            // find matching category subsets
11235            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11236            if (categoriesIterator != null) {
11237                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11238                        categoriesIterator);
11239                if (intentListCopy.size() == 0) {
11240                    // no more intents to match; we're not equivalent
11241                    if (DEBUG_FILTERS) {
11242                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11243                                + " package: " + applicationInfo.packageName
11244                                + " activity: " + intent.activity.className
11245                                + " origPrio: " + intent.getPriority());
11246                    }
11247                    intent.setPriority(0);
11248                    return;
11249                }
11250            }
11251
11252            // find matching schemes subsets
11253            final Iterator<String> schemesIterator = intent.schemesIterator();
11254            if (schemesIterator != null) {
11255                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11256                        schemesIterator);
11257                if (intentListCopy.size() == 0) {
11258                    // no more intents to match; we're not equivalent
11259                    if (DEBUG_FILTERS) {
11260                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11261                                + " package: " + applicationInfo.packageName
11262                                + " activity: " + intent.activity.className
11263                                + " origPrio: " + intent.getPriority());
11264                    }
11265                    intent.setPriority(0);
11266                    return;
11267                }
11268            }
11269
11270            // find matching authorities subsets
11271            final Iterator<IntentFilter.AuthorityEntry>
11272                    authoritiesIterator = intent.authoritiesIterator();
11273            if (authoritiesIterator != null) {
11274                getIntentListSubset(intentListCopy,
11275                        new AuthoritiesIterGenerator(),
11276                        authoritiesIterator);
11277                if (intentListCopy.size() == 0) {
11278                    // no more intents to match; we're not equivalent
11279                    if (DEBUG_FILTERS) {
11280                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11281                                + " package: " + applicationInfo.packageName
11282                                + " activity: " + intent.activity.className
11283                                + " origPrio: " + intent.getPriority());
11284                    }
11285                    intent.setPriority(0);
11286                    return;
11287                }
11288            }
11289
11290            // we found matching filter(s); app gets the max priority of all intents
11291            int cappedPriority = 0;
11292            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11293                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11294            }
11295            if (intent.getPriority() > cappedPriority) {
11296                if (DEBUG_FILTERS) {
11297                    Slog.i(TAG, "Found matching filter(s);"
11298                            + " cap priority to " + cappedPriority + ";"
11299                            + " package: " + applicationInfo.packageName
11300                            + " activity: " + intent.activity.className
11301                            + " origPrio: " + intent.getPriority());
11302                }
11303                intent.setPriority(cappedPriority);
11304                return;
11305            }
11306            // all this for nothing; the requested priority was <= what was on the system
11307        }
11308
11309        public final void addActivity(PackageParser.Activity a, String type) {
11310            mActivities.put(a.getComponentName(), a);
11311            if (DEBUG_SHOW_INFO)
11312                Log.v(
11313                TAG, "  " + type + " " +
11314                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11315            if (DEBUG_SHOW_INFO)
11316                Log.v(TAG, "    Class=" + a.info.name);
11317            final int NI = a.intents.size();
11318            for (int j=0; j<NI; j++) {
11319                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11320                if ("activity".equals(type)) {
11321                    final PackageSetting ps =
11322                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11323                    final List<PackageParser.Activity> systemActivities =
11324                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11325                    adjustPriority(systemActivities, intent);
11326                }
11327                if (DEBUG_SHOW_INFO) {
11328                    Log.v(TAG, "    IntentFilter:");
11329                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11330                }
11331                if (!intent.debugCheck()) {
11332                    Log.w(TAG, "==> For Activity " + a.info.name);
11333                }
11334                addFilter(intent);
11335            }
11336        }
11337
11338        public final void removeActivity(PackageParser.Activity a, String type) {
11339            mActivities.remove(a.getComponentName());
11340            if (DEBUG_SHOW_INFO) {
11341                Log.v(TAG, "  " + type + " "
11342                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11343                                : a.info.name) + ":");
11344                Log.v(TAG, "    Class=" + a.info.name);
11345            }
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 (DEBUG_SHOW_INFO) {
11350                    Log.v(TAG, "    IntentFilter:");
11351                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11352                }
11353                removeFilter(intent);
11354            }
11355        }
11356
11357        @Override
11358        protected boolean allowFilterResult(
11359                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11360            ActivityInfo filterAi = filter.activity.info;
11361            for (int i=dest.size()-1; i>=0; i--) {
11362                ActivityInfo destAi = dest.get(i).activityInfo;
11363                if (destAi.name == filterAi.name
11364                        && destAi.packageName == filterAi.packageName) {
11365                    return false;
11366                }
11367            }
11368            return true;
11369        }
11370
11371        @Override
11372        protected ActivityIntentInfo[] newArray(int size) {
11373            return new ActivityIntentInfo[size];
11374        }
11375
11376        @Override
11377        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11378            if (!sUserManager.exists(userId)) return true;
11379            PackageParser.Package p = filter.activity.owner;
11380            if (p != null) {
11381                PackageSetting ps = (PackageSetting)p.mExtras;
11382                if (ps != null) {
11383                    // System apps are never considered stopped for purposes of
11384                    // filtering, because there may be no way for the user to
11385                    // actually re-launch them.
11386                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11387                            && ps.getStopped(userId);
11388                }
11389            }
11390            return false;
11391        }
11392
11393        @Override
11394        protected boolean isPackageForFilter(String packageName,
11395                PackageParser.ActivityIntentInfo info) {
11396            return packageName.equals(info.activity.owner.packageName);
11397        }
11398
11399        @Override
11400        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11401                int match, int userId) {
11402            if (!sUserManager.exists(userId)) return null;
11403            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11404                return null;
11405            }
11406            final PackageParser.Activity activity = info.activity;
11407            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11408            if (ps == null) {
11409                return null;
11410            }
11411            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11412                    ps.readUserState(userId), userId);
11413            if (ai == null) {
11414                return null;
11415            }
11416            final ResolveInfo res = new ResolveInfo();
11417            res.activityInfo = ai;
11418            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11419                res.filter = info;
11420            }
11421            if (info != null) {
11422                res.handleAllWebDataURI = info.handleAllWebDataURI();
11423            }
11424            res.priority = info.getPriority();
11425            res.preferredOrder = activity.owner.mPreferredOrder;
11426            //System.out.println("Result: " + res.activityInfo.className +
11427            //                   " = " + res.priority);
11428            res.match = match;
11429            res.isDefault = info.hasDefault;
11430            res.labelRes = info.labelRes;
11431            res.nonLocalizedLabel = info.nonLocalizedLabel;
11432            if (userNeedsBadging(userId)) {
11433                res.noResourceId = true;
11434            } else {
11435                res.icon = info.icon;
11436            }
11437            res.iconResourceId = info.icon;
11438            res.system = res.activityInfo.applicationInfo.isSystemApp();
11439            return res;
11440        }
11441
11442        @Override
11443        protected void sortResults(List<ResolveInfo> results) {
11444            Collections.sort(results, mResolvePrioritySorter);
11445        }
11446
11447        @Override
11448        protected void dumpFilter(PrintWriter out, String prefix,
11449                PackageParser.ActivityIntentInfo filter) {
11450            out.print(prefix); out.print(
11451                    Integer.toHexString(System.identityHashCode(filter.activity)));
11452                    out.print(' ');
11453                    filter.activity.printComponentShortName(out);
11454                    out.print(" filter ");
11455                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11456        }
11457
11458        @Override
11459        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11460            return filter.activity;
11461        }
11462
11463        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11464            PackageParser.Activity activity = (PackageParser.Activity)label;
11465            out.print(prefix); out.print(
11466                    Integer.toHexString(System.identityHashCode(activity)));
11467                    out.print(' ');
11468                    activity.printComponentShortName(out);
11469            if (count > 1) {
11470                out.print(" ("); out.print(count); out.print(" filters)");
11471            }
11472            out.println();
11473        }
11474
11475        // Keys are String (activity class name), values are Activity.
11476        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11477                = new ArrayMap<ComponentName, PackageParser.Activity>();
11478        private int mFlags;
11479    }
11480
11481    private final class ServiceIntentResolver
11482            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11483        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11484                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11485            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11486            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11487                    isEphemeral, userId);
11488        }
11489
11490        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11491                int userId) {
11492            if (!sUserManager.exists(userId)) return null;
11493            mFlags = flags;
11494            return super.queryIntent(intent, resolvedType,
11495                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11496                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11497                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11498        }
11499
11500        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11501                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11502            if (!sUserManager.exists(userId)) return null;
11503            if (packageServices == null) {
11504                return null;
11505            }
11506            mFlags = flags;
11507            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11508            final boolean vislbleToEphemeral =
11509                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11510            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11511            final int N = packageServices.size();
11512            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11513                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11514
11515            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11516            for (int i = 0; i < N; ++i) {
11517                intentFilters = packageServices.get(i).intents;
11518                if (intentFilters != null && intentFilters.size() > 0) {
11519                    PackageParser.ServiceIntentInfo[] array =
11520                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11521                    intentFilters.toArray(array);
11522                    listCut.add(array);
11523                }
11524            }
11525            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11526                    vislbleToEphemeral, isEphemeral, listCut, userId);
11527        }
11528
11529        public final void addService(PackageParser.Service s) {
11530            mServices.put(s.getComponentName(), s);
11531            if (DEBUG_SHOW_INFO) {
11532                Log.v(TAG, "  "
11533                        + (s.info.nonLocalizedLabel != null
11534                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11535                Log.v(TAG, "    Class=" + s.info.name);
11536            }
11537            final int NI = s.intents.size();
11538            int j;
11539            for (j=0; j<NI; j++) {
11540                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11541                if (DEBUG_SHOW_INFO) {
11542                    Log.v(TAG, "    IntentFilter:");
11543                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11544                }
11545                if (!intent.debugCheck()) {
11546                    Log.w(TAG, "==> For Service " + s.info.name);
11547                }
11548                addFilter(intent);
11549            }
11550        }
11551
11552        public final void removeService(PackageParser.Service s) {
11553            mServices.remove(s.getComponentName());
11554            if (DEBUG_SHOW_INFO) {
11555                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11556                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11557                Log.v(TAG, "    Class=" + s.info.name);
11558            }
11559            final int NI = s.intents.size();
11560            int j;
11561            for (j=0; j<NI; j++) {
11562                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11563                if (DEBUG_SHOW_INFO) {
11564                    Log.v(TAG, "    IntentFilter:");
11565                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11566                }
11567                removeFilter(intent);
11568            }
11569        }
11570
11571        @Override
11572        protected boolean allowFilterResult(
11573                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11574            ServiceInfo filterSi = filter.service.info;
11575            for (int i=dest.size()-1; i>=0; i--) {
11576                ServiceInfo destAi = dest.get(i).serviceInfo;
11577                if (destAi.name == filterSi.name
11578                        && destAi.packageName == filterSi.packageName) {
11579                    return false;
11580                }
11581            }
11582            return true;
11583        }
11584
11585        @Override
11586        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11587            return new PackageParser.ServiceIntentInfo[size];
11588        }
11589
11590        @Override
11591        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11592            if (!sUserManager.exists(userId)) return true;
11593            PackageParser.Package p = filter.service.owner;
11594            if (p != null) {
11595                PackageSetting ps = (PackageSetting)p.mExtras;
11596                if (ps != null) {
11597                    // System apps are never considered stopped for purposes of
11598                    // filtering, because there may be no way for the user to
11599                    // actually re-launch them.
11600                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11601                            && ps.getStopped(userId);
11602                }
11603            }
11604            return false;
11605        }
11606
11607        @Override
11608        protected boolean isPackageForFilter(String packageName,
11609                PackageParser.ServiceIntentInfo info) {
11610            return packageName.equals(info.service.owner.packageName);
11611        }
11612
11613        @Override
11614        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11615                int match, int userId) {
11616            if (!sUserManager.exists(userId)) return null;
11617            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11618            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11619                return null;
11620            }
11621            final PackageParser.Service service = info.service;
11622            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11623            if (ps == null) {
11624                return null;
11625            }
11626            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11627                    ps.readUserState(userId), userId);
11628            if (si == null) {
11629                return null;
11630            }
11631            final ResolveInfo res = new ResolveInfo();
11632            res.serviceInfo = si;
11633            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11634                res.filter = filter;
11635            }
11636            res.priority = info.getPriority();
11637            res.preferredOrder = service.owner.mPreferredOrder;
11638            res.match = match;
11639            res.isDefault = info.hasDefault;
11640            res.labelRes = info.labelRes;
11641            res.nonLocalizedLabel = info.nonLocalizedLabel;
11642            res.icon = info.icon;
11643            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11644            return res;
11645        }
11646
11647        @Override
11648        protected void sortResults(List<ResolveInfo> results) {
11649            Collections.sort(results, mResolvePrioritySorter);
11650        }
11651
11652        @Override
11653        protected void dumpFilter(PrintWriter out, String prefix,
11654                PackageParser.ServiceIntentInfo filter) {
11655            out.print(prefix); out.print(
11656                    Integer.toHexString(System.identityHashCode(filter.service)));
11657                    out.print(' ');
11658                    filter.service.printComponentShortName(out);
11659                    out.print(" filter ");
11660                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11661        }
11662
11663        @Override
11664        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11665            return filter.service;
11666        }
11667
11668        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11669            PackageParser.Service service = (PackageParser.Service)label;
11670            out.print(prefix); out.print(
11671                    Integer.toHexString(System.identityHashCode(service)));
11672                    out.print(' ');
11673                    service.printComponentShortName(out);
11674            if (count > 1) {
11675                out.print(" ("); out.print(count); out.print(" filters)");
11676            }
11677            out.println();
11678        }
11679
11680//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11681//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11682//            final List<ResolveInfo> retList = Lists.newArrayList();
11683//            while (i.hasNext()) {
11684//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11685//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11686//                    retList.add(resolveInfo);
11687//                }
11688//            }
11689//            return retList;
11690//        }
11691
11692        // Keys are String (activity class name), values are Activity.
11693        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11694                = new ArrayMap<ComponentName, PackageParser.Service>();
11695        private int mFlags;
11696    }
11697
11698    private final class ProviderIntentResolver
11699            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11700        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11701                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11702            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11703            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11704                    isEphemeral, userId);
11705        }
11706
11707        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11708                int userId) {
11709            if (!sUserManager.exists(userId))
11710                return null;
11711            mFlags = flags;
11712            return super.queryIntent(intent, resolvedType,
11713                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11714                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11715                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11716        }
11717
11718        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11719                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11720            if (!sUserManager.exists(userId))
11721                return null;
11722            if (packageProviders == null) {
11723                return null;
11724            }
11725            mFlags = flags;
11726            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11727            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11728            final boolean vislbleToEphemeral =
11729                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11730            final int N = packageProviders.size();
11731            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11732                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11733
11734            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11735            for (int i = 0; i < N; ++i) {
11736                intentFilters = packageProviders.get(i).intents;
11737                if (intentFilters != null && intentFilters.size() > 0) {
11738                    PackageParser.ProviderIntentInfo[] array =
11739                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11740                    intentFilters.toArray(array);
11741                    listCut.add(array);
11742                }
11743            }
11744            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11745                    vislbleToEphemeral, isEphemeral, listCut, userId);
11746        }
11747
11748        public final void addProvider(PackageParser.Provider p) {
11749            if (mProviders.containsKey(p.getComponentName())) {
11750                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11751                return;
11752            }
11753
11754            mProviders.put(p.getComponentName(), p);
11755            if (DEBUG_SHOW_INFO) {
11756                Log.v(TAG, "  "
11757                        + (p.info.nonLocalizedLabel != null
11758                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11759                Log.v(TAG, "    Class=" + p.info.name);
11760            }
11761            final int NI = p.intents.size();
11762            int j;
11763            for (j = 0; j < NI; j++) {
11764                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11765                if (DEBUG_SHOW_INFO) {
11766                    Log.v(TAG, "    IntentFilter:");
11767                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11768                }
11769                if (!intent.debugCheck()) {
11770                    Log.w(TAG, "==> For Provider " + p.info.name);
11771                }
11772                addFilter(intent);
11773            }
11774        }
11775
11776        public final void removeProvider(PackageParser.Provider p) {
11777            mProviders.remove(p.getComponentName());
11778            if (DEBUG_SHOW_INFO) {
11779                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11780                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11781                Log.v(TAG, "    Class=" + p.info.name);
11782            }
11783            final int NI = p.intents.size();
11784            int j;
11785            for (j = 0; j < NI; j++) {
11786                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11787                if (DEBUG_SHOW_INFO) {
11788                    Log.v(TAG, "    IntentFilter:");
11789                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11790                }
11791                removeFilter(intent);
11792            }
11793        }
11794
11795        @Override
11796        protected boolean allowFilterResult(
11797                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11798            ProviderInfo filterPi = filter.provider.info;
11799            for (int i = dest.size() - 1; i >= 0; i--) {
11800                ProviderInfo destPi = dest.get(i).providerInfo;
11801                if (destPi.name == filterPi.name
11802                        && destPi.packageName == filterPi.packageName) {
11803                    return false;
11804                }
11805            }
11806            return true;
11807        }
11808
11809        @Override
11810        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11811            return new PackageParser.ProviderIntentInfo[size];
11812        }
11813
11814        @Override
11815        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11816            if (!sUserManager.exists(userId))
11817                return true;
11818            PackageParser.Package p = filter.provider.owner;
11819            if (p != null) {
11820                PackageSetting ps = (PackageSetting) p.mExtras;
11821                if (ps != null) {
11822                    // System apps are never considered stopped for purposes of
11823                    // filtering, because there may be no way for the user to
11824                    // actually re-launch them.
11825                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11826                            && ps.getStopped(userId);
11827                }
11828            }
11829            return false;
11830        }
11831
11832        @Override
11833        protected boolean isPackageForFilter(String packageName,
11834                PackageParser.ProviderIntentInfo info) {
11835            return packageName.equals(info.provider.owner.packageName);
11836        }
11837
11838        @Override
11839        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11840                int match, int userId) {
11841            if (!sUserManager.exists(userId))
11842                return null;
11843            final PackageParser.ProviderIntentInfo info = filter;
11844            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11845                return null;
11846            }
11847            final PackageParser.Provider provider = info.provider;
11848            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11849            if (ps == null) {
11850                return null;
11851            }
11852            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11853                    ps.readUserState(userId), userId);
11854            if (pi == null) {
11855                return null;
11856            }
11857            final ResolveInfo res = new ResolveInfo();
11858            res.providerInfo = pi;
11859            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11860                res.filter = filter;
11861            }
11862            res.priority = info.getPriority();
11863            res.preferredOrder = provider.owner.mPreferredOrder;
11864            res.match = match;
11865            res.isDefault = info.hasDefault;
11866            res.labelRes = info.labelRes;
11867            res.nonLocalizedLabel = info.nonLocalizedLabel;
11868            res.icon = info.icon;
11869            res.system = res.providerInfo.applicationInfo.isSystemApp();
11870            return res;
11871        }
11872
11873        @Override
11874        protected void sortResults(List<ResolveInfo> results) {
11875            Collections.sort(results, mResolvePrioritySorter);
11876        }
11877
11878        @Override
11879        protected void dumpFilter(PrintWriter out, String prefix,
11880                PackageParser.ProviderIntentInfo filter) {
11881            out.print(prefix);
11882            out.print(
11883                    Integer.toHexString(System.identityHashCode(filter.provider)));
11884            out.print(' ');
11885            filter.provider.printComponentShortName(out);
11886            out.print(" filter ");
11887            out.println(Integer.toHexString(System.identityHashCode(filter)));
11888        }
11889
11890        @Override
11891        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11892            return filter.provider;
11893        }
11894
11895        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11896            PackageParser.Provider provider = (PackageParser.Provider)label;
11897            out.print(prefix); out.print(
11898                    Integer.toHexString(System.identityHashCode(provider)));
11899                    out.print(' ');
11900                    provider.printComponentShortName(out);
11901            if (count > 1) {
11902                out.print(" ("); out.print(count); out.print(" filters)");
11903            }
11904            out.println();
11905        }
11906
11907        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11908                = new ArrayMap<ComponentName, PackageParser.Provider>();
11909        private int mFlags;
11910    }
11911
11912    static final class EphemeralIntentResolver
11913            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11914        /**
11915         * The result that has the highest defined order. Ordering applies on a
11916         * per-package basis. Mapping is from package name to Pair of order and
11917         * EphemeralResolveInfo.
11918         * <p>
11919         * NOTE: This is implemented as a field variable for convenience and efficiency.
11920         * By having a field variable, we're able to track filter ordering as soon as
11921         * a non-zero order is defined. Otherwise, multiple loops across the result set
11922         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11923         * this needs to be contained entirely within {@link #filterResults()}.
11924         */
11925        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11926
11927        @Override
11928        protected EphemeralResponse[] newArray(int size) {
11929            return new EphemeralResponse[size];
11930        }
11931
11932        @Override
11933        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11934            return true;
11935        }
11936
11937        @Override
11938        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11939                int userId) {
11940            if (!sUserManager.exists(userId)) {
11941                return null;
11942            }
11943            final String packageName = responseObj.resolveInfo.getPackageName();
11944            final Integer order = responseObj.getOrder();
11945            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11946                    mOrderResult.get(packageName);
11947            // ordering is enabled and this item's order isn't high enough
11948            if (lastOrderResult != null && lastOrderResult.first >= order) {
11949                return null;
11950            }
11951            final EphemeralResolveInfo res = responseObj.resolveInfo;
11952            if (order > 0) {
11953                // non-zero order, enable ordering
11954                mOrderResult.put(packageName, new Pair<>(order, res));
11955            }
11956            return responseObj;
11957        }
11958
11959        @Override
11960        protected void filterResults(List<EphemeralResponse> results) {
11961            // only do work if ordering is enabled [most of the time it won't be]
11962            if (mOrderResult.size() == 0) {
11963                return;
11964            }
11965            int resultSize = results.size();
11966            for (int i = 0; i < resultSize; i++) {
11967                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11968                final String packageName = info.getPackageName();
11969                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11970                if (savedInfo == null) {
11971                    // package doesn't having ordering
11972                    continue;
11973                }
11974                if (savedInfo.second == info) {
11975                    // circled back to the highest ordered item; remove from order list
11976                    mOrderResult.remove(savedInfo);
11977                    if (mOrderResult.size() == 0) {
11978                        // no more ordered items
11979                        break;
11980                    }
11981                    continue;
11982                }
11983                // item has a worse order, remove it from the result list
11984                results.remove(i);
11985                resultSize--;
11986                i--;
11987            }
11988        }
11989    }
11990
11991    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11992            new Comparator<ResolveInfo>() {
11993        public int compare(ResolveInfo r1, ResolveInfo r2) {
11994            int v1 = r1.priority;
11995            int v2 = r2.priority;
11996            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11997            if (v1 != v2) {
11998                return (v1 > v2) ? -1 : 1;
11999            }
12000            v1 = r1.preferredOrder;
12001            v2 = r2.preferredOrder;
12002            if (v1 != v2) {
12003                return (v1 > v2) ? -1 : 1;
12004            }
12005            if (r1.isDefault != r2.isDefault) {
12006                return r1.isDefault ? -1 : 1;
12007            }
12008            v1 = r1.match;
12009            v2 = r2.match;
12010            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12011            if (v1 != v2) {
12012                return (v1 > v2) ? -1 : 1;
12013            }
12014            if (r1.system != r2.system) {
12015                return r1.system ? -1 : 1;
12016            }
12017            if (r1.activityInfo != null) {
12018                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12019            }
12020            if (r1.serviceInfo != null) {
12021                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12022            }
12023            if (r1.providerInfo != null) {
12024                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12025            }
12026            return 0;
12027        }
12028    };
12029
12030    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12031            new Comparator<ProviderInfo>() {
12032        public int compare(ProviderInfo p1, ProviderInfo p2) {
12033            final int v1 = p1.initOrder;
12034            final int v2 = p2.initOrder;
12035            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12036        }
12037    };
12038
12039    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12040            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12041            final int[] userIds) {
12042        mHandler.post(new Runnable() {
12043            @Override
12044            public void run() {
12045                try {
12046                    final IActivityManager am = ActivityManager.getService();
12047                    if (am == null) return;
12048                    final int[] resolvedUserIds;
12049                    if (userIds == null) {
12050                        resolvedUserIds = am.getRunningUserIds();
12051                    } else {
12052                        resolvedUserIds = userIds;
12053                    }
12054                    for (int id : resolvedUserIds) {
12055                        final Intent intent = new Intent(action,
12056                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12057                        if (extras != null) {
12058                            intent.putExtras(extras);
12059                        }
12060                        if (targetPkg != null) {
12061                            intent.setPackage(targetPkg);
12062                        }
12063                        // Modify the UID when posting to other users
12064                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12065                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12066                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12067                            intent.putExtra(Intent.EXTRA_UID, uid);
12068                        }
12069                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12070                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12071                        if (DEBUG_BROADCASTS) {
12072                            RuntimeException here = new RuntimeException("here");
12073                            here.fillInStackTrace();
12074                            Slog.d(TAG, "Sending to user " + id + ": "
12075                                    + intent.toShortString(false, true, false, false)
12076                                    + " " + intent.getExtras(), here);
12077                        }
12078                        am.broadcastIntent(null, intent, null, finishedReceiver,
12079                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12080                                null, finishedReceiver != null, false, id);
12081                    }
12082                } catch (RemoteException ex) {
12083                }
12084            }
12085        });
12086    }
12087
12088    /**
12089     * Check if the external storage media is available. This is true if there
12090     * is a mounted external storage medium or if the external storage is
12091     * emulated.
12092     */
12093    private boolean isExternalMediaAvailable() {
12094        return mMediaMounted || Environment.isExternalStorageEmulated();
12095    }
12096
12097    @Override
12098    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12099        // writer
12100        synchronized (mPackages) {
12101            if (!isExternalMediaAvailable()) {
12102                // If the external storage is no longer mounted at this point,
12103                // the caller may not have been able to delete all of this
12104                // packages files and can not delete any more.  Bail.
12105                return null;
12106            }
12107            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12108            if (lastPackage != null) {
12109                pkgs.remove(lastPackage);
12110            }
12111            if (pkgs.size() > 0) {
12112                return pkgs.get(0);
12113            }
12114        }
12115        return null;
12116    }
12117
12118    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12119        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12120                userId, andCode ? 1 : 0, packageName);
12121        if (mSystemReady) {
12122            msg.sendToTarget();
12123        } else {
12124            if (mPostSystemReadyMessages == null) {
12125                mPostSystemReadyMessages = new ArrayList<>();
12126            }
12127            mPostSystemReadyMessages.add(msg);
12128        }
12129    }
12130
12131    void startCleaningPackages() {
12132        // reader
12133        if (!isExternalMediaAvailable()) {
12134            return;
12135        }
12136        synchronized (mPackages) {
12137            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12138                return;
12139            }
12140        }
12141        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12142        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12143        IActivityManager am = ActivityManager.getService();
12144        if (am != null) {
12145            try {
12146                am.startService(null, intent, null, mContext.getOpPackageName(),
12147                        UserHandle.USER_SYSTEM);
12148            } catch (RemoteException e) {
12149            }
12150        }
12151    }
12152
12153    @Override
12154    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12155            int installFlags, String installerPackageName, int userId) {
12156        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12157
12158        final int callingUid = Binder.getCallingUid();
12159        enforceCrossUserPermission(callingUid, userId,
12160                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12161
12162        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12163            try {
12164                if (observer != null) {
12165                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12166                }
12167            } catch (RemoteException re) {
12168            }
12169            return;
12170        }
12171
12172        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12173            installFlags |= PackageManager.INSTALL_FROM_ADB;
12174
12175        } else {
12176            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12177            // about installerPackageName.
12178
12179            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12180            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12181        }
12182
12183        UserHandle user;
12184        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12185            user = UserHandle.ALL;
12186        } else {
12187            user = new UserHandle(userId);
12188        }
12189
12190        // Only system components can circumvent runtime permissions when installing.
12191        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12192                && mContext.checkCallingOrSelfPermission(Manifest.permission
12193                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12194            throw new SecurityException("You need the "
12195                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12196                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12197        }
12198
12199        final File originFile = new File(originPath);
12200        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12201
12202        final Message msg = mHandler.obtainMessage(INIT_COPY);
12203        final VerificationInfo verificationInfo = new VerificationInfo(
12204                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12205        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12206                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12207                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12208                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12209        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12210        msg.obj = params;
12211
12212        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12213                System.identityHashCode(msg.obj));
12214        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12215                System.identityHashCode(msg.obj));
12216
12217        mHandler.sendMessage(msg);
12218    }
12219
12220    void installStage(String packageName, File stagedDir, String stagedCid,
12221            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12222            String installerPackageName, int installerUid, UserHandle user,
12223            Certificate[][] certificates) {
12224        if (DEBUG_EPHEMERAL) {
12225            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12226                Slog.d(TAG, "Ephemeral install of " + packageName);
12227            }
12228        }
12229        final VerificationInfo verificationInfo = new VerificationInfo(
12230                sessionParams.originatingUri, sessionParams.referrerUri,
12231                sessionParams.originatingUid, installerUid);
12232
12233        final OriginInfo origin;
12234        if (stagedDir != null) {
12235            origin = OriginInfo.fromStagedFile(stagedDir);
12236        } else {
12237            origin = OriginInfo.fromStagedContainer(stagedCid);
12238        }
12239
12240        final Message msg = mHandler.obtainMessage(INIT_COPY);
12241        final InstallParams params = new InstallParams(origin, null, observer,
12242                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12243                verificationInfo, user, sessionParams.abiOverride,
12244                sessionParams.grantedRuntimePermissions, certificates, sessionParams.installReason);
12245        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12246        msg.obj = params;
12247
12248        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12249                System.identityHashCode(msg.obj));
12250        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12251                System.identityHashCode(msg.obj));
12252
12253        mHandler.sendMessage(msg);
12254    }
12255
12256    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12257            int userId) {
12258        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12259        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12260    }
12261
12262    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12263            int appId, int... userIds) {
12264        if (ArrayUtils.isEmpty(userIds)) {
12265            return;
12266        }
12267        Bundle extras = new Bundle(1);
12268        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12269        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12270
12271        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12272                packageName, extras, 0, null, null, userIds);
12273        if (isSystem) {
12274            mHandler.post(() -> {
12275                        for (int userId : userIds) {
12276                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12277                        }
12278                    }
12279            );
12280        }
12281    }
12282
12283    /**
12284     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12285     * automatically without needing an explicit launch.
12286     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12287     */
12288    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12289        // If user is not running, the app didn't miss any broadcast
12290        if (!mUserManagerInternal.isUserRunning(userId)) {
12291            return;
12292        }
12293        final IActivityManager am = ActivityManager.getService();
12294        try {
12295            // Deliver LOCKED_BOOT_COMPLETED first
12296            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12297                    .setPackage(packageName);
12298            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12299            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12300                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12301
12302            // Deliver BOOT_COMPLETED only if user is unlocked
12303            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12304                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12305                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12306                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12307            }
12308        } catch (RemoteException e) {
12309            throw e.rethrowFromSystemServer();
12310        }
12311    }
12312
12313    @Override
12314    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12315            int userId) {
12316        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12317        PackageSetting pkgSetting;
12318        final int uid = Binder.getCallingUid();
12319        enforceCrossUserPermission(uid, userId,
12320                true /* requireFullPermission */, true /* checkShell */,
12321                "setApplicationHiddenSetting for user " + userId);
12322
12323        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12324            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12325            return false;
12326        }
12327
12328        long callingId = Binder.clearCallingIdentity();
12329        try {
12330            boolean sendAdded = false;
12331            boolean sendRemoved = false;
12332            // writer
12333            synchronized (mPackages) {
12334                pkgSetting = mSettings.mPackages.get(packageName);
12335                if (pkgSetting == null) {
12336                    return false;
12337                }
12338                // Do not allow "android" is being disabled
12339                if ("android".equals(packageName)) {
12340                    Slog.w(TAG, "Cannot hide package: android");
12341                    return false;
12342                }
12343                // Only allow protected packages to hide themselves.
12344                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12345                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12346                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12347                    return false;
12348                }
12349
12350                if (pkgSetting.getHidden(userId) != hidden) {
12351                    pkgSetting.setHidden(hidden, userId);
12352                    mSettings.writePackageRestrictionsLPr(userId);
12353                    if (hidden) {
12354                        sendRemoved = true;
12355                    } else {
12356                        sendAdded = true;
12357                    }
12358                }
12359            }
12360            if (sendAdded) {
12361                sendPackageAddedForUser(packageName, pkgSetting, userId);
12362                return true;
12363            }
12364            if (sendRemoved) {
12365                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12366                        "hiding pkg");
12367                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12368                return true;
12369            }
12370        } finally {
12371            Binder.restoreCallingIdentity(callingId);
12372        }
12373        return false;
12374    }
12375
12376    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12377            int userId) {
12378        final PackageRemovedInfo info = new PackageRemovedInfo();
12379        info.removedPackage = packageName;
12380        info.removedUsers = new int[] {userId};
12381        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12382        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12383    }
12384
12385    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12386        if (pkgList.length > 0) {
12387            Bundle extras = new Bundle(1);
12388            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12389
12390            sendPackageBroadcast(
12391                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12392                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12393                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12394                    new int[] {userId});
12395        }
12396    }
12397
12398    /**
12399     * Returns true if application is not found or there was an error. Otherwise it returns
12400     * the hidden state of the package for the given user.
12401     */
12402    @Override
12403    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12404        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12406                true /* requireFullPermission */, false /* checkShell */,
12407                "getApplicationHidden for user " + userId);
12408        PackageSetting pkgSetting;
12409        long callingId = Binder.clearCallingIdentity();
12410        try {
12411            // writer
12412            synchronized (mPackages) {
12413                pkgSetting = mSettings.mPackages.get(packageName);
12414                if (pkgSetting == null) {
12415                    return true;
12416                }
12417                return pkgSetting.getHidden(userId);
12418            }
12419        } finally {
12420            Binder.restoreCallingIdentity(callingId);
12421        }
12422    }
12423
12424    /**
12425     * @hide
12426     */
12427    @Override
12428    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
12429        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12430                null);
12431        PackageSetting pkgSetting;
12432        final int uid = Binder.getCallingUid();
12433        enforceCrossUserPermission(uid, userId,
12434                true /* requireFullPermission */, true /* checkShell */,
12435                "installExistingPackage for user " + userId);
12436        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12437            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12438        }
12439
12440        long callingId = Binder.clearCallingIdentity();
12441        try {
12442            boolean installed = false;
12443
12444            // writer
12445            synchronized (mPackages) {
12446                pkgSetting = mSettings.mPackages.get(packageName);
12447                if (pkgSetting == null) {
12448                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12449                }
12450                if (!pkgSetting.getInstalled(userId)) {
12451                    pkgSetting.setInstalled(true, userId);
12452                    pkgSetting.setHidden(false, userId);
12453                    pkgSetting.setInstallReason(installReason, userId);
12454                    mSettings.writePackageRestrictionsLPr(userId);
12455                    installed = true;
12456                }
12457            }
12458
12459            if (installed) {
12460                if (pkgSetting.pkg != null) {
12461                    synchronized (mInstallLock) {
12462                        // We don't need to freeze for a brand new install
12463                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12464                    }
12465                }
12466                sendPackageAddedForUser(packageName, pkgSetting, userId);
12467            }
12468        } finally {
12469            Binder.restoreCallingIdentity(callingId);
12470        }
12471
12472        return PackageManager.INSTALL_SUCCEEDED;
12473    }
12474
12475    boolean isUserRestricted(int userId, String restrictionKey) {
12476        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12477        if (restrictions.getBoolean(restrictionKey, false)) {
12478            Log.w(TAG, "User is restricted: " + restrictionKey);
12479            return true;
12480        }
12481        return false;
12482    }
12483
12484    @Override
12485    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12486            int userId) {
12487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12488        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12489                true /* requireFullPermission */, true /* checkShell */,
12490                "setPackagesSuspended for user " + userId);
12491
12492        if (ArrayUtils.isEmpty(packageNames)) {
12493            return packageNames;
12494        }
12495
12496        // List of package names for whom the suspended state has changed.
12497        List<String> changedPackages = new ArrayList<>(packageNames.length);
12498        // List of package names for whom the suspended state is not set as requested in this
12499        // method.
12500        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12501        long callingId = Binder.clearCallingIdentity();
12502        try {
12503            for (int i = 0; i < packageNames.length; i++) {
12504                String packageName = packageNames[i];
12505                boolean changed = false;
12506                final int appId;
12507                synchronized (mPackages) {
12508                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12509                    if (pkgSetting == null) {
12510                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12511                                + "\". Skipping suspending/un-suspending.");
12512                        unactionedPackages.add(packageName);
12513                        continue;
12514                    }
12515                    appId = pkgSetting.appId;
12516                    if (pkgSetting.getSuspended(userId) != suspended) {
12517                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12518                            unactionedPackages.add(packageName);
12519                            continue;
12520                        }
12521                        pkgSetting.setSuspended(suspended, userId);
12522                        mSettings.writePackageRestrictionsLPr(userId);
12523                        changed = true;
12524                        changedPackages.add(packageName);
12525                    }
12526                }
12527
12528                if (changed && suspended) {
12529                    killApplication(packageName, UserHandle.getUid(userId, appId),
12530                            "suspending package");
12531                }
12532            }
12533        } finally {
12534            Binder.restoreCallingIdentity(callingId);
12535        }
12536
12537        if (!changedPackages.isEmpty()) {
12538            sendPackagesSuspendedForUser(changedPackages.toArray(
12539                    new String[changedPackages.size()]), userId, suspended);
12540        }
12541
12542        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12543    }
12544
12545    @Override
12546    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12548                true /* requireFullPermission */, false /* checkShell */,
12549                "isPackageSuspendedForUser for user " + userId);
12550        synchronized (mPackages) {
12551            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12552            if (pkgSetting == null) {
12553                throw new IllegalArgumentException("Unknown target package: " + packageName);
12554            }
12555            return pkgSetting.getSuspended(userId);
12556        }
12557    }
12558
12559    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12560        if (isPackageDeviceAdmin(packageName, userId)) {
12561            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12562                    + "\": has an active device admin");
12563            return false;
12564        }
12565
12566        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12567        if (packageName.equals(activeLauncherPackageName)) {
12568            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12569                    + "\": contains the active launcher");
12570            return false;
12571        }
12572
12573        if (packageName.equals(mRequiredInstallerPackage)) {
12574            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12575                    + "\": required for package installation");
12576            return false;
12577        }
12578
12579        if (packageName.equals(mRequiredUninstallerPackage)) {
12580            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12581                    + "\": required for package uninstallation");
12582            return false;
12583        }
12584
12585        if (packageName.equals(mRequiredVerifierPackage)) {
12586            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12587                    + "\": required for package verification");
12588            return false;
12589        }
12590
12591        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12592            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12593                    + "\": is the default dialer");
12594            return false;
12595        }
12596
12597        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12598            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12599                    + "\": protected package");
12600            return false;
12601        }
12602
12603        return true;
12604    }
12605
12606    private String getActiveLauncherPackageName(int userId) {
12607        Intent intent = new Intent(Intent.ACTION_MAIN);
12608        intent.addCategory(Intent.CATEGORY_HOME);
12609        ResolveInfo resolveInfo = resolveIntent(
12610                intent,
12611                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12612                PackageManager.MATCH_DEFAULT_ONLY,
12613                userId);
12614
12615        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12616    }
12617
12618    private String getDefaultDialerPackageName(int userId) {
12619        synchronized (mPackages) {
12620            return mSettings.getDefaultDialerPackageNameLPw(userId);
12621        }
12622    }
12623
12624    @Override
12625    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12626        mContext.enforceCallingOrSelfPermission(
12627                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12628                "Only package verification agents can verify applications");
12629
12630        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12631        final PackageVerificationResponse response = new PackageVerificationResponse(
12632                verificationCode, Binder.getCallingUid());
12633        msg.arg1 = id;
12634        msg.obj = response;
12635        mHandler.sendMessage(msg);
12636    }
12637
12638    @Override
12639    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12640            long millisecondsToDelay) {
12641        mContext.enforceCallingOrSelfPermission(
12642                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12643                "Only package verification agents can extend verification timeouts");
12644
12645        final PackageVerificationState state = mPendingVerification.get(id);
12646        final PackageVerificationResponse response = new PackageVerificationResponse(
12647                verificationCodeAtTimeout, Binder.getCallingUid());
12648
12649        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12650            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12651        }
12652        if (millisecondsToDelay < 0) {
12653            millisecondsToDelay = 0;
12654        }
12655        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12656                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12657            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12658        }
12659
12660        if ((state != null) && !state.timeoutExtended()) {
12661            state.extendTimeout();
12662
12663            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12664            msg.arg1 = id;
12665            msg.obj = response;
12666            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12667        }
12668    }
12669
12670    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12671            int verificationCode, UserHandle user) {
12672        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12673        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12674        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12675        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12676        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12677
12678        mContext.sendBroadcastAsUser(intent, user,
12679                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12680    }
12681
12682    private ComponentName matchComponentForVerifier(String packageName,
12683            List<ResolveInfo> receivers) {
12684        ActivityInfo targetReceiver = null;
12685
12686        final int NR = receivers.size();
12687        for (int i = 0; i < NR; i++) {
12688            final ResolveInfo info = receivers.get(i);
12689            if (info.activityInfo == null) {
12690                continue;
12691            }
12692
12693            if (packageName.equals(info.activityInfo.packageName)) {
12694                targetReceiver = info.activityInfo;
12695                break;
12696            }
12697        }
12698
12699        if (targetReceiver == null) {
12700            return null;
12701        }
12702
12703        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12704    }
12705
12706    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12707            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12708        if (pkgInfo.verifiers.length == 0) {
12709            return null;
12710        }
12711
12712        final int N = pkgInfo.verifiers.length;
12713        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12714        for (int i = 0; i < N; i++) {
12715            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12716
12717            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12718                    receivers);
12719            if (comp == null) {
12720                continue;
12721            }
12722
12723            final int verifierUid = getUidForVerifier(verifierInfo);
12724            if (verifierUid == -1) {
12725                continue;
12726            }
12727
12728            if (DEBUG_VERIFY) {
12729                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12730                        + " with the correct signature");
12731            }
12732            sufficientVerifiers.add(comp);
12733            verificationState.addSufficientVerifier(verifierUid);
12734        }
12735
12736        return sufficientVerifiers;
12737    }
12738
12739    private int getUidForVerifier(VerifierInfo verifierInfo) {
12740        synchronized (mPackages) {
12741            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12742            if (pkg == null) {
12743                return -1;
12744            } else if (pkg.mSignatures.length != 1) {
12745                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12746                        + " has more than one signature; ignoring");
12747                return -1;
12748            }
12749
12750            /*
12751             * If the public key of the package's signature does not match
12752             * our expected public key, then this is a different package and
12753             * we should skip.
12754             */
12755
12756            final byte[] expectedPublicKey;
12757            try {
12758                final Signature verifierSig = pkg.mSignatures[0];
12759                final PublicKey publicKey = verifierSig.getPublicKey();
12760                expectedPublicKey = publicKey.getEncoded();
12761            } catch (CertificateException e) {
12762                return -1;
12763            }
12764
12765            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12766
12767            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12768                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12769                        + " does not have the expected public key; ignoring");
12770                return -1;
12771            }
12772
12773            return pkg.applicationInfo.uid;
12774        }
12775    }
12776
12777    @Override
12778    public void finishPackageInstall(int token, boolean didLaunch) {
12779        enforceSystemOrRoot("Only the system is allowed to finish installs");
12780
12781        if (DEBUG_INSTALL) {
12782            Slog.v(TAG, "BM finishing package install for " + token);
12783        }
12784        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12785
12786        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12787        mHandler.sendMessage(msg);
12788    }
12789
12790    /**
12791     * Get the verification agent timeout.
12792     *
12793     * @return verification timeout in milliseconds
12794     */
12795    private long getVerificationTimeout() {
12796        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12797                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12798                DEFAULT_VERIFICATION_TIMEOUT);
12799    }
12800
12801    /**
12802     * Get the default verification agent response code.
12803     *
12804     * @return default verification response code
12805     */
12806    private int getDefaultVerificationResponse() {
12807        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12808                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12809                DEFAULT_VERIFICATION_RESPONSE);
12810    }
12811
12812    /**
12813     * Check whether or not package verification has been enabled.
12814     *
12815     * @return true if verification should be performed
12816     */
12817    private boolean isVerificationEnabled(int userId, int installFlags) {
12818        if (!DEFAULT_VERIFY_ENABLE) {
12819            return false;
12820        }
12821        // Ephemeral apps don't get the full verification treatment
12822        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12823            if (DEBUG_EPHEMERAL) {
12824                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12825            }
12826            return false;
12827        }
12828
12829        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12830
12831        // Check if installing from ADB
12832        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12833            // Do not run verification in a test harness environment
12834            if (ActivityManager.isRunningInTestHarness()) {
12835                return false;
12836            }
12837            if (ensureVerifyAppsEnabled) {
12838                return true;
12839            }
12840            // Check if the developer does not want package verification for ADB installs
12841            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12842                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12843                return false;
12844            }
12845        }
12846
12847        if (ensureVerifyAppsEnabled) {
12848            return true;
12849        }
12850
12851        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12852                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12853    }
12854
12855    @Override
12856    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12857            throws RemoteException {
12858        mContext.enforceCallingOrSelfPermission(
12859                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12860                "Only intentfilter verification agents can verify applications");
12861
12862        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12863        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12864                Binder.getCallingUid(), verificationCode, failedDomains);
12865        msg.arg1 = id;
12866        msg.obj = response;
12867        mHandler.sendMessage(msg);
12868    }
12869
12870    @Override
12871    public int getIntentVerificationStatus(String packageName, int userId) {
12872        synchronized (mPackages) {
12873            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12874        }
12875    }
12876
12877    @Override
12878    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12879        mContext.enforceCallingOrSelfPermission(
12880                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12881
12882        boolean result = false;
12883        synchronized (mPackages) {
12884            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12885        }
12886        if (result) {
12887            scheduleWritePackageRestrictionsLocked(userId);
12888        }
12889        return result;
12890    }
12891
12892    @Override
12893    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12894            String packageName) {
12895        synchronized (mPackages) {
12896            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12897        }
12898    }
12899
12900    @Override
12901    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12902        if (TextUtils.isEmpty(packageName)) {
12903            return ParceledListSlice.emptyList();
12904        }
12905        synchronized (mPackages) {
12906            PackageParser.Package pkg = mPackages.get(packageName);
12907            if (pkg == null || pkg.activities == null) {
12908                return ParceledListSlice.emptyList();
12909            }
12910            final int count = pkg.activities.size();
12911            ArrayList<IntentFilter> result = new ArrayList<>();
12912            for (int n=0; n<count; n++) {
12913                PackageParser.Activity activity = pkg.activities.get(n);
12914                if (activity.intents != null && activity.intents.size() > 0) {
12915                    result.addAll(activity.intents);
12916                }
12917            }
12918            return new ParceledListSlice<>(result);
12919        }
12920    }
12921
12922    @Override
12923    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12924        mContext.enforceCallingOrSelfPermission(
12925                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12926
12927        synchronized (mPackages) {
12928            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12929            if (packageName != null) {
12930                result |= updateIntentVerificationStatus(packageName,
12931                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12932                        userId);
12933                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12934                        packageName, userId);
12935            }
12936            return result;
12937        }
12938    }
12939
12940    @Override
12941    public String getDefaultBrowserPackageName(int userId) {
12942        synchronized (mPackages) {
12943            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12944        }
12945    }
12946
12947    /**
12948     * Get the "allow unknown sources" setting.
12949     *
12950     * @return the current "allow unknown sources" setting
12951     */
12952    private int getUnknownSourcesSettings() {
12953        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12954                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12955                -1);
12956    }
12957
12958    @Override
12959    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12960        final int uid = Binder.getCallingUid();
12961        // writer
12962        synchronized (mPackages) {
12963            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12964            if (targetPackageSetting == null) {
12965                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12966            }
12967
12968            PackageSetting installerPackageSetting;
12969            if (installerPackageName != null) {
12970                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12971                if (installerPackageSetting == null) {
12972                    throw new IllegalArgumentException("Unknown installer package: "
12973                            + installerPackageName);
12974                }
12975            } else {
12976                installerPackageSetting = null;
12977            }
12978
12979            Signature[] callerSignature;
12980            Object obj = mSettings.getUserIdLPr(uid);
12981            if (obj != null) {
12982                if (obj instanceof SharedUserSetting) {
12983                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12984                } else if (obj instanceof PackageSetting) {
12985                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12986                } else {
12987                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12988                }
12989            } else {
12990                throw new SecurityException("Unknown calling UID: " + uid);
12991            }
12992
12993            // Verify: can't set installerPackageName to a package that is
12994            // not signed with the same cert as the caller.
12995            if (installerPackageSetting != null) {
12996                if (compareSignatures(callerSignature,
12997                        installerPackageSetting.signatures.mSignatures)
12998                        != PackageManager.SIGNATURE_MATCH) {
12999                    throw new SecurityException(
13000                            "Caller does not have same cert as new installer package "
13001                            + installerPackageName);
13002                }
13003            }
13004
13005            // Verify: if target already has an installer package, it must
13006            // be signed with the same cert as the caller.
13007            if (targetPackageSetting.installerPackageName != null) {
13008                PackageSetting setting = mSettings.mPackages.get(
13009                        targetPackageSetting.installerPackageName);
13010                // If the currently set package isn't valid, then it's always
13011                // okay to change it.
13012                if (setting != null) {
13013                    if (compareSignatures(callerSignature,
13014                            setting.signatures.mSignatures)
13015                            != PackageManager.SIGNATURE_MATCH) {
13016                        throw new SecurityException(
13017                                "Caller does not have same cert as old installer package "
13018                                + targetPackageSetting.installerPackageName);
13019                    }
13020                }
13021            }
13022
13023            // Okay!
13024            targetPackageSetting.installerPackageName = installerPackageName;
13025            if (installerPackageName != null) {
13026                mSettings.mInstallerPackages.add(installerPackageName);
13027            }
13028            scheduleWriteSettingsLocked();
13029        }
13030    }
13031
13032    @Override
13033    public void setApplicationCategoryHint(String packageName, int categoryHint,
13034            String callerPackageName) {
13035        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13036                callerPackageName);
13037        synchronized (mPackages) {
13038            PackageSetting ps = mSettings.mPackages.get(packageName);
13039            if (ps == null) {
13040                throw new IllegalArgumentException("Unknown target package " + packageName);
13041            }
13042
13043            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13044                throw new IllegalArgumentException("Calling package " + callerPackageName
13045                        + " is not installer for " + packageName);
13046            }
13047
13048            if (ps.categoryHint != categoryHint) {
13049                ps.categoryHint = categoryHint;
13050                scheduleWriteSettingsLocked();
13051            }
13052        }
13053    }
13054
13055    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13056        // Queue up an async operation since the package installation may take a little while.
13057        mHandler.post(new Runnable() {
13058            public void run() {
13059                mHandler.removeCallbacks(this);
13060                 // Result object to be returned
13061                PackageInstalledInfo res = new PackageInstalledInfo();
13062                res.setReturnCode(currentStatus);
13063                res.uid = -1;
13064                res.pkg = null;
13065                res.removedInfo = null;
13066                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13067                    args.doPreInstall(res.returnCode);
13068                    synchronized (mInstallLock) {
13069                        installPackageTracedLI(args, res);
13070                    }
13071                    args.doPostInstall(res.returnCode, res.uid);
13072                }
13073
13074                // A restore should be performed at this point if (a) the install
13075                // succeeded, (b) the operation is not an update, and (c) the new
13076                // package has not opted out of backup participation.
13077                final boolean update = res.removedInfo != null
13078                        && res.removedInfo.removedPackage != null;
13079                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13080                boolean doRestore = !update
13081                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13082
13083                // Set up the post-install work request bookkeeping.  This will be used
13084                // and cleaned up by the post-install event handling regardless of whether
13085                // there's a restore pass performed.  Token values are >= 1.
13086                int token;
13087                if (mNextInstallToken < 0) mNextInstallToken = 1;
13088                token = mNextInstallToken++;
13089
13090                PostInstallData data = new PostInstallData(args, res);
13091                mRunningInstalls.put(token, data);
13092                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13093
13094                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13095                    // Pass responsibility to the Backup Manager.  It will perform a
13096                    // restore if appropriate, then pass responsibility back to the
13097                    // Package Manager to run the post-install observer callbacks
13098                    // and broadcasts.
13099                    IBackupManager bm = IBackupManager.Stub.asInterface(
13100                            ServiceManager.getService(Context.BACKUP_SERVICE));
13101                    if (bm != null) {
13102                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13103                                + " to BM for possible restore");
13104                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13105                        try {
13106                            // TODO: http://b/22388012
13107                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13108                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13109                            } else {
13110                                doRestore = false;
13111                            }
13112                        } catch (RemoteException e) {
13113                            // can't happen; the backup manager is local
13114                        } catch (Exception e) {
13115                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13116                            doRestore = false;
13117                        }
13118                    } else {
13119                        Slog.e(TAG, "Backup Manager not found!");
13120                        doRestore = false;
13121                    }
13122                }
13123
13124                if (!doRestore) {
13125                    // No restore possible, or the Backup Manager was mysteriously not
13126                    // available -- just fire the post-install work request directly.
13127                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13128
13129                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13130
13131                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13132                    mHandler.sendMessage(msg);
13133                }
13134            }
13135        });
13136    }
13137
13138    /**
13139     * Callback from PackageSettings whenever an app is first transitioned out of the
13140     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13141     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13142     * here whether the app is the target of an ongoing install, and only send the
13143     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13144     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13145     * handling.
13146     */
13147    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13148        // Serialize this with the rest of the install-process message chain.  In the
13149        // restore-at-install case, this Runnable will necessarily run before the
13150        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13151        // are coherent.  In the non-restore case, the app has already completed install
13152        // and been launched through some other means, so it is not in a problematic
13153        // state for observers to see the FIRST_LAUNCH signal.
13154        mHandler.post(new Runnable() {
13155            @Override
13156            public void run() {
13157                for (int i = 0; i < mRunningInstalls.size(); i++) {
13158                    final PostInstallData data = mRunningInstalls.valueAt(i);
13159                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13160                        continue;
13161                    }
13162                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13163                        // right package; but is it for the right user?
13164                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13165                            if (userId == data.res.newUsers[uIndex]) {
13166                                if (DEBUG_BACKUP) {
13167                                    Slog.i(TAG, "Package " + pkgName
13168                                            + " being restored so deferring FIRST_LAUNCH");
13169                                }
13170                                return;
13171                            }
13172                        }
13173                    }
13174                }
13175                // didn't find it, so not being restored
13176                if (DEBUG_BACKUP) {
13177                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13178                }
13179                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13180            }
13181        });
13182    }
13183
13184    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13185        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13186                installerPkg, null, userIds);
13187    }
13188
13189    private abstract class HandlerParams {
13190        private static final int MAX_RETRIES = 4;
13191
13192        /**
13193         * Number of times startCopy() has been attempted and had a non-fatal
13194         * error.
13195         */
13196        private int mRetries = 0;
13197
13198        /** User handle for the user requesting the information or installation. */
13199        private final UserHandle mUser;
13200        String traceMethod;
13201        int traceCookie;
13202
13203        HandlerParams(UserHandle user) {
13204            mUser = user;
13205        }
13206
13207        UserHandle getUser() {
13208            return mUser;
13209        }
13210
13211        HandlerParams setTraceMethod(String traceMethod) {
13212            this.traceMethod = traceMethod;
13213            return this;
13214        }
13215
13216        HandlerParams setTraceCookie(int traceCookie) {
13217            this.traceCookie = traceCookie;
13218            return this;
13219        }
13220
13221        final boolean startCopy() {
13222            boolean res;
13223            try {
13224                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13225
13226                if (++mRetries > MAX_RETRIES) {
13227                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13228                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13229                    handleServiceError();
13230                    return false;
13231                } else {
13232                    handleStartCopy();
13233                    res = true;
13234                }
13235            } catch (RemoteException e) {
13236                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13237                mHandler.sendEmptyMessage(MCS_RECONNECT);
13238                res = false;
13239            }
13240            handleReturnCode();
13241            return res;
13242        }
13243
13244        final void serviceError() {
13245            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13246            handleServiceError();
13247            handleReturnCode();
13248        }
13249
13250        abstract void handleStartCopy() throws RemoteException;
13251        abstract void handleServiceError();
13252        abstract void handleReturnCode();
13253    }
13254
13255    class MeasureParams extends HandlerParams {
13256        private final PackageStats mStats;
13257        private boolean mSuccess;
13258
13259        private final IPackageStatsObserver mObserver;
13260
13261        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13262            super(new UserHandle(stats.userHandle));
13263            mObserver = observer;
13264            mStats = stats;
13265        }
13266
13267        @Override
13268        public String toString() {
13269            return "MeasureParams{"
13270                + Integer.toHexString(System.identityHashCode(this))
13271                + " " + mStats.packageName + "}";
13272        }
13273
13274        @Override
13275        void handleStartCopy() throws RemoteException {
13276            synchronized (mInstallLock) {
13277                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13278            }
13279
13280            if (mSuccess) {
13281                boolean mounted = false;
13282                try {
13283                    final String status = Environment.getExternalStorageState();
13284                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13285                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13286                } catch (Exception e) {
13287                }
13288
13289                if (mounted) {
13290                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13291
13292                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13293                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13294
13295                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13296                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13297
13298                    // Always subtract cache size, since it's a subdirectory
13299                    mStats.externalDataSize -= mStats.externalCacheSize;
13300
13301                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13302                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13303
13304                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13305                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13306                }
13307            }
13308        }
13309
13310        @Override
13311        void handleReturnCode() {
13312            if (mObserver != null) {
13313                try {
13314                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13315                } catch (RemoteException e) {
13316                    Slog.i(TAG, "Observer no longer exists.");
13317                }
13318            }
13319        }
13320
13321        @Override
13322        void handleServiceError() {
13323            Slog.e(TAG, "Could not measure application " + mStats.packageName
13324                            + " external storage");
13325        }
13326    }
13327
13328    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13329            throws RemoteException {
13330        long result = 0;
13331        for (File path : paths) {
13332            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13333        }
13334        return result;
13335    }
13336
13337    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13338        for (File path : paths) {
13339            try {
13340                mcs.clearDirectory(path.getAbsolutePath());
13341            } catch (RemoteException e) {
13342            }
13343        }
13344    }
13345
13346    static class OriginInfo {
13347        /**
13348         * Location where install is coming from, before it has been
13349         * copied/renamed into place. This could be a single monolithic APK
13350         * file, or a cluster directory. This location may be untrusted.
13351         */
13352        final File file;
13353        final String cid;
13354
13355        /**
13356         * Flag indicating that {@link #file} or {@link #cid} has already been
13357         * staged, meaning downstream users don't need to defensively copy the
13358         * contents.
13359         */
13360        final boolean staged;
13361
13362        /**
13363         * Flag indicating that {@link #file} or {@link #cid} is an already
13364         * installed app that is being moved.
13365         */
13366        final boolean existing;
13367
13368        final String resolvedPath;
13369        final File resolvedFile;
13370
13371        static OriginInfo fromNothing() {
13372            return new OriginInfo(null, null, false, false);
13373        }
13374
13375        static OriginInfo fromUntrustedFile(File file) {
13376            return new OriginInfo(file, null, false, false);
13377        }
13378
13379        static OriginInfo fromExistingFile(File file) {
13380            return new OriginInfo(file, null, false, true);
13381        }
13382
13383        static OriginInfo fromStagedFile(File file) {
13384            return new OriginInfo(file, null, true, false);
13385        }
13386
13387        static OriginInfo fromStagedContainer(String cid) {
13388            return new OriginInfo(null, cid, true, false);
13389        }
13390
13391        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13392            this.file = file;
13393            this.cid = cid;
13394            this.staged = staged;
13395            this.existing = existing;
13396
13397            if (cid != null) {
13398                resolvedPath = PackageHelper.getSdDir(cid);
13399                resolvedFile = new File(resolvedPath);
13400            } else if (file != null) {
13401                resolvedPath = file.getAbsolutePath();
13402                resolvedFile = file;
13403            } else {
13404                resolvedPath = null;
13405                resolvedFile = null;
13406            }
13407        }
13408    }
13409
13410    static class MoveInfo {
13411        final int moveId;
13412        final String fromUuid;
13413        final String toUuid;
13414        final String packageName;
13415        final String dataAppName;
13416        final int appId;
13417        final String seinfo;
13418        final int targetSdkVersion;
13419
13420        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13421                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13422            this.moveId = moveId;
13423            this.fromUuid = fromUuid;
13424            this.toUuid = toUuid;
13425            this.packageName = packageName;
13426            this.dataAppName = dataAppName;
13427            this.appId = appId;
13428            this.seinfo = seinfo;
13429            this.targetSdkVersion = targetSdkVersion;
13430        }
13431    }
13432
13433    static class VerificationInfo {
13434        /** A constant used to indicate that a uid value is not present. */
13435        public static final int NO_UID = -1;
13436
13437        /** URI referencing where the package was downloaded from. */
13438        final Uri originatingUri;
13439
13440        /** HTTP referrer URI associated with the originatingURI. */
13441        final Uri referrer;
13442
13443        /** UID of the application that the install request originated from. */
13444        final int originatingUid;
13445
13446        /** UID of application requesting the install */
13447        final int installerUid;
13448
13449        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13450            this.originatingUri = originatingUri;
13451            this.referrer = referrer;
13452            this.originatingUid = originatingUid;
13453            this.installerUid = installerUid;
13454        }
13455    }
13456
13457    class InstallParams extends HandlerParams {
13458        final OriginInfo origin;
13459        final MoveInfo move;
13460        final IPackageInstallObserver2 observer;
13461        int installFlags;
13462        final String installerPackageName;
13463        final String volumeUuid;
13464        private InstallArgs mArgs;
13465        private int mRet;
13466        final String packageAbiOverride;
13467        final String[] grantedRuntimePermissions;
13468        final VerificationInfo verificationInfo;
13469        final Certificate[][] certificates;
13470        final int installReason;
13471
13472        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13473                int installFlags, String installerPackageName, String volumeUuid,
13474                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13475                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
13476            super(user);
13477            this.origin = origin;
13478            this.move = move;
13479            this.observer = observer;
13480            this.installFlags = installFlags;
13481            this.installerPackageName = installerPackageName;
13482            this.volumeUuid = volumeUuid;
13483            this.verificationInfo = verificationInfo;
13484            this.packageAbiOverride = packageAbiOverride;
13485            this.grantedRuntimePermissions = grantedPermissions;
13486            this.certificates = certificates;
13487            this.installReason = installReason;
13488        }
13489
13490        @Override
13491        public String toString() {
13492            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13493                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13494        }
13495
13496        private int installLocationPolicy(PackageInfoLite pkgLite) {
13497            String packageName = pkgLite.packageName;
13498            int installLocation = pkgLite.installLocation;
13499            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13500            // reader
13501            synchronized (mPackages) {
13502                // Currently installed package which the new package is attempting to replace or
13503                // null if no such package is installed.
13504                PackageParser.Package installedPkg = mPackages.get(packageName);
13505                // Package which currently owns the data which the new package will own if installed.
13506                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13507                // will be null whereas dataOwnerPkg will contain information about the package
13508                // which was uninstalled while keeping its data.
13509                PackageParser.Package dataOwnerPkg = installedPkg;
13510                if (dataOwnerPkg  == null) {
13511                    PackageSetting ps = mSettings.mPackages.get(packageName);
13512                    if (ps != null) {
13513                        dataOwnerPkg = ps.pkg;
13514                    }
13515                }
13516
13517                if (dataOwnerPkg != null) {
13518                    // If installed, the package will get access to data left on the device by its
13519                    // predecessor. As a security measure, this is permited only if this is not a
13520                    // version downgrade or if the predecessor package is marked as debuggable and
13521                    // a downgrade is explicitly requested.
13522                    //
13523                    // On debuggable platform builds, downgrades are permitted even for
13524                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13525                    // not offer security guarantees and thus it's OK to disable some security
13526                    // mechanisms to make debugging/testing easier on those builds. However, even on
13527                    // debuggable builds downgrades of packages are permitted only if requested via
13528                    // installFlags. This is because we aim to keep the behavior of debuggable
13529                    // platform builds as close as possible to the behavior of non-debuggable
13530                    // platform builds.
13531                    final boolean downgradeRequested =
13532                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13533                    final boolean packageDebuggable =
13534                                (dataOwnerPkg.applicationInfo.flags
13535                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13536                    final boolean downgradePermitted =
13537                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13538                    if (!downgradePermitted) {
13539                        try {
13540                            checkDowngrade(dataOwnerPkg, pkgLite);
13541                        } catch (PackageManagerException e) {
13542                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13543                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13544                        }
13545                    }
13546                }
13547
13548                if (installedPkg != null) {
13549                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13550                        // Check for updated system application.
13551                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13552                            if (onSd) {
13553                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13554                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13555                            }
13556                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13557                        } else {
13558                            if (onSd) {
13559                                // Install flag overrides everything.
13560                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13561                            }
13562                            // If current upgrade specifies particular preference
13563                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13564                                // Application explicitly specified internal.
13565                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13566                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13567                                // App explictly prefers external. Let policy decide
13568                            } else {
13569                                // Prefer previous location
13570                                if (isExternal(installedPkg)) {
13571                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13572                                }
13573                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13574                            }
13575                        }
13576                    } else {
13577                        // Invalid install. Return error code
13578                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13579                    }
13580                }
13581            }
13582            // All the special cases have been taken care of.
13583            // Return result based on recommended install location.
13584            if (onSd) {
13585                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13586            }
13587            return pkgLite.recommendedInstallLocation;
13588        }
13589
13590        /*
13591         * Invoke remote method to get package information and install
13592         * location values. Override install location based on default
13593         * policy if needed and then create install arguments based
13594         * on the install location.
13595         */
13596        public void handleStartCopy() throws RemoteException {
13597            int ret = PackageManager.INSTALL_SUCCEEDED;
13598
13599            // If we're already staged, we've firmly committed to an install location
13600            if (origin.staged) {
13601                if (origin.file != null) {
13602                    installFlags |= PackageManager.INSTALL_INTERNAL;
13603                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13604                } else if (origin.cid != null) {
13605                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13606                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13607                } else {
13608                    throw new IllegalStateException("Invalid stage location");
13609                }
13610            }
13611
13612            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13613            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13614            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13615            PackageInfoLite pkgLite = null;
13616
13617            if (onInt && onSd) {
13618                // Check if both bits are set.
13619                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13620                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13621            } else if (onSd && ephemeral) {
13622                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13623                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13624            } else {
13625                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13626                        packageAbiOverride);
13627
13628                if (DEBUG_EPHEMERAL && ephemeral) {
13629                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13630                }
13631
13632                /*
13633                 * If we have too little free space, try to free cache
13634                 * before giving up.
13635                 */
13636                if (!origin.staged && pkgLite.recommendedInstallLocation
13637                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13638                    // TODO: focus freeing disk space on the target device
13639                    final StorageManager storage = StorageManager.from(mContext);
13640                    final long lowThreshold = storage.getStorageLowBytes(
13641                            Environment.getDataDirectory());
13642
13643                    final long sizeBytes = mContainerService.calculateInstalledSize(
13644                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13645
13646                    try {
13647                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13648                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13649                                installFlags, packageAbiOverride);
13650                    } catch (InstallerException e) {
13651                        Slog.w(TAG, "Failed to free cache", e);
13652                    }
13653
13654                    /*
13655                     * The cache free must have deleted the file we
13656                     * downloaded to install.
13657                     *
13658                     * TODO: fix the "freeCache" call to not delete
13659                     *       the file we care about.
13660                     */
13661                    if (pkgLite.recommendedInstallLocation
13662                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13663                        pkgLite.recommendedInstallLocation
13664                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13665                    }
13666                }
13667            }
13668
13669            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13670                int loc = pkgLite.recommendedInstallLocation;
13671                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13672                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13673                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13674                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13675                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13676                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13677                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13678                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13679                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13680                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13681                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13682                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13683                } else {
13684                    // Override with defaults if needed.
13685                    loc = installLocationPolicy(pkgLite);
13686                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13687                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13688                    } else if (!onSd && !onInt) {
13689                        // Override install location with flags
13690                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13691                            // Set the flag to install on external media.
13692                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13693                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13694                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13695                            if (DEBUG_EPHEMERAL) {
13696                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13697                            }
13698                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13699                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13700                                    |PackageManager.INSTALL_INTERNAL);
13701                        } else {
13702                            // Make sure the flag for installing on external
13703                            // media is unset
13704                            installFlags |= PackageManager.INSTALL_INTERNAL;
13705                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13706                        }
13707                    }
13708                }
13709            }
13710
13711            final InstallArgs args = createInstallArgs(this);
13712            mArgs = args;
13713
13714            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13715                // TODO: http://b/22976637
13716                // Apps installed for "all" users use the device owner to verify the app
13717                UserHandle verifierUser = getUser();
13718                if (verifierUser == UserHandle.ALL) {
13719                    verifierUser = UserHandle.SYSTEM;
13720                }
13721
13722                /*
13723                 * Determine if we have any installed package verifiers. If we
13724                 * do, then we'll defer to them to verify the packages.
13725                 */
13726                final int requiredUid = mRequiredVerifierPackage == null ? -1
13727                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13728                                verifierUser.getIdentifier());
13729                if (!origin.existing && requiredUid != -1
13730                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13731                    final Intent verification = new Intent(
13732                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13733                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13734                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13735                            PACKAGE_MIME_TYPE);
13736                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13737
13738                    // Query all live verifiers based on current user state
13739                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13740                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13741
13742                    if (DEBUG_VERIFY) {
13743                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13744                                + verification.toString() + " with " + pkgLite.verifiers.length
13745                                + " optional verifiers");
13746                    }
13747
13748                    final int verificationId = mPendingVerificationToken++;
13749
13750                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13751
13752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13753                            installerPackageName);
13754
13755                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13756                            installFlags);
13757
13758                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13759                            pkgLite.packageName);
13760
13761                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13762                            pkgLite.versionCode);
13763
13764                    if (verificationInfo != null) {
13765                        if (verificationInfo.originatingUri != null) {
13766                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13767                                    verificationInfo.originatingUri);
13768                        }
13769                        if (verificationInfo.referrer != null) {
13770                            verification.putExtra(Intent.EXTRA_REFERRER,
13771                                    verificationInfo.referrer);
13772                        }
13773                        if (verificationInfo.originatingUid >= 0) {
13774                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13775                                    verificationInfo.originatingUid);
13776                        }
13777                        if (verificationInfo.installerUid >= 0) {
13778                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13779                                    verificationInfo.installerUid);
13780                        }
13781                    }
13782
13783                    final PackageVerificationState verificationState = new PackageVerificationState(
13784                            requiredUid, args);
13785
13786                    mPendingVerification.append(verificationId, verificationState);
13787
13788                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13789                            receivers, verificationState);
13790
13791                    /*
13792                     * If any sufficient verifiers were listed in the package
13793                     * manifest, attempt to ask them.
13794                     */
13795                    if (sufficientVerifiers != null) {
13796                        final int N = sufficientVerifiers.size();
13797                        if (N == 0) {
13798                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13799                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13800                        } else {
13801                            for (int i = 0; i < N; i++) {
13802                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13803
13804                                final Intent sufficientIntent = new Intent(verification);
13805                                sufficientIntent.setComponent(verifierComponent);
13806                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13807                            }
13808                        }
13809                    }
13810
13811                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13812                            mRequiredVerifierPackage, receivers);
13813                    if (ret == PackageManager.INSTALL_SUCCEEDED
13814                            && mRequiredVerifierPackage != null) {
13815                        Trace.asyncTraceBegin(
13816                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13817                        /*
13818                         * Send the intent to the required verification agent,
13819                         * but only start the verification timeout after the
13820                         * target BroadcastReceivers have run.
13821                         */
13822                        verification.setComponent(requiredVerifierComponent);
13823                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13824                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13825                                new BroadcastReceiver() {
13826                                    @Override
13827                                    public void onReceive(Context context, Intent intent) {
13828                                        final Message msg = mHandler
13829                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13830                                        msg.arg1 = verificationId;
13831                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13832                                    }
13833                                }, null, 0, null, null);
13834
13835                        /*
13836                         * We don't want the copy to proceed until verification
13837                         * succeeds, so null out this field.
13838                         */
13839                        mArgs = null;
13840                    }
13841                } else {
13842                    /*
13843                     * No package verification is enabled, so immediately start
13844                     * the remote call to initiate copy using temporary file.
13845                     */
13846                    ret = args.copyApk(mContainerService, true);
13847                }
13848            }
13849
13850            mRet = ret;
13851        }
13852
13853        @Override
13854        void handleReturnCode() {
13855            // If mArgs is null, then MCS couldn't be reached. When it
13856            // reconnects, it will try again to install. At that point, this
13857            // will succeed.
13858            if (mArgs != null) {
13859                processPendingInstall(mArgs, mRet);
13860            }
13861        }
13862
13863        @Override
13864        void handleServiceError() {
13865            mArgs = createInstallArgs(this);
13866            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13867        }
13868
13869        public boolean isForwardLocked() {
13870            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13871        }
13872    }
13873
13874    /**
13875     * Used during creation of InstallArgs
13876     *
13877     * @param installFlags package installation flags
13878     * @return true if should be installed on external storage
13879     */
13880    private static boolean installOnExternalAsec(int installFlags) {
13881        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13882            return false;
13883        }
13884        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13885            return true;
13886        }
13887        return false;
13888    }
13889
13890    /**
13891     * Used during creation of InstallArgs
13892     *
13893     * @param installFlags package installation flags
13894     * @return true if should be installed as forward locked
13895     */
13896    private static boolean installForwardLocked(int installFlags) {
13897        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13898    }
13899
13900    private InstallArgs createInstallArgs(InstallParams params) {
13901        if (params.move != null) {
13902            return new MoveInstallArgs(params);
13903        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13904            return new AsecInstallArgs(params);
13905        } else {
13906            return new FileInstallArgs(params);
13907        }
13908    }
13909
13910    /**
13911     * Create args that describe an existing installed package. Typically used
13912     * when cleaning up old installs, or used as a move source.
13913     */
13914    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13915            String resourcePath, String[] instructionSets) {
13916        final boolean isInAsec;
13917        if (installOnExternalAsec(installFlags)) {
13918            /* Apps on SD card are always in ASEC containers. */
13919            isInAsec = true;
13920        } else if (installForwardLocked(installFlags)
13921                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13922            /*
13923             * Forward-locked apps are only in ASEC containers if they're the
13924             * new style
13925             */
13926            isInAsec = true;
13927        } else {
13928            isInAsec = false;
13929        }
13930
13931        if (isInAsec) {
13932            return new AsecInstallArgs(codePath, instructionSets,
13933                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13934        } else {
13935            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13936        }
13937    }
13938
13939    static abstract class InstallArgs {
13940        /** @see InstallParams#origin */
13941        final OriginInfo origin;
13942        /** @see InstallParams#move */
13943        final MoveInfo move;
13944
13945        final IPackageInstallObserver2 observer;
13946        // Always refers to PackageManager flags only
13947        final int installFlags;
13948        final String installerPackageName;
13949        final String volumeUuid;
13950        final UserHandle user;
13951        final String abiOverride;
13952        final String[] installGrantPermissions;
13953        /** If non-null, drop an async trace when the install completes */
13954        final String traceMethod;
13955        final int traceCookie;
13956        final Certificate[][] certificates;
13957        final int installReason;
13958
13959        // The list of instruction sets supported by this app. This is currently
13960        // only used during the rmdex() phase to clean up resources. We can get rid of this
13961        // if we move dex files under the common app path.
13962        /* nullable */ String[] instructionSets;
13963
13964        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13965                int installFlags, String installerPackageName, String volumeUuid,
13966                UserHandle user, String[] instructionSets,
13967                String abiOverride, String[] installGrantPermissions,
13968                String traceMethod, int traceCookie, Certificate[][] certificates,
13969                int installReason) {
13970            this.origin = origin;
13971            this.move = move;
13972            this.installFlags = installFlags;
13973            this.observer = observer;
13974            this.installerPackageName = installerPackageName;
13975            this.volumeUuid = volumeUuid;
13976            this.user = user;
13977            this.instructionSets = instructionSets;
13978            this.abiOverride = abiOverride;
13979            this.installGrantPermissions = installGrantPermissions;
13980            this.traceMethod = traceMethod;
13981            this.traceCookie = traceCookie;
13982            this.certificates = certificates;
13983            this.installReason = installReason;
13984        }
13985
13986        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13987        abstract int doPreInstall(int status);
13988
13989        /**
13990         * Rename package into final resting place. All paths on the given
13991         * scanned package should be updated to reflect the rename.
13992         */
13993        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13994        abstract int doPostInstall(int status, int uid);
13995
13996        /** @see PackageSettingBase#codePathString */
13997        abstract String getCodePath();
13998        /** @see PackageSettingBase#resourcePathString */
13999        abstract String getResourcePath();
14000
14001        // Need installer lock especially for dex file removal.
14002        abstract void cleanUpResourcesLI();
14003        abstract boolean doPostDeleteLI(boolean delete);
14004
14005        /**
14006         * Called before the source arguments are copied. This is used mostly
14007         * for MoveParams when it needs to read the source file to put it in the
14008         * destination.
14009         */
14010        int doPreCopy() {
14011            return PackageManager.INSTALL_SUCCEEDED;
14012        }
14013
14014        /**
14015         * Called after the source arguments are copied. This is used mostly for
14016         * MoveParams when it needs to read the source file to put it in the
14017         * destination.
14018         */
14019        int doPostCopy(int uid) {
14020            return PackageManager.INSTALL_SUCCEEDED;
14021        }
14022
14023        protected boolean isFwdLocked() {
14024            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14025        }
14026
14027        protected boolean isExternalAsec() {
14028            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14029        }
14030
14031        protected boolean isEphemeral() {
14032            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14033        }
14034
14035        UserHandle getUser() {
14036            return user;
14037        }
14038    }
14039
14040    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14041        if (!allCodePaths.isEmpty()) {
14042            if (instructionSets == null) {
14043                throw new IllegalStateException("instructionSet == null");
14044            }
14045            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14046            for (String codePath : allCodePaths) {
14047                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14048                    try {
14049                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14050                    } catch (InstallerException ignored) {
14051                    }
14052                }
14053            }
14054        }
14055    }
14056
14057    /**
14058     * Logic to handle installation of non-ASEC applications, including copying
14059     * and renaming logic.
14060     */
14061    class FileInstallArgs extends InstallArgs {
14062        private File codeFile;
14063        private File resourceFile;
14064
14065        // Example topology:
14066        // /data/app/com.example/base.apk
14067        // /data/app/com.example/split_foo.apk
14068        // /data/app/com.example/lib/arm/libfoo.so
14069        // /data/app/com.example/lib/arm64/libfoo.so
14070        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14071
14072        /** New install */
14073        FileInstallArgs(InstallParams params) {
14074            super(params.origin, params.move, params.observer, params.installFlags,
14075                    params.installerPackageName, params.volumeUuid,
14076                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14077                    params.grantedRuntimePermissions,
14078                    params.traceMethod, params.traceCookie, params.certificates,
14079                    params.installReason);
14080            if (isFwdLocked()) {
14081                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14082            }
14083        }
14084
14085        /** Existing install */
14086        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14087            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14088                    null, null, null, 0, null /*certificates*/,
14089                    PackageManager.INSTALL_REASON_UNKNOWN);
14090            this.codeFile = (codePath != null) ? new File(codePath) : null;
14091            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14092        }
14093
14094        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14095            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14096            try {
14097                return doCopyApk(imcs, temp);
14098            } finally {
14099                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14100            }
14101        }
14102
14103        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14104            if (origin.staged) {
14105                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14106                codeFile = origin.file;
14107                resourceFile = origin.file;
14108                return PackageManager.INSTALL_SUCCEEDED;
14109            }
14110
14111            try {
14112                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14113                final File tempDir =
14114                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14115                codeFile = tempDir;
14116                resourceFile = tempDir;
14117            } catch (IOException e) {
14118                Slog.w(TAG, "Failed to create copy file: " + e);
14119                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14120            }
14121
14122            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14123                @Override
14124                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14125                    if (!FileUtils.isValidExtFilename(name)) {
14126                        throw new IllegalArgumentException("Invalid filename: " + name);
14127                    }
14128                    try {
14129                        final File file = new File(codeFile, name);
14130                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14131                                O_RDWR | O_CREAT, 0644);
14132                        Os.chmod(file.getAbsolutePath(), 0644);
14133                        return new ParcelFileDescriptor(fd);
14134                    } catch (ErrnoException e) {
14135                        throw new RemoteException("Failed to open: " + e.getMessage());
14136                    }
14137                }
14138            };
14139
14140            int ret = PackageManager.INSTALL_SUCCEEDED;
14141            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14142            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14143                Slog.e(TAG, "Failed to copy package");
14144                return ret;
14145            }
14146
14147            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14148            NativeLibraryHelper.Handle handle = null;
14149            try {
14150                handle = NativeLibraryHelper.Handle.create(codeFile);
14151                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14152                        abiOverride);
14153            } catch (IOException e) {
14154                Slog.e(TAG, "Copying native libraries failed", e);
14155                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14156            } finally {
14157                IoUtils.closeQuietly(handle);
14158            }
14159
14160            return ret;
14161        }
14162
14163        int doPreInstall(int status) {
14164            if (status != PackageManager.INSTALL_SUCCEEDED) {
14165                cleanUp();
14166            }
14167            return status;
14168        }
14169
14170        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14171            if (status != PackageManager.INSTALL_SUCCEEDED) {
14172                cleanUp();
14173                return false;
14174            }
14175
14176            final File targetDir = codeFile.getParentFile();
14177            final File beforeCodeFile = codeFile;
14178            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14179
14180            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14181            try {
14182                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14183            } catch (ErrnoException e) {
14184                Slog.w(TAG, "Failed to rename", e);
14185                return false;
14186            }
14187
14188            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14189                Slog.w(TAG, "Failed to restorecon");
14190                return false;
14191            }
14192
14193            // Reflect the rename internally
14194            codeFile = afterCodeFile;
14195            resourceFile = afterCodeFile;
14196
14197            // Reflect the rename in scanned details
14198            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14199            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14200                    afterCodeFile, pkg.baseCodePath));
14201            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14202                    afterCodeFile, pkg.splitCodePaths));
14203
14204            // Reflect the rename in app info
14205            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14206            pkg.setApplicationInfoCodePath(pkg.codePath);
14207            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14208            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14209            pkg.setApplicationInfoResourcePath(pkg.codePath);
14210            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14211            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14212
14213            return true;
14214        }
14215
14216        int doPostInstall(int status, int uid) {
14217            if (status != PackageManager.INSTALL_SUCCEEDED) {
14218                cleanUp();
14219            }
14220            return status;
14221        }
14222
14223        @Override
14224        String getCodePath() {
14225            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14226        }
14227
14228        @Override
14229        String getResourcePath() {
14230            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14231        }
14232
14233        private boolean cleanUp() {
14234            if (codeFile == null || !codeFile.exists()) {
14235                return false;
14236            }
14237
14238            removeCodePathLI(codeFile);
14239
14240            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14241                resourceFile.delete();
14242            }
14243
14244            return true;
14245        }
14246
14247        void cleanUpResourcesLI() {
14248            // Try enumerating all code paths before deleting
14249            List<String> allCodePaths = Collections.EMPTY_LIST;
14250            if (codeFile != null && codeFile.exists()) {
14251                try {
14252                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14253                    allCodePaths = pkg.getAllCodePaths();
14254                } catch (PackageParserException e) {
14255                    // Ignored; we tried our best
14256                }
14257            }
14258
14259            cleanUp();
14260            removeDexFiles(allCodePaths, instructionSets);
14261        }
14262
14263        boolean doPostDeleteLI(boolean delete) {
14264            // XXX err, shouldn't we respect the delete flag?
14265            cleanUpResourcesLI();
14266            return true;
14267        }
14268    }
14269
14270    private boolean isAsecExternal(String cid) {
14271        final String asecPath = PackageHelper.getSdFilesystem(cid);
14272        return !asecPath.startsWith(mAsecInternalPath);
14273    }
14274
14275    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14276            PackageManagerException {
14277        if (copyRet < 0) {
14278            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14279                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14280                throw new PackageManagerException(copyRet, message);
14281            }
14282        }
14283    }
14284
14285    /**
14286     * Extract the StorageManagerService "container ID" from the full code path of an
14287     * .apk.
14288     */
14289    static String cidFromCodePath(String fullCodePath) {
14290        int eidx = fullCodePath.lastIndexOf("/");
14291        String subStr1 = fullCodePath.substring(0, eidx);
14292        int sidx = subStr1.lastIndexOf("/");
14293        return subStr1.substring(sidx+1, eidx);
14294    }
14295
14296    /**
14297     * Logic to handle installation of ASEC applications, including copying and
14298     * renaming logic.
14299     */
14300    class AsecInstallArgs extends InstallArgs {
14301        static final String RES_FILE_NAME = "pkg.apk";
14302        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14303
14304        String cid;
14305        String packagePath;
14306        String resourcePath;
14307
14308        /** New install */
14309        AsecInstallArgs(InstallParams params) {
14310            super(params.origin, params.move, params.observer, params.installFlags,
14311                    params.installerPackageName, params.volumeUuid,
14312                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14313                    params.grantedRuntimePermissions,
14314                    params.traceMethod, params.traceCookie, params.certificates,
14315                    params.installReason);
14316        }
14317
14318        /** Existing install */
14319        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14320                        boolean isExternal, boolean isForwardLocked) {
14321            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14322                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14323                    instructionSets, null, null, null, 0, null /*certificates*/,
14324                    PackageManager.INSTALL_REASON_UNKNOWN);
14325            // Hackily pretend we're still looking at a full code path
14326            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14327                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14328            }
14329
14330            // Extract cid from fullCodePath
14331            int eidx = fullCodePath.lastIndexOf("/");
14332            String subStr1 = fullCodePath.substring(0, eidx);
14333            int sidx = subStr1.lastIndexOf("/");
14334            cid = subStr1.substring(sidx+1, eidx);
14335            setMountPath(subStr1);
14336        }
14337
14338        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14339            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14340                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14341                    instructionSets, null, null, null, 0, null /*certificates*/,
14342                    PackageManager.INSTALL_REASON_UNKNOWN);
14343            this.cid = cid;
14344            setMountPath(PackageHelper.getSdDir(cid));
14345        }
14346
14347        void createCopyFile() {
14348            cid = mInstallerService.allocateExternalStageCidLegacy();
14349        }
14350
14351        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14352            if (origin.staged && origin.cid != null) {
14353                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14354                cid = origin.cid;
14355                setMountPath(PackageHelper.getSdDir(cid));
14356                return PackageManager.INSTALL_SUCCEEDED;
14357            }
14358
14359            if (temp) {
14360                createCopyFile();
14361            } else {
14362                /*
14363                 * Pre-emptively destroy the container since it's destroyed if
14364                 * copying fails due to it existing anyway.
14365                 */
14366                PackageHelper.destroySdDir(cid);
14367            }
14368
14369            final String newMountPath = imcs.copyPackageToContainer(
14370                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14371                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14372
14373            if (newMountPath != null) {
14374                setMountPath(newMountPath);
14375                return PackageManager.INSTALL_SUCCEEDED;
14376            } else {
14377                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14378            }
14379        }
14380
14381        @Override
14382        String getCodePath() {
14383            return packagePath;
14384        }
14385
14386        @Override
14387        String getResourcePath() {
14388            return resourcePath;
14389        }
14390
14391        int doPreInstall(int status) {
14392            if (status != PackageManager.INSTALL_SUCCEEDED) {
14393                // Destroy container
14394                PackageHelper.destroySdDir(cid);
14395            } else {
14396                boolean mounted = PackageHelper.isContainerMounted(cid);
14397                if (!mounted) {
14398                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14399                            Process.SYSTEM_UID);
14400                    if (newMountPath != null) {
14401                        setMountPath(newMountPath);
14402                    } else {
14403                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14404                    }
14405                }
14406            }
14407            return status;
14408        }
14409
14410        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14411            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14412            String newMountPath = null;
14413            if (PackageHelper.isContainerMounted(cid)) {
14414                // Unmount the container
14415                if (!PackageHelper.unMountSdDir(cid)) {
14416                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14417                    return false;
14418                }
14419            }
14420            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14421                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14422                        " which might be stale. Will try to clean up.");
14423                // Clean up the stale container and proceed to recreate.
14424                if (!PackageHelper.destroySdDir(newCacheId)) {
14425                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14426                    return false;
14427                }
14428                // Successfully cleaned up stale container. Try to rename again.
14429                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14430                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14431                            + " inspite of cleaning it up.");
14432                    return false;
14433                }
14434            }
14435            if (!PackageHelper.isContainerMounted(newCacheId)) {
14436                Slog.w(TAG, "Mounting container " + newCacheId);
14437                newMountPath = PackageHelper.mountSdDir(newCacheId,
14438                        getEncryptKey(), Process.SYSTEM_UID);
14439            } else {
14440                newMountPath = PackageHelper.getSdDir(newCacheId);
14441            }
14442            if (newMountPath == null) {
14443                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14444                return false;
14445            }
14446            Log.i(TAG, "Succesfully renamed " + cid +
14447                    " to " + newCacheId +
14448                    " at new path: " + newMountPath);
14449            cid = newCacheId;
14450
14451            final File beforeCodeFile = new File(packagePath);
14452            setMountPath(newMountPath);
14453            final File afterCodeFile = new File(packagePath);
14454
14455            // Reflect the rename in scanned details
14456            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14457            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14458                    afterCodeFile, pkg.baseCodePath));
14459            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14460                    afterCodeFile, pkg.splitCodePaths));
14461
14462            // Reflect the rename in app info
14463            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14464            pkg.setApplicationInfoCodePath(pkg.codePath);
14465            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14466            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14467            pkg.setApplicationInfoResourcePath(pkg.codePath);
14468            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14469            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14470
14471            return true;
14472        }
14473
14474        private void setMountPath(String mountPath) {
14475            final File mountFile = new File(mountPath);
14476
14477            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14478            if (monolithicFile.exists()) {
14479                packagePath = monolithicFile.getAbsolutePath();
14480                if (isFwdLocked()) {
14481                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14482                } else {
14483                    resourcePath = packagePath;
14484                }
14485            } else {
14486                packagePath = mountFile.getAbsolutePath();
14487                resourcePath = packagePath;
14488            }
14489        }
14490
14491        int doPostInstall(int status, int uid) {
14492            if (status != PackageManager.INSTALL_SUCCEEDED) {
14493                cleanUp();
14494            } else {
14495                final int groupOwner;
14496                final String protectedFile;
14497                if (isFwdLocked()) {
14498                    groupOwner = UserHandle.getSharedAppGid(uid);
14499                    protectedFile = RES_FILE_NAME;
14500                } else {
14501                    groupOwner = -1;
14502                    protectedFile = null;
14503                }
14504
14505                if (uid < Process.FIRST_APPLICATION_UID
14506                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14507                    Slog.e(TAG, "Failed to finalize " + cid);
14508                    PackageHelper.destroySdDir(cid);
14509                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14510                }
14511
14512                boolean mounted = PackageHelper.isContainerMounted(cid);
14513                if (!mounted) {
14514                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14515                }
14516            }
14517            return status;
14518        }
14519
14520        private void cleanUp() {
14521            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14522
14523            // Destroy secure container
14524            PackageHelper.destroySdDir(cid);
14525        }
14526
14527        private List<String> getAllCodePaths() {
14528            final File codeFile = new File(getCodePath());
14529            if (codeFile != null && codeFile.exists()) {
14530                try {
14531                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14532                    return pkg.getAllCodePaths();
14533                } catch (PackageParserException e) {
14534                    // Ignored; we tried our best
14535                }
14536            }
14537            return Collections.EMPTY_LIST;
14538        }
14539
14540        void cleanUpResourcesLI() {
14541            // Enumerate all code paths before deleting
14542            cleanUpResourcesLI(getAllCodePaths());
14543        }
14544
14545        private void cleanUpResourcesLI(List<String> allCodePaths) {
14546            cleanUp();
14547            removeDexFiles(allCodePaths, instructionSets);
14548        }
14549
14550        String getPackageName() {
14551            return getAsecPackageName(cid);
14552        }
14553
14554        boolean doPostDeleteLI(boolean delete) {
14555            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14556            final List<String> allCodePaths = getAllCodePaths();
14557            boolean mounted = PackageHelper.isContainerMounted(cid);
14558            if (mounted) {
14559                // Unmount first
14560                if (PackageHelper.unMountSdDir(cid)) {
14561                    mounted = false;
14562                }
14563            }
14564            if (!mounted && delete) {
14565                cleanUpResourcesLI(allCodePaths);
14566            }
14567            return !mounted;
14568        }
14569
14570        @Override
14571        int doPreCopy() {
14572            if (isFwdLocked()) {
14573                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14574                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14575                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14576                }
14577            }
14578
14579            return PackageManager.INSTALL_SUCCEEDED;
14580        }
14581
14582        @Override
14583        int doPostCopy(int uid) {
14584            if (isFwdLocked()) {
14585                if (uid < Process.FIRST_APPLICATION_UID
14586                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14587                                RES_FILE_NAME)) {
14588                    Slog.e(TAG, "Failed to finalize " + cid);
14589                    PackageHelper.destroySdDir(cid);
14590                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14591                }
14592            }
14593
14594            return PackageManager.INSTALL_SUCCEEDED;
14595        }
14596    }
14597
14598    /**
14599     * Logic to handle movement of existing installed applications.
14600     */
14601    class MoveInstallArgs extends InstallArgs {
14602        private File codeFile;
14603        private File resourceFile;
14604
14605        /** New install */
14606        MoveInstallArgs(InstallParams params) {
14607            super(params.origin, params.move, params.observer, params.installFlags,
14608                    params.installerPackageName, params.volumeUuid,
14609                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14610                    params.grantedRuntimePermissions,
14611                    params.traceMethod, params.traceCookie, params.certificates,
14612                    params.installReason);
14613        }
14614
14615        int copyApk(IMediaContainerService imcs, boolean temp) {
14616            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14617                    + move.fromUuid + " to " + move.toUuid);
14618            synchronized (mInstaller) {
14619                try {
14620                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14621                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14622                } catch (InstallerException e) {
14623                    Slog.w(TAG, "Failed to move app", e);
14624                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14625                }
14626            }
14627
14628            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14629            resourceFile = codeFile;
14630            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14631
14632            return PackageManager.INSTALL_SUCCEEDED;
14633        }
14634
14635        int doPreInstall(int status) {
14636            if (status != PackageManager.INSTALL_SUCCEEDED) {
14637                cleanUp(move.toUuid);
14638            }
14639            return status;
14640        }
14641
14642        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14643            if (status != PackageManager.INSTALL_SUCCEEDED) {
14644                cleanUp(move.toUuid);
14645                return false;
14646            }
14647
14648            // Reflect the move in app info
14649            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14650            pkg.setApplicationInfoCodePath(pkg.codePath);
14651            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14652            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14653            pkg.setApplicationInfoResourcePath(pkg.codePath);
14654            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14655            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14656
14657            return true;
14658        }
14659
14660        int doPostInstall(int status, int uid) {
14661            if (status == PackageManager.INSTALL_SUCCEEDED) {
14662                cleanUp(move.fromUuid);
14663            } else {
14664                cleanUp(move.toUuid);
14665            }
14666            return status;
14667        }
14668
14669        @Override
14670        String getCodePath() {
14671            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14672        }
14673
14674        @Override
14675        String getResourcePath() {
14676            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14677        }
14678
14679        private boolean cleanUp(String volumeUuid) {
14680            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14681                    move.dataAppName);
14682            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14683            final int[] userIds = sUserManager.getUserIds();
14684            synchronized (mInstallLock) {
14685                // Clean up both app data and code
14686                // All package moves are frozen until finished
14687                for (int userId : userIds) {
14688                    try {
14689                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14690                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14691                    } catch (InstallerException e) {
14692                        Slog.w(TAG, String.valueOf(e));
14693                    }
14694                }
14695                removeCodePathLI(codeFile);
14696            }
14697            return true;
14698        }
14699
14700        void cleanUpResourcesLI() {
14701            throw new UnsupportedOperationException();
14702        }
14703
14704        boolean doPostDeleteLI(boolean delete) {
14705            throw new UnsupportedOperationException();
14706        }
14707    }
14708
14709    static String getAsecPackageName(String packageCid) {
14710        int idx = packageCid.lastIndexOf("-");
14711        if (idx == -1) {
14712            return packageCid;
14713        }
14714        return packageCid.substring(0, idx);
14715    }
14716
14717    // Utility method used to create code paths based on package name and available index.
14718    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14719        String idxStr = "";
14720        int idx = 1;
14721        // Fall back to default value of idx=1 if prefix is not
14722        // part of oldCodePath
14723        if (oldCodePath != null) {
14724            String subStr = oldCodePath;
14725            // Drop the suffix right away
14726            if (suffix != null && subStr.endsWith(suffix)) {
14727                subStr = subStr.substring(0, subStr.length() - suffix.length());
14728            }
14729            // If oldCodePath already contains prefix find out the
14730            // ending index to either increment or decrement.
14731            int sidx = subStr.lastIndexOf(prefix);
14732            if (sidx != -1) {
14733                subStr = subStr.substring(sidx + prefix.length());
14734                if (subStr != null) {
14735                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14736                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14737                    }
14738                    try {
14739                        idx = Integer.parseInt(subStr);
14740                        if (idx <= 1) {
14741                            idx++;
14742                        } else {
14743                            idx--;
14744                        }
14745                    } catch(NumberFormatException e) {
14746                    }
14747                }
14748            }
14749        }
14750        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14751        return prefix + idxStr;
14752    }
14753
14754    private File getNextCodePath(File targetDir, String packageName) {
14755        File result;
14756        SecureRandom random = new SecureRandom();
14757        byte[] bytes = new byte[16];
14758        do {
14759            random.nextBytes(bytes);
14760            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14761            result = new File(targetDir, packageName + "-" + suffix);
14762        } while (result.exists());
14763        return result;
14764    }
14765
14766    // Utility method that returns the relative package path with respect
14767    // to the installation directory. Like say for /data/data/com.test-1.apk
14768    // string com.test-1 is returned.
14769    static String deriveCodePathName(String codePath) {
14770        if (codePath == null) {
14771            return null;
14772        }
14773        final File codeFile = new File(codePath);
14774        final String name = codeFile.getName();
14775        if (codeFile.isDirectory()) {
14776            return name;
14777        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14778            final int lastDot = name.lastIndexOf('.');
14779            return name.substring(0, lastDot);
14780        } else {
14781            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14782            return null;
14783        }
14784    }
14785
14786    static class PackageInstalledInfo {
14787        String name;
14788        int uid;
14789        // The set of users that originally had this package installed.
14790        int[] origUsers;
14791        // The set of users that now have this package installed.
14792        int[] newUsers;
14793        PackageParser.Package pkg;
14794        int returnCode;
14795        String returnMsg;
14796        PackageRemovedInfo removedInfo;
14797        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14798
14799        public void setError(int code, String msg) {
14800            setReturnCode(code);
14801            setReturnMessage(msg);
14802            Slog.w(TAG, msg);
14803        }
14804
14805        public void setError(String msg, PackageParserException e) {
14806            setReturnCode(e.error);
14807            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14808            Slog.w(TAG, msg, e);
14809        }
14810
14811        public void setError(String msg, PackageManagerException e) {
14812            returnCode = e.error;
14813            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14814            Slog.w(TAG, msg, e);
14815        }
14816
14817        public void setReturnCode(int returnCode) {
14818            this.returnCode = returnCode;
14819            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14820            for (int i = 0; i < childCount; i++) {
14821                addedChildPackages.valueAt(i).returnCode = returnCode;
14822            }
14823        }
14824
14825        private void setReturnMessage(String returnMsg) {
14826            this.returnMsg = returnMsg;
14827            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14828            for (int i = 0; i < childCount; i++) {
14829                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14830            }
14831        }
14832
14833        // In some error cases we want to convey more info back to the observer
14834        String origPackage;
14835        String origPermission;
14836    }
14837
14838    /*
14839     * Install a non-existing package.
14840     */
14841    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14842            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14843            PackageInstalledInfo res, int installReason) {
14844        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14845
14846        // Remember this for later, in case we need to rollback this install
14847        String pkgName = pkg.packageName;
14848
14849        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14850
14851        synchronized(mPackages) {
14852            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14853            if (renamedPackage != null) {
14854                // A package with the same name is already installed, though
14855                // it has been renamed to an older name.  The package we
14856                // are trying to install should be installed as an update to
14857                // the existing one, but that has not been requested, so bail.
14858                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14859                        + " without first uninstalling package running as "
14860                        + renamedPackage);
14861                return;
14862            }
14863            if (mPackages.containsKey(pkgName)) {
14864                // Don't allow installation over an existing package with the same name.
14865                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14866                        + " without first uninstalling.");
14867                return;
14868            }
14869        }
14870
14871        try {
14872            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14873                    System.currentTimeMillis(), user);
14874
14875            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
14876
14877            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14878                prepareAppDataAfterInstallLIF(newPackage);
14879
14880            } else {
14881                // Remove package from internal structures, but keep around any
14882                // data that might have already existed
14883                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14884                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14885            }
14886        } catch (PackageManagerException e) {
14887            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14888        }
14889
14890        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14891    }
14892
14893    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14894        // Can't rotate keys during boot or if sharedUser.
14895        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14896                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14897            return false;
14898        }
14899        // app is using upgradeKeySets; make sure all are valid
14900        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14901        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14902        for (int i = 0; i < upgradeKeySets.length; i++) {
14903            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14904                Slog.wtf(TAG, "Package "
14905                         + (oldPs.name != null ? oldPs.name : "<null>")
14906                         + " contains upgrade-key-set reference to unknown key-set: "
14907                         + upgradeKeySets[i]
14908                         + " reverting to signatures check.");
14909                return false;
14910            }
14911        }
14912        return true;
14913    }
14914
14915    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14916        // Upgrade keysets are being used.  Determine if new package has a superset of the
14917        // required keys.
14918        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14919        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14920        for (int i = 0; i < upgradeKeySets.length; i++) {
14921            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14922            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14923                return true;
14924            }
14925        }
14926        return false;
14927    }
14928
14929    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14930        try (DigestInputStream digestStream =
14931                new DigestInputStream(new FileInputStream(file), digest)) {
14932            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14933        }
14934    }
14935
14936    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14937            UserHandle user, String installerPackageName, PackageInstalledInfo res,
14938            int installReason) {
14939        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14940
14941        final PackageParser.Package oldPackage;
14942        final String pkgName = pkg.packageName;
14943        final int[] allUsers;
14944        final int[] installedUsers;
14945
14946        synchronized(mPackages) {
14947            oldPackage = mPackages.get(pkgName);
14948            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14949
14950            // don't allow upgrade to target a release SDK from a pre-release SDK
14951            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14952                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14953            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14954                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14955            if (oldTargetsPreRelease
14956                    && !newTargetsPreRelease
14957                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14958                Slog.w(TAG, "Can't install package targeting released sdk");
14959                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14960                return;
14961            }
14962
14963            // don't allow an upgrade from full to ephemeral
14964            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14965            if (isEphemeral && !oldIsEphemeral) {
14966                // can't downgrade from full to ephemeral
14967                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14968                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14969                return;
14970            }
14971
14972            // verify signatures are valid
14973            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14974            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14975                if (!checkUpgradeKeySetLP(ps, pkg)) {
14976                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14977                            "New package not signed by keys specified by upgrade-keysets: "
14978                                    + pkgName);
14979                    return;
14980                }
14981            } else {
14982                // default to original signature matching
14983                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14984                        != PackageManager.SIGNATURE_MATCH) {
14985                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14986                            "New package has a different signature: " + pkgName);
14987                    return;
14988                }
14989            }
14990
14991            // don't allow a system upgrade unless the upgrade hash matches
14992            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14993                byte[] digestBytes = null;
14994                try {
14995                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14996                    updateDigest(digest, new File(pkg.baseCodePath));
14997                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14998                        for (String path : pkg.splitCodePaths) {
14999                            updateDigest(digest, new File(path));
15000                        }
15001                    }
15002                    digestBytes = digest.digest();
15003                } catch (NoSuchAlgorithmException | IOException e) {
15004                    res.setError(INSTALL_FAILED_INVALID_APK,
15005                            "Could not compute hash: " + pkgName);
15006                    return;
15007                }
15008                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15009                    res.setError(INSTALL_FAILED_INVALID_APK,
15010                            "New package fails restrict-update check: " + pkgName);
15011                    return;
15012                }
15013                // retain upgrade restriction
15014                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15015            }
15016
15017            // Check for shared user id changes
15018            String invalidPackageName =
15019                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15020            if (invalidPackageName != null) {
15021                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15022                        "Package " + invalidPackageName + " tried to change user "
15023                                + oldPackage.mSharedUserId);
15024                return;
15025            }
15026
15027            // In case of rollback, remember per-user/profile install state
15028            allUsers = sUserManager.getUserIds();
15029            installedUsers = ps.queryInstalledUsers(allUsers, true);
15030        }
15031
15032        // Update what is removed
15033        res.removedInfo = new PackageRemovedInfo();
15034        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15035        res.removedInfo.removedPackage = oldPackage.packageName;
15036        res.removedInfo.isUpdate = true;
15037        res.removedInfo.origUsers = installedUsers;
15038        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15039        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15040        for (int i = 0; i < installedUsers.length; i++) {
15041            final int userId = installedUsers[i];
15042            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15043        }
15044
15045        final int childCount = (oldPackage.childPackages != null)
15046                ? oldPackage.childPackages.size() : 0;
15047        for (int i = 0; i < childCount; i++) {
15048            boolean childPackageUpdated = false;
15049            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15050            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15051            if (res.addedChildPackages != null) {
15052                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15053                if (childRes != null) {
15054                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15055                    childRes.removedInfo.removedPackage = childPkg.packageName;
15056                    childRes.removedInfo.isUpdate = true;
15057                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15058                    childPackageUpdated = true;
15059                }
15060            }
15061            if (!childPackageUpdated) {
15062                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15063                childRemovedRes.removedPackage = childPkg.packageName;
15064                childRemovedRes.isUpdate = false;
15065                childRemovedRes.dataRemoved = true;
15066                synchronized (mPackages) {
15067                    if (childPs != null) {
15068                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15069                    }
15070                }
15071                if (res.removedInfo.removedChildPackages == null) {
15072                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15073                }
15074                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15075            }
15076        }
15077
15078        boolean sysPkg = (isSystemApp(oldPackage));
15079        if (sysPkg) {
15080            // Set the system/privileged flags as needed
15081            final boolean privileged =
15082                    (oldPackage.applicationInfo.privateFlags
15083                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15084            final int systemPolicyFlags = policyFlags
15085                    | PackageParser.PARSE_IS_SYSTEM
15086                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15087
15088            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15089                    user, allUsers, installerPackageName, res, installReason);
15090        } else {
15091            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15092                    user, allUsers, installerPackageName, res, installReason);
15093        }
15094    }
15095
15096    public List<String> getPreviousCodePaths(String packageName) {
15097        final PackageSetting ps = mSettings.mPackages.get(packageName);
15098        final List<String> result = new ArrayList<String>();
15099        if (ps != null && ps.oldCodePaths != null) {
15100            result.addAll(ps.oldCodePaths);
15101        }
15102        return result;
15103    }
15104
15105    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15106            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15107            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15108            int installReason) {
15109        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15110                + deletedPackage);
15111
15112        String pkgName = deletedPackage.packageName;
15113        boolean deletedPkg = true;
15114        boolean addedPkg = false;
15115        boolean updatedSettings = false;
15116        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15117        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15118                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15119
15120        final long origUpdateTime = (pkg.mExtras != null)
15121                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15122
15123        // First delete the existing package while retaining the data directory
15124        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15125                res.removedInfo, true, pkg)) {
15126            // If the existing package wasn't successfully deleted
15127            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15128            deletedPkg = false;
15129        } else {
15130            // Successfully deleted the old package; proceed with replace.
15131
15132            // If deleted package lived in a container, give users a chance to
15133            // relinquish resources before killing.
15134            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15135                if (DEBUG_INSTALL) {
15136                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15137                }
15138                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15139                final ArrayList<String> pkgList = new ArrayList<String>(1);
15140                pkgList.add(deletedPackage.applicationInfo.packageName);
15141                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15142            }
15143
15144            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15145                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15146            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15147
15148            try {
15149                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15150                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15151                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15152                        installReason);
15153
15154                // Update the in-memory copy of the previous code paths.
15155                PackageSetting ps = mSettings.mPackages.get(pkgName);
15156                if (!killApp) {
15157                    if (ps.oldCodePaths == null) {
15158                        ps.oldCodePaths = new ArraySet<>();
15159                    }
15160                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15161                    if (deletedPackage.splitCodePaths != null) {
15162                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15163                    }
15164                } else {
15165                    ps.oldCodePaths = null;
15166                }
15167                if (ps.childPackageNames != null) {
15168                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15169                        final String childPkgName = ps.childPackageNames.get(i);
15170                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15171                        childPs.oldCodePaths = ps.oldCodePaths;
15172                    }
15173                }
15174                prepareAppDataAfterInstallLIF(newPackage);
15175                addedPkg = true;
15176            } catch (PackageManagerException e) {
15177                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15178            }
15179        }
15180
15181        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15182            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15183
15184            // Revert all internal state mutations and added folders for the failed install
15185            if (addedPkg) {
15186                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15187                        res.removedInfo, true, null);
15188            }
15189
15190            // Restore the old package
15191            if (deletedPkg) {
15192                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15193                File restoreFile = new File(deletedPackage.codePath);
15194                // Parse old package
15195                boolean oldExternal = isExternal(deletedPackage);
15196                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15197                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15198                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15199                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15200                try {
15201                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15202                            null);
15203                } catch (PackageManagerException e) {
15204                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15205                            + e.getMessage());
15206                    return;
15207                }
15208
15209                synchronized (mPackages) {
15210                    // Ensure the installer package name up to date
15211                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15212
15213                    // Update permissions for restored package
15214                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15215
15216                    mSettings.writeLPr();
15217                }
15218
15219                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15220            }
15221        } else {
15222            synchronized (mPackages) {
15223                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15224                if (ps != null) {
15225                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15226                    if (res.removedInfo.removedChildPackages != null) {
15227                        final int childCount = res.removedInfo.removedChildPackages.size();
15228                        // Iterate in reverse as we may modify the collection
15229                        for (int i = childCount - 1; i >= 0; i--) {
15230                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15231                            if (res.addedChildPackages.containsKey(childPackageName)) {
15232                                res.removedInfo.removedChildPackages.removeAt(i);
15233                            } else {
15234                                PackageRemovedInfo childInfo = res.removedInfo
15235                                        .removedChildPackages.valueAt(i);
15236                                childInfo.removedForAllUsers = mPackages.get(
15237                                        childInfo.removedPackage) == null;
15238                            }
15239                        }
15240                    }
15241                }
15242            }
15243        }
15244    }
15245
15246    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15247            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15248            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15249            int installReason) {
15250        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15251                + ", old=" + deletedPackage);
15252
15253        final boolean disabledSystem;
15254
15255        // Remove existing system package
15256        removePackageLI(deletedPackage, true);
15257
15258        synchronized (mPackages) {
15259            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15260        }
15261        if (!disabledSystem) {
15262            // We didn't need to disable the .apk as a current system package,
15263            // which means we are replacing another update that is already
15264            // installed.  We need to make sure to delete the older one's .apk.
15265            res.removedInfo.args = createInstallArgsForExisting(0,
15266                    deletedPackage.applicationInfo.getCodePath(),
15267                    deletedPackage.applicationInfo.getResourcePath(),
15268                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15269        } else {
15270            res.removedInfo.args = null;
15271        }
15272
15273        // Successfully disabled the old package. Now proceed with re-installation
15274        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15275                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15276        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15277
15278        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15279        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15280                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15281
15282        PackageParser.Package newPackage = null;
15283        try {
15284            // Add the package to the internal data structures
15285            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15286
15287            // Set the update and install times
15288            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15289            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15290                    System.currentTimeMillis());
15291
15292            // Update the package dynamic state if succeeded
15293            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15294                // Now that the install succeeded make sure we remove data
15295                // directories for any child package the update removed.
15296                final int deletedChildCount = (deletedPackage.childPackages != null)
15297                        ? deletedPackage.childPackages.size() : 0;
15298                final int newChildCount = (newPackage.childPackages != null)
15299                        ? newPackage.childPackages.size() : 0;
15300                for (int i = 0; i < deletedChildCount; i++) {
15301                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15302                    boolean childPackageDeleted = true;
15303                    for (int j = 0; j < newChildCount; j++) {
15304                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15305                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15306                            childPackageDeleted = false;
15307                            break;
15308                        }
15309                    }
15310                    if (childPackageDeleted) {
15311                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15312                                deletedChildPkg.packageName);
15313                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15314                            PackageRemovedInfo removedChildRes = res.removedInfo
15315                                    .removedChildPackages.get(deletedChildPkg.packageName);
15316                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15317                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15318                        }
15319                    }
15320                }
15321
15322                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15323                        installReason);
15324                prepareAppDataAfterInstallLIF(newPackage);
15325            }
15326        } catch (PackageManagerException e) {
15327            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15328            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15329        }
15330
15331        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15332            // Re installation failed. Restore old information
15333            // Remove new pkg information
15334            if (newPackage != null) {
15335                removeInstalledPackageLI(newPackage, true);
15336            }
15337            // Add back the old system package
15338            try {
15339                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15340            } catch (PackageManagerException e) {
15341                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15342            }
15343
15344            synchronized (mPackages) {
15345                if (disabledSystem) {
15346                    enableSystemPackageLPw(deletedPackage);
15347                }
15348
15349                // Ensure the installer package name up to date
15350                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15351
15352                // Update permissions for restored package
15353                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15354
15355                mSettings.writeLPr();
15356            }
15357
15358            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15359                    + " after failed upgrade");
15360        }
15361    }
15362
15363    /**
15364     * Checks whether the parent or any of the child packages have a change shared
15365     * user. For a package to be a valid update the shred users of the parent and
15366     * the children should match. We may later support changing child shared users.
15367     * @param oldPkg The updated package.
15368     * @param newPkg The update package.
15369     * @return The shared user that change between the versions.
15370     */
15371    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15372            PackageParser.Package newPkg) {
15373        // Check parent shared user
15374        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15375            return newPkg.packageName;
15376        }
15377        // Check child shared users
15378        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15379        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15380        for (int i = 0; i < newChildCount; i++) {
15381            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15382            // If this child was present, did it have the same shared user?
15383            for (int j = 0; j < oldChildCount; j++) {
15384                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15385                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15386                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15387                    return newChildPkg.packageName;
15388                }
15389            }
15390        }
15391        return null;
15392    }
15393
15394    private void removeNativeBinariesLI(PackageSetting ps) {
15395        // Remove the lib path for the parent package
15396        if (ps != null) {
15397            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15398            // Remove the lib path for the child packages
15399            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15400            for (int i = 0; i < childCount; i++) {
15401                PackageSetting childPs = null;
15402                synchronized (mPackages) {
15403                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15404                }
15405                if (childPs != null) {
15406                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15407                            .legacyNativeLibraryPathString);
15408                }
15409            }
15410        }
15411    }
15412
15413    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15414        // Enable the parent package
15415        mSettings.enableSystemPackageLPw(pkg.packageName);
15416        // Enable the child packages
15417        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15418        for (int i = 0; i < childCount; i++) {
15419            PackageParser.Package childPkg = pkg.childPackages.get(i);
15420            mSettings.enableSystemPackageLPw(childPkg.packageName);
15421        }
15422    }
15423
15424    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15425            PackageParser.Package newPkg) {
15426        // Disable the parent package (parent always replaced)
15427        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15428        // Disable the child packages
15429        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15430        for (int i = 0; i < childCount; i++) {
15431            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15432            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15433            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15434        }
15435        return disabled;
15436    }
15437
15438    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15439            String installerPackageName) {
15440        // Enable the parent package
15441        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15442        // Enable the child packages
15443        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15444        for (int i = 0; i < childCount; i++) {
15445            PackageParser.Package childPkg = pkg.childPackages.get(i);
15446            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15447        }
15448    }
15449
15450    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15451        // Collect all used permissions in the UID
15452        ArraySet<String> usedPermissions = new ArraySet<>();
15453        final int packageCount = su.packages.size();
15454        for (int i = 0; i < packageCount; i++) {
15455            PackageSetting ps = su.packages.valueAt(i);
15456            if (ps.pkg == null) {
15457                continue;
15458            }
15459            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15460            for (int j = 0; j < requestedPermCount; j++) {
15461                String permission = ps.pkg.requestedPermissions.get(j);
15462                BasePermission bp = mSettings.mPermissions.get(permission);
15463                if (bp != null) {
15464                    usedPermissions.add(permission);
15465                }
15466            }
15467        }
15468
15469        PermissionsState permissionsState = su.getPermissionsState();
15470        // Prune install permissions
15471        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15472        final int installPermCount = installPermStates.size();
15473        for (int i = installPermCount - 1; i >= 0;  i--) {
15474            PermissionState permissionState = installPermStates.get(i);
15475            if (!usedPermissions.contains(permissionState.getName())) {
15476                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15477                if (bp != null) {
15478                    permissionsState.revokeInstallPermission(bp);
15479                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15480                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15481                }
15482            }
15483        }
15484
15485        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15486
15487        // Prune runtime permissions
15488        for (int userId : allUserIds) {
15489            List<PermissionState> runtimePermStates = permissionsState
15490                    .getRuntimePermissionStates(userId);
15491            final int runtimePermCount = runtimePermStates.size();
15492            for (int i = runtimePermCount - 1; i >= 0; i--) {
15493                PermissionState permissionState = runtimePermStates.get(i);
15494                if (!usedPermissions.contains(permissionState.getName())) {
15495                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15496                    if (bp != null) {
15497                        permissionsState.revokeRuntimePermission(bp, userId);
15498                        permissionsState.updatePermissionFlags(bp, userId,
15499                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15500                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15501                                runtimePermissionChangedUserIds, userId);
15502                    }
15503                }
15504            }
15505        }
15506
15507        return runtimePermissionChangedUserIds;
15508    }
15509
15510    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15511            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15512        // Update the parent package setting
15513        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15514                res, user, installReason);
15515        // Update the child packages setting
15516        final int childCount = (newPackage.childPackages != null)
15517                ? newPackage.childPackages.size() : 0;
15518        for (int i = 0; i < childCount; i++) {
15519            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15520            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15521            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15522                    childRes.origUsers, childRes, user, installReason);
15523        }
15524    }
15525
15526    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15527            String installerPackageName, int[] allUsers, int[] installedForUsers,
15528            PackageInstalledInfo res, UserHandle user, int installReason) {
15529        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15530
15531        String pkgName = newPackage.packageName;
15532        synchronized (mPackages) {
15533            //write settings. the installStatus will be incomplete at this stage.
15534            //note that the new package setting would have already been
15535            //added to mPackages. It hasn't been persisted yet.
15536            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15537            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15538            mSettings.writeLPr();
15539            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15540        }
15541
15542        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15543        synchronized (mPackages) {
15544            updatePermissionsLPw(newPackage.packageName, newPackage,
15545                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15546                            ? UPDATE_PERMISSIONS_ALL : 0));
15547            // For system-bundled packages, we assume that installing an upgraded version
15548            // of the package implies that the user actually wants to run that new code,
15549            // so we enable the package.
15550            PackageSetting ps = mSettings.mPackages.get(pkgName);
15551            final int userId = user.getIdentifier();
15552            if (ps != null) {
15553                if (isSystemApp(newPackage)) {
15554                    if (DEBUG_INSTALL) {
15555                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15556                    }
15557                    // Enable system package for requested users
15558                    if (res.origUsers != null) {
15559                        for (int origUserId : res.origUsers) {
15560                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15561                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15562                                        origUserId, installerPackageName);
15563                            }
15564                        }
15565                    }
15566                    // Also convey the prior install/uninstall state
15567                    if (allUsers != null && installedForUsers != null) {
15568                        for (int currentUserId : allUsers) {
15569                            final boolean installed = ArrayUtils.contains(
15570                                    installedForUsers, currentUserId);
15571                            if (DEBUG_INSTALL) {
15572                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15573                            }
15574                            ps.setInstalled(installed, currentUserId);
15575                        }
15576                        // these install state changes will be persisted in the
15577                        // upcoming call to mSettings.writeLPr().
15578                    }
15579                }
15580                // It's implied that when a user requests installation, they want the app to be
15581                // installed and enabled.
15582                if (userId != UserHandle.USER_ALL) {
15583                    ps.setInstalled(true, userId);
15584                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15585                }
15586
15587                // When replacing an existing package, preserve the original install reason for all
15588                // users that had the package installed before.
15589                final Set<Integer> previousUserIds = new ArraySet<>();
15590                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15591                    final int installReasonCount = res.removedInfo.installReasons.size();
15592                    for (int i = 0; i < installReasonCount; i++) {
15593                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15594                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15595                        ps.setInstallReason(previousInstallReason, previousUserId);
15596                        previousUserIds.add(previousUserId);
15597                    }
15598                }
15599
15600                // Set install reason for users that are having the package newly installed.
15601                if (userId == UserHandle.USER_ALL) {
15602                    for (int currentUserId : sUserManager.getUserIds()) {
15603                        if (!previousUserIds.contains(currentUserId)) {
15604                            ps.setInstallReason(installReason, currentUserId);
15605                        }
15606                    }
15607                } else if (!previousUserIds.contains(userId)) {
15608                    ps.setInstallReason(installReason, userId);
15609                }
15610            }
15611            res.name = pkgName;
15612            res.uid = newPackage.applicationInfo.uid;
15613            res.pkg = newPackage;
15614            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15615            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15616            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15617            //to update install status
15618            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15619            mSettings.writeLPr();
15620            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15621        }
15622
15623        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15624    }
15625
15626    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15627        try {
15628            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15629            installPackageLI(args, res);
15630        } finally {
15631            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15632        }
15633    }
15634
15635    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15636        final int installFlags = args.installFlags;
15637        final String installerPackageName = args.installerPackageName;
15638        final String volumeUuid = args.volumeUuid;
15639        final File tmpPackageFile = new File(args.getCodePath());
15640        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15641        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15642                || (args.volumeUuid != null));
15643        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15644        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15645        boolean replace = false;
15646        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15647        if (args.move != null) {
15648            // moving a complete application; perform an initial scan on the new install location
15649            scanFlags |= SCAN_INITIAL;
15650        }
15651        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15652            scanFlags |= SCAN_DONT_KILL_APP;
15653        }
15654
15655        // Result object to be returned
15656        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15657
15658        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15659
15660        // Sanity check
15661        if (ephemeral && (forwardLocked || onExternal)) {
15662            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15663                    + " external=" + onExternal);
15664            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15665            return;
15666        }
15667
15668        // Retrieve PackageSettings and parse package
15669        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15670                | PackageParser.PARSE_ENFORCE_CODE
15671                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15672                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15673                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15674                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15675        PackageParser pp = new PackageParser();
15676        pp.setSeparateProcesses(mSeparateProcesses);
15677        pp.setDisplayMetrics(mMetrics);
15678
15679        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15680        final PackageParser.Package pkg;
15681        try {
15682            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15683        } catch (PackageParserException e) {
15684            res.setError("Failed parse during installPackageLI", e);
15685            return;
15686        } finally {
15687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15688        }
15689
15690        // Ephemeral apps must have target SDK >= O.
15691        // TODO: Update conditional and error message when O gets locked down
15692        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15693            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15694                    "Ephemeral apps must have target SDK version of at least O");
15695            return;
15696        }
15697
15698        // If we are installing a clustered package add results for the children
15699        if (pkg.childPackages != null) {
15700            synchronized (mPackages) {
15701                final int childCount = pkg.childPackages.size();
15702                for (int i = 0; i < childCount; i++) {
15703                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15704                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15705                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15706                    childRes.pkg = childPkg;
15707                    childRes.name = childPkg.packageName;
15708                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15709                    if (childPs != null) {
15710                        childRes.origUsers = childPs.queryInstalledUsers(
15711                                sUserManager.getUserIds(), true);
15712                    }
15713                    if ((mPackages.containsKey(childPkg.packageName))) {
15714                        childRes.removedInfo = new PackageRemovedInfo();
15715                        childRes.removedInfo.removedPackage = childPkg.packageName;
15716                    }
15717                    if (res.addedChildPackages == null) {
15718                        res.addedChildPackages = new ArrayMap<>();
15719                    }
15720                    res.addedChildPackages.put(childPkg.packageName, childRes);
15721                }
15722            }
15723        }
15724
15725        // If package doesn't declare API override, mark that we have an install
15726        // time CPU ABI override.
15727        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15728            pkg.cpuAbiOverride = args.abiOverride;
15729        }
15730
15731        String pkgName = res.name = pkg.packageName;
15732        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15733            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15734                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15735                return;
15736            }
15737        }
15738
15739        try {
15740            // either use what we've been given or parse directly from the APK
15741            if (args.certificates != null) {
15742                try {
15743                    PackageParser.populateCertificates(pkg, args.certificates);
15744                } catch (PackageParserException e) {
15745                    // there was something wrong with the certificates we were given;
15746                    // try to pull them from the APK
15747                    PackageParser.collectCertificates(pkg, parseFlags);
15748                }
15749            } else {
15750                PackageParser.collectCertificates(pkg, parseFlags);
15751            }
15752        } catch (PackageParserException e) {
15753            res.setError("Failed collect during installPackageLI", e);
15754            return;
15755        }
15756
15757        // Get rid of all references to package scan path via parser.
15758        pp = null;
15759        String oldCodePath = null;
15760        boolean systemApp = false;
15761        synchronized (mPackages) {
15762            // Check if installing already existing package
15763            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15764                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15765                if (pkg.mOriginalPackages != null
15766                        && pkg.mOriginalPackages.contains(oldName)
15767                        && mPackages.containsKey(oldName)) {
15768                    // This package is derived from an original package,
15769                    // and this device has been updating from that original
15770                    // name.  We must continue using the original name, so
15771                    // rename the new package here.
15772                    pkg.setPackageName(oldName);
15773                    pkgName = pkg.packageName;
15774                    replace = true;
15775                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15776                            + oldName + " pkgName=" + pkgName);
15777                } else if (mPackages.containsKey(pkgName)) {
15778                    // This package, under its official name, already exists
15779                    // on the device; we should replace it.
15780                    replace = true;
15781                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15782                }
15783
15784                // Child packages are installed through the parent package
15785                if (pkg.parentPackage != null) {
15786                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15787                            "Package " + pkg.packageName + " is child of package "
15788                                    + pkg.parentPackage.parentPackage + ". Child packages "
15789                                    + "can be updated only through the parent package.");
15790                    return;
15791                }
15792
15793                if (replace) {
15794                    // Prevent apps opting out from runtime permissions
15795                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15796                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15797                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15798                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15799                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15800                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15801                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15802                                        + " doesn't support runtime permissions but the old"
15803                                        + " target SDK " + oldTargetSdk + " does.");
15804                        return;
15805                    }
15806
15807                    // Prevent installing of child packages
15808                    if (oldPackage.parentPackage != null) {
15809                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15810                                "Package " + pkg.packageName + " is child of package "
15811                                        + oldPackage.parentPackage + ". Child packages "
15812                                        + "can be updated only through the parent package.");
15813                        return;
15814                    }
15815                }
15816            }
15817
15818            PackageSetting ps = mSettings.mPackages.get(pkgName);
15819            if (ps != null) {
15820                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15821
15822                // Quick sanity check that we're signed correctly if updating;
15823                // we'll check this again later when scanning, but we want to
15824                // bail early here before tripping over redefined permissions.
15825                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15826                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15827                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15828                                + pkg.packageName + " upgrade keys do not match the "
15829                                + "previously installed version");
15830                        return;
15831                    }
15832                } else {
15833                    try {
15834                        verifySignaturesLP(ps, pkg);
15835                    } catch (PackageManagerException e) {
15836                        res.setError(e.error, e.getMessage());
15837                        return;
15838                    }
15839                }
15840
15841                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15842                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15843                    systemApp = (ps.pkg.applicationInfo.flags &
15844                            ApplicationInfo.FLAG_SYSTEM) != 0;
15845                }
15846                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15847            }
15848
15849            // Check whether the newly-scanned package wants to define an already-defined perm
15850            int N = pkg.permissions.size();
15851            for (int i = N-1; i >= 0; i--) {
15852                PackageParser.Permission perm = pkg.permissions.get(i);
15853                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15854                if (bp != null) {
15855                    // If the defining package is signed with our cert, it's okay.  This
15856                    // also includes the "updating the same package" case, of course.
15857                    // "updating same package" could also involve key-rotation.
15858                    final boolean sigsOk;
15859                    if (bp.sourcePackage.equals(pkg.packageName)
15860                            && (bp.packageSetting instanceof PackageSetting)
15861                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15862                                    scanFlags))) {
15863                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15864                    } else {
15865                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15866                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15867                    }
15868                    if (!sigsOk) {
15869                        // If the owning package is the system itself, we log but allow
15870                        // install to proceed; we fail the install on all other permission
15871                        // redefinitions.
15872                        if (!bp.sourcePackage.equals("android")) {
15873                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15874                                    + pkg.packageName + " attempting to redeclare permission "
15875                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15876                            res.origPermission = perm.info.name;
15877                            res.origPackage = bp.sourcePackage;
15878                            return;
15879                        } else {
15880                            Slog.w(TAG, "Package " + pkg.packageName
15881                                    + " attempting to redeclare system permission "
15882                                    + perm.info.name + "; ignoring new declaration");
15883                            pkg.permissions.remove(i);
15884                        }
15885                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15886                        // Prevent apps to change protection level to dangerous from any other
15887                        // type as this would allow a privilege escalation where an app adds a
15888                        // normal/signature permission in other app's group and later redefines
15889                        // it as dangerous leading to the group auto-grant.
15890                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15891                                == PermissionInfo.PROTECTION_DANGEROUS) {
15892                            if (bp != null && !bp.isRuntime()) {
15893                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15894                                        + "non-runtime permission " + perm.info.name
15895                                        + " to runtime; keeping old protection level");
15896                                perm.info.protectionLevel = bp.protectionLevel;
15897                            }
15898                        }
15899                    }
15900                }
15901            }
15902        }
15903
15904        if (systemApp) {
15905            if (onExternal) {
15906                // Abort update; system app can't be replaced with app on sdcard
15907                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15908                        "Cannot install updates to system apps on sdcard");
15909                return;
15910            } else if (ephemeral) {
15911                // Abort update; system app can't be replaced with an ephemeral app
15912                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15913                        "Cannot update a system app with an ephemeral app");
15914                return;
15915            }
15916        }
15917
15918        if (args.move != null) {
15919            // We did an in-place move, so dex is ready to roll
15920            scanFlags |= SCAN_NO_DEX;
15921            scanFlags |= SCAN_MOVE;
15922
15923            synchronized (mPackages) {
15924                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15925                if (ps == null) {
15926                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15927                            "Missing settings for moved package " + pkgName);
15928                }
15929
15930                // We moved the entire application as-is, so bring over the
15931                // previously derived ABI information.
15932                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15933                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15934            }
15935
15936        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15937            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15938            scanFlags |= SCAN_NO_DEX;
15939
15940            try {
15941                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15942                    args.abiOverride : pkg.cpuAbiOverride);
15943                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15944                        true /*extractLibs*/, mAppLib32InstallDir);
15945            } catch (PackageManagerException pme) {
15946                Slog.e(TAG, "Error deriving application ABI", pme);
15947                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15948                return;
15949            }
15950
15951            // Shared libraries for the package need to be updated.
15952            synchronized (mPackages) {
15953                try {
15954                    updateSharedLibrariesLPr(pkg, null);
15955                } catch (PackageManagerException e) {
15956                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15957                }
15958            }
15959            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15960            // Do not run PackageDexOptimizer through the local performDexOpt
15961            // method because `pkg` may not be in `mPackages` yet.
15962            //
15963            // Also, don't fail application installs if the dexopt step fails.
15964            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15965                    null /* instructionSets */, false /* checkProfiles */,
15966                    getCompilerFilterForReason(REASON_INSTALL),
15967                    getOrCreateCompilerPackageStats(pkg));
15968            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15969
15970            // Notify BackgroundDexOptService that the package has been changed.
15971            // If this is an update of a package which used to fail to compile,
15972            // BDOS will remove it from its blacklist.
15973            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15974        }
15975
15976        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15977            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15978            return;
15979        }
15980
15981        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15982
15983        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15984                "installPackageLI")) {
15985            if (replace) {
15986                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15987                        installerPackageName, res, args.installReason);
15988            } else {
15989                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15990                        args.user, installerPackageName, volumeUuid, res, args.installReason);
15991            }
15992        }
15993        synchronized (mPackages) {
15994            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15995            if (ps != null) {
15996                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15997            }
15998
15999            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16000            for (int i = 0; i < childCount; i++) {
16001                PackageParser.Package childPkg = pkg.childPackages.get(i);
16002                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16003                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16004                if (childPs != null) {
16005                    childRes.newUsers = childPs.queryInstalledUsers(
16006                            sUserManager.getUserIds(), true);
16007                }
16008            }
16009        }
16010    }
16011
16012    private void startIntentFilterVerifications(int userId, boolean replacing,
16013            PackageParser.Package pkg) {
16014        if (mIntentFilterVerifierComponent == null) {
16015            Slog.w(TAG, "No IntentFilter verification will not be done as "
16016                    + "there is no IntentFilterVerifier available!");
16017            return;
16018        }
16019
16020        final int verifierUid = getPackageUid(
16021                mIntentFilterVerifierComponent.getPackageName(),
16022                MATCH_DEBUG_TRIAGED_MISSING,
16023                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16024
16025        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16026        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16027        mHandler.sendMessage(msg);
16028
16029        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16030        for (int i = 0; i < childCount; i++) {
16031            PackageParser.Package childPkg = pkg.childPackages.get(i);
16032            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16033            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16034            mHandler.sendMessage(msg);
16035        }
16036    }
16037
16038    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16039            PackageParser.Package pkg) {
16040        int size = pkg.activities.size();
16041        if (size == 0) {
16042            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16043                    "No activity, so no need to verify any IntentFilter!");
16044            return;
16045        }
16046
16047        final boolean hasDomainURLs = hasDomainURLs(pkg);
16048        if (!hasDomainURLs) {
16049            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16050                    "No domain URLs, so no need to verify any IntentFilter!");
16051            return;
16052        }
16053
16054        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16055                + " if any IntentFilter from the " + size
16056                + " Activities needs verification ...");
16057
16058        int count = 0;
16059        final String packageName = pkg.packageName;
16060
16061        synchronized (mPackages) {
16062            // If this is a new install and we see that we've already run verification for this
16063            // package, we have nothing to do: it means the state was restored from backup.
16064            if (!replacing) {
16065                IntentFilterVerificationInfo ivi =
16066                        mSettings.getIntentFilterVerificationLPr(packageName);
16067                if (ivi != null) {
16068                    if (DEBUG_DOMAIN_VERIFICATION) {
16069                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16070                                + ivi.getStatusString());
16071                    }
16072                    return;
16073                }
16074            }
16075
16076            // If any filters need to be verified, then all need to be.
16077            boolean needToVerify = false;
16078            for (PackageParser.Activity a : pkg.activities) {
16079                for (ActivityIntentInfo filter : a.intents) {
16080                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16081                        if (DEBUG_DOMAIN_VERIFICATION) {
16082                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16083                        }
16084                        needToVerify = true;
16085                        break;
16086                    }
16087                }
16088            }
16089
16090            if (needToVerify) {
16091                final int verificationId = mIntentFilterVerificationToken++;
16092                for (PackageParser.Activity a : pkg.activities) {
16093                    for (ActivityIntentInfo filter : a.intents) {
16094                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16095                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16096                                    "Verification needed for IntentFilter:" + filter.toString());
16097                            mIntentFilterVerifier.addOneIntentFilterVerification(
16098                                    verifierUid, userId, verificationId, filter, packageName);
16099                            count++;
16100                        }
16101                    }
16102                }
16103            }
16104        }
16105
16106        if (count > 0) {
16107            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16108                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16109                    +  " for userId:" + userId);
16110            mIntentFilterVerifier.startVerifications(userId);
16111        } else {
16112            if (DEBUG_DOMAIN_VERIFICATION) {
16113                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16114            }
16115        }
16116    }
16117
16118    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16119        final ComponentName cn  = filter.activity.getComponentName();
16120        final String packageName = cn.getPackageName();
16121
16122        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16123                packageName);
16124        if (ivi == null) {
16125            return true;
16126        }
16127        int status = ivi.getStatus();
16128        switch (status) {
16129            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16130            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16131                return true;
16132
16133            default:
16134                // Nothing to do
16135                return false;
16136        }
16137    }
16138
16139    private static boolean isMultiArch(ApplicationInfo info) {
16140        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16141    }
16142
16143    private static boolean isExternal(PackageParser.Package pkg) {
16144        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16145    }
16146
16147    private static boolean isExternal(PackageSetting ps) {
16148        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16149    }
16150
16151    private static boolean isEphemeral(PackageParser.Package pkg) {
16152        return pkg.applicationInfo.isEphemeralApp();
16153    }
16154
16155    private static boolean isEphemeral(PackageSetting ps) {
16156        return ps.pkg != null && isEphemeral(ps.pkg);
16157    }
16158
16159    private static boolean isSystemApp(PackageParser.Package pkg) {
16160        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16161    }
16162
16163    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16164        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16165    }
16166
16167    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16168        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16169    }
16170
16171    private static boolean isSystemApp(PackageSetting ps) {
16172        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16173    }
16174
16175    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16176        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16177    }
16178
16179    private int packageFlagsToInstallFlags(PackageSetting ps) {
16180        int installFlags = 0;
16181        if (isEphemeral(ps)) {
16182            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16183        }
16184        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16185            // This existing package was an external ASEC install when we have
16186            // the external flag without a UUID
16187            installFlags |= PackageManager.INSTALL_EXTERNAL;
16188        }
16189        if (ps.isForwardLocked()) {
16190            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16191        }
16192        return installFlags;
16193    }
16194
16195    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16196        if (isExternal(pkg)) {
16197            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16198                return StorageManager.UUID_PRIMARY_PHYSICAL;
16199            } else {
16200                return pkg.volumeUuid;
16201            }
16202        } else {
16203            return StorageManager.UUID_PRIVATE_INTERNAL;
16204        }
16205    }
16206
16207    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16208        if (isExternal(pkg)) {
16209            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16210                return mSettings.getExternalVersion();
16211            } else {
16212                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16213            }
16214        } else {
16215            return mSettings.getInternalVersion();
16216        }
16217    }
16218
16219    private void deleteTempPackageFiles() {
16220        final FilenameFilter filter = new FilenameFilter() {
16221            public boolean accept(File dir, String name) {
16222                return name.startsWith("vmdl") && name.endsWith(".tmp");
16223            }
16224        };
16225        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16226            file.delete();
16227        }
16228    }
16229
16230    @Override
16231    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16232            int flags) {
16233        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16234                flags);
16235    }
16236
16237    @Override
16238    public void deletePackage(final String packageName,
16239            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16240        mContext.enforceCallingOrSelfPermission(
16241                android.Manifest.permission.DELETE_PACKAGES, null);
16242        Preconditions.checkNotNull(packageName);
16243        Preconditions.checkNotNull(observer);
16244        final int uid = Binder.getCallingUid();
16245        if (!isOrphaned(packageName)
16246                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16247            try {
16248                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16249                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16250                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16251                observer.onUserActionRequired(intent);
16252            } catch (RemoteException re) {
16253            }
16254            return;
16255        }
16256        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16257        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16258        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16259            mContext.enforceCallingOrSelfPermission(
16260                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16261                    "deletePackage for user " + userId);
16262        }
16263
16264        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16265            try {
16266                observer.onPackageDeleted(packageName,
16267                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16268            } catch (RemoteException re) {
16269            }
16270            return;
16271        }
16272
16273        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16274            try {
16275                observer.onPackageDeleted(packageName,
16276                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16277            } catch (RemoteException re) {
16278            }
16279            return;
16280        }
16281
16282        if (DEBUG_REMOVE) {
16283            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16284                    + " deleteAllUsers: " + deleteAllUsers );
16285        }
16286        // Queue up an async operation since the package deletion may take a little while.
16287        mHandler.post(new Runnable() {
16288            public void run() {
16289                mHandler.removeCallbacks(this);
16290                int returnCode;
16291                if (!deleteAllUsers) {
16292                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16293                } else {
16294                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16295                    // If nobody is blocking uninstall, proceed with delete for all users
16296                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16297                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16298                    } else {
16299                        // Otherwise uninstall individually for users with blockUninstalls=false
16300                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16301                        for (int userId : users) {
16302                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16303                                returnCode = deletePackageX(packageName, userId, userFlags);
16304                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16305                                    Slog.w(TAG, "Package delete failed for user " + userId
16306                                            + ", returnCode " + returnCode);
16307                                }
16308                            }
16309                        }
16310                        // The app has only been marked uninstalled for certain users.
16311                        // We still need to report that delete was blocked
16312                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16313                    }
16314                }
16315                try {
16316                    observer.onPackageDeleted(packageName, returnCode, null);
16317                } catch (RemoteException e) {
16318                    Log.i(TAG, "Observer no longer exists.");
16319                } //end catch
16320            } //end run
16321        });
16322    }
16323
16324    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16325        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16326              || callingUid == Process.SYSTEM_UID) {
16327            return true;
16328        }
16329        final int callingUserId = UserHandle.getUserId(callingUid);
16330        // If the caller installed the pkgName, then allow it to silently uninstall.
16331        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16332            return true;
16333        }
16334
16335        // Allow package verifier to silently uninstall.
16336        if (mRequiredVerifierPackage != null &&
16337                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16338            return true;
16339        }
16340
16341        // Allow package uninstaller to silently uninstall.
16342        if (mRequiredUninstallerPackage != null &&
16343                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16344            return true;
16345        }
16346
16347        // Allow storage manager to silently uninstall.
16348        if (mStorageManagerPackage != null &&
16349                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16350            return true;
16351        }
16352        return false;
16353    }
16354
16355    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16356        int[] result = EMPTY_INT_ARRAY;
16357        for (int userId : userIds) {
16358            if (getBlockUninstallForUser(packageName, userId)) {
16359                result = ArrayUtils.appendInt(result, userId);
16360            }
16361        }
16362        return result;
16363    }
16364
16365    @Override
16366    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16367        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16368    }
16369
16370    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16371        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16372                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16373        try {
16374            if (dpm != null) {
16375                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16376                        /* callingUserOnly =*/ false);
16377                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16378                        : deviceOwnerComponentName.getPackageName();
16379                // Does the package contains the device owner?
16380                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16381                // this check is probably not needed, since DO should be registered as a device
16382                // admin on some user too. (Original bug for this: b/17657954)
16383                if (packageName.equals(deviceOwnerPackageName)) {
16384                    return true;
16385                }
16386                // Does it contain a device admin for any user?
16387                int[] users;
16388                if (userId == UserHandle.USER_ALL) {
16389                    users = sUserManager.getUserIds();
16390                } else {
16391                    users = new int[]{userId};
16392                }
16393                for (int i = 0; i < users.length; ++i) {
16394                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16395                        return true;
16396                    }
16397                }
16398            }
16399        } catch (RemoteException e) {
16400        }
16401        return false;
16402    }
16403
16404    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16405        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16406    }
16407
16408    /**
16409     *  This method is an internal method that could be get invoked either
16410     *  to delete an installed package or to clean up a failed installation.
16411     *  After deleting an installed package, a broadcast is sent to notify any
16412     *  listeners that the package has been removed. For cleaning up a failed
16413     *  installation, the broadcast is not necessary since the package's
16414     *  installation wouldn't have sent the initial broadcast either
16415     *  The key steps in deleting a package are
16416     *  deleting the package information in internal structures like mPackages,
16417     *  deleting the packages base directories through installd
16418     *  updating mSettings to reflect current status
16419     *  persisting settings for later use
16420     *  sending a broadcast if necessary
16421     */
16422    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16423        final PackageRemovedInfo info = new PackageRemovedInfo();
16424        final boolean res;
16425
16426        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16427                ? UserHandle.USER_ALL : userId;
16428
16429        if (isPackageDeviceAdmin(packageName, removeUser)) {
16430            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16431            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16432        }
16433
16434        PackageSetting uninstalledPs = null;
16435
16436        // for the uninstall-updates case and restricted profiles, remember the per-
16437        // user handle installed state
16438        int[] allUsers;
16439        synchronized (mPackages) {
16440            uninstalledPs = mSettings.mPackages.get(packageName);
16441            if (uninstalledPs == null) {
16442                Slog.w(TAG, "Not removing non-existent package " + packageName);
16443                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16444            }
16445            allUsers = sUserManager.getUserIds();
16446            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16447        }
16448
16449        final int freezeUser;
16450        if (isUpdatedSystemApp(uninstalledPs)
16451                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16452            // We're downgrading a system app, which will apply to all users, so
16453            // freeze them all during the downgrade
16454            freezeUser = UserHandle.USER_ALL;
16455        } else {
16456            freezeUser = removeUser;
16457        }
16458
16459        synchronized (mInstallLock) {
16460            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16461            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16462                    deleteFlags, "deletePackageX")) {
16463                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16464                        deleteFlags | REMOVE_CHATTY, info, true, null);
16465            }
16466            synchronized (mPackages) {
16467                if (res) {
16468                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16469                }
16470            }
16471        }
16472
16473        if (res) {
16474            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16475            info.sendPackageRemovedBroadcasts(killApp);
16476            info.sendSystemPackageUpdatedBroadcasts();
16477            info.sendSystemPackageAppearedBroadcasts();
16478        }
16479        // Force a gc here.
16480        Runtime.getRuntime().gc();
16481        // Delete the resources here after sending the broadcast to let
16482        // other processes clean up before deleting resources.
16483        if (info.args != null) {
16484            synchronized (mInstallLock) {
16485                info.args.doPostDeleteLI(true);
16486            }
16487        }
16488
16489        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16490    }
16491
16492    class PackageRemovedInfo {
16493        String removedPackage;
16494        int uid = -1;
16495        int removedAppId = -1;
16496        int[] origUsers;
16497        int[] removedUsers = null;
16498        SparseArray<Integer> installReasons;
16499        boolean isRemovedPackageSystemUpdate = false;
16500        boolean isUpdate;
16501        boolean dataRemoved;
16502        boolean removedForAllUsers;
16503        // Clean up resources deleted packages.
16504        InstallArgs args = null;
16505        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16506        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16507
16508        void sendPackageRemovedBroadcasts(boolean killApp) {
16509            sendPackageRemovedBroadcastInternal(killApp);
16510            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16511            for (int i = 0; i < childCount; i++) {
16512                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16513                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16514            }
16515        }
16516
16517        void sendSystemPackageUpdatedBroadcasts() {
16518            if (isRemovedPackageSystemUpdate) {
16519                sendSystemPackageUpdatedBroadcastsInternal();
16520                final int childCount = (removedChildPackages != null)
16521                        ? removedChildPackages.size() : 0;
16522                for (int i = 0; i < childCount; i++) {
16523                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16524                    if (childInfo.isRemovedPackageSystemUpdate) {
16525                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16526                    }
16527                }
16528            }
16529        }
16530
16531        void sendSystemPackageAppearedBroadcasts() {
16532            final int packageCount = (appearedChildPackages != null)
16533                    ? appearedChildPackages.size() : 0;
16534            for (int i = 0; i < packageCount; i++) {
16535                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16536                sendPackageAddedForNewUsers(installedInfo.name, true,
16537                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16538            }
16539        }
16540
16541        private void sendSystemPackageUpdatedBroadcastsInternal() {
16542            Bundle extras = new Bundle(2);
16543            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16544            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16545            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16546                    extras, 0, null, null, null);
16547            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16548                    extras, 0, null, null, null);
16549            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16550                    null, 0, removedPackage, null, null);
16551        }
16552
16553        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16554            Bundle extras = new Bundle(2);
16555            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16556            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16557            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16558            if (isUpdate || isRemovedPackageSystemUpdate) {
16559                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16560            }
16561            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16562            if (removedPackage != null) {
16563                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16564                        extras, 0, null, null, removedUsers);
16565                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16566                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16567                            removedPackage, extras, 0, null, null, removedUsers);
16568                }
16569            }
16570            if (removedAppId >= 0) {
16571                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16572                        removedUsers);
16573            }
16574        }
16575    }
16576
16577    /*
16578     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16579     * flag is not set, the data directory is removed as well.
16580     * make sure this flag is set for partially installed apps. If not its meaningless to
16581     * delete a partially installed application.
16582     */
16583    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16584            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16585        String packageName = ps.name;
16586        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16587        // Retrieve object to delete permissions for shared user later on
16588        final PackageParser.Package deletedPkg;
16589        final PackageSetting deletedPs;
16590        // reader
16591        synchronized (mPackages) {
16592            deletedPkg = mPackages.get(packageName);
16593            deletedPs = mSettings.mPackages.get(packageName);
16594            if (outInfo != null) {
16595                outInfo.removedPackage = packageName;
16596                outInfo.removedUsers = deletedPs != null
16597                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16598                        : null;
16599            }
16600        }
16601
16602        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16603
16604        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16605            final PackageParser.Package resolvedPkg;
16606            if (deletedPkg != null) {
16607                resolvedPkg = deletedPkg;
16608            } else {
16609                // We don't have a parsed package when it lives on an ejected
16610                // adopted storage device, so fake something together
16611                resolvedPkg = new PackageParser.Package(ps.name);
16612                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16613            }
16614            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16615                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16616            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16617            if (outInfo != null) {
16618                outInfo.dataRemoved = true;
16619            }
16620            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16621        }
16622
16623        // writer
16624        synchronized (mPackages) {
16625            if (deletedPs != null) {
16626                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16627                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16628                    clearDefaultBrowserIfNeeded(packageName);
16629                    if (outInfo != null) {
16630                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16631                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16632                    }
16633                    updatePermissionsLPw(deletedPs.name, null, 0);
16634                    if (deletedPs.sharedUser != null) {
16635                        // Remove permissions associated with package. Since runtime
16636                        // permissions are per user we have to kill the removed package
16637                        // or packages running under the shared user of the removed
16638                        // package if revoking the permissions requested only by the removed
16639                        // package is successful and this causes a change in gids.
16640                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16641                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16642                                    userId);
16643                            if (userIdToKill == UserHandle.USER_ALL
16644                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16645                                // If gids changed for this user, kill all affected packages.
16646                                mHandler.post(new Runnable() {
16647                                    @Override
16648                                    public void run() {
16649                                        // This has to happen with no lock held.
16650                                        killApplication(deletedPs.name, deletedPs.appId,
16651                                                KILL_APP_REASON_GIDS_CHANGED);
16652                                    }
16653                                });
16654                                break;
16655                            }
16656                        }
16657                    }
16658                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16659                }
16660                // make sure to preserve per-user disabled state if this removal was just
16661                // a downgrade of a system app to the factory package
16662                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16663                    if (DEBUG_REMOVE) {
16664                        Slog.d(TAG, "Propagating install state across downgrade");
16665                    }
16666                    for (int userId : allUserHandles) {
16667                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16668                        if (DEBUG_REMOVE) {
16669                            Slog.d(TAG, "    user " + userId + " => " + installed);
16670                        }
16671                        ps.setInstalled(installed, userId);
16672                    }
16673                }
16674            }
16675            // can downgrade to reader
16676            if (writeSettings) {
16677                // Save settings now
16678                mSettings.writeLPr();
16679            }
16680        }
16681        if (outInfo != null) {
16682            // A user ID was deleted here. Go through all users and remove it
16683            // from KeyStore.
16684            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16685        }
16686    }
16687
16688    static boolean locationIsPrivileged(File path) {
16689        try {
16690            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16691                    .getCanonicalPath();
16692            return path.getCanonicalPath().startsWith(privilegedAppDir);
16693        } catch (IOException e) {
16694            Slog.e(TAG, "Unable to access code path " + path);
16695        }
16696        return false;
16697    }
16698
16699    /*
16700     * Tries to delete system package.
16701     */
16702    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16703            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16704            boolean writeSettings) {
16705        if (deletedPs.parentPackageName != null) {
16706            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16707            return false;
16708        }
16709
16710        final boolean applyUserRestrictions
16711                = (allUserHandles != null) && (outInfo.origUsers != null);
16712        final PackageSetting disabledPs;
16713        // Confirm if the system package has been updated
16714        // An updated system app can be deleted. This will also have to restore
16715        // the system pkg from system partition
16716        // reader
16717        synchronized (mPackages) {
16718            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16719        }
16720
16721        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16722                + " disabledPs=" + disabledPs);
16723
16724        if (disabledPs == null) {
16725            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16726            return false;
16727        } else if (DEBUG_REMOVE) {
16728            Slog.d(TAG, "Deleting system pkg from data partition");
16729        }
16730
16731        if (DEBUG_REMOVE) {
16732            if (applyUserRestrictions) {
16733                Slog.d(TAG, "Remembering install states:");
16734                for (int userId : allUserHandles) {
16735                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16736                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16737                }
16738            }
16739        }
16740
16741        // Delete the updated package
16742        outInfo.isRemovedPackageSystemUpdate = true;
16743        if (outInfo.removedChildPackages != null) {
16744            final int childCount = (deletedPs.childPackageNames != null)
16745                    ? deletedPs.childPackageNames.size() : 0;
16746            for (int i = 0; i < childCount; i++) {
16747                String childPackageName = deletedPs.childPackageNames.get(i);
16748                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16749                        .contains(childPackageName)) {
16750                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16751                            childPackageName);
16752                    if (childInfo != null) {
16753                        childInfo.isRemovedPackageSystemUpdate = true;
16754                    }
16755                }
16756            }
16757        }
16758
16759        if (disabledPs.versionCode < deletedPs.versionCode) {
16760            // Delete data for downgrades
16761            flags &= ~PackageManager.DELETE_KEEP_DATA;
16762        } else {
16763            // Preserve data by setting flag
16764            flags |= PackageManager.DELETE_KEEP_DATA;
16765        }
16766
16767        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16768                outInfo, writeSettings, disabledPs.pkg);
16769        if (!ret) {
16770            return false;
16771        }
16772
16773        // writer
16774        synchronized (mPackages) {
16775            // Reinstate the old system package
16776            enableSystemPackageLPw(disabledPs.pkg);
16777            // Remove any native libraries from the upgraded package.
16778            removeNativeBinariesLI(deletedPs);
16779        }
16780
16781        // Install the system package
16782        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16783        int parseFlags = mDefParseFlags
16784                | PackageParser.PARSE_MUST_BE_APK
16785                | PackageParser.PARSE_IS_SYSTEM
16786                | PackageParser.PARSE_IS_SYSTEM_DIR;
16787        if (locationIsPrivileged(disabledPs.codePath)) {
16788            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16789        }
16790
16791        final PackageParser.Package newPkg;
16792        try {
16793            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16794                0 /* currentTime */, null);
16795        } catch (PackageManagerException e) {
16796            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16797                    + e.getMessage());
16798            return false;
16799        }
16800        try {
16801            // update shared libraries for the newly re-installed system package
16802            updateSharedLibrariesLPr(newPkg, null);
16803        } catch (PackageManagerException e) {
16804            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16805        }
16806
16807        prepareAppDataAfterInstallLIF(newPkg);
16808
16809        // writer
16810        synchronized (mPackages) {
16811            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16812
16813            // Propagate the permissions state as we do not want to drop on the floor
16814            // runtime permissions. The update permissions method below will take
16815            // care of removing obsolete permissions and grant install permissions.
16816            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16817            updatePermissionsLPw(newPkg.packageName, newPkg,
16818                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16819
16820            if (applyUserRestrictions) {
16821                if (DEBUG_REMOVE) {
16822                    Slog.d(TAG, "Propagating install state across reinstall");
16823                }
16824                for (int userId : allUserHandles) {
16825                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16826                    if (DEBUG_REMOVE) {
16827                        Slog.d(TAG, "    user " + userId + " => " + installed);
16828                    }
16829                    ps.setInstalled(installed, userId);
16830
16831                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16832                }
16833                // Regardless of writeSettings we need to ensure that this restriction
16834                // state propagation is persisted
16835                mSettings.writeAllUsersPackageRestrictionsLPr();
16836            }
16837            // can downgrade to reader here
16838            if (writeSettings) {
16839                mSettings.writeLPr();
16840            }
16841        }
16842        return true;
16843    }
16844
16845    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16846            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16847            PackageRemovedInfo outInfo, boolean writeSettings,
16848            PackageParser.Package replacingPackage) {
16849        synchronized (mPackages) {
16850            if (outInfo != null) {
16851                outInfo.uid = ps.appId;
16852            }
16853
16854            if (outInfo != null && outInfo.removedChildPackages != null) {
16855                final int childCount = (ps.childPackageNames != null)
16856                        ? ps.childPackageNames.size() : 0;
16857                for (int i = 0; i < childCount; i++) {
16858                    String childPackageName = ps.childPackageNames.get(i);
16859                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16860                    if (childPs == null) {
16861                        return false;
16862                    }
16863                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16864                            childPackageName);
16865                    if (childInfo != null) {
16866                        childInfo.uid = childPs.appId;
16867                    }
16868                }
16869            }
16870        }
16871
16872        // Delete package data from internal structures and also remove data if flag is set
16873        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16874
16875        // Delete the child packages data
16876        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16877        for (int i = 0; i < childCount; i++) {
16878            PackageSetting childPs;
16879            synchronized (mPackages) {
16880                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16881            }
16882            if (childPs != null) {
16883                PackageRemovedInfo childOutInfo = (outInfo != null
16884                        && outInfo.removedChildPackages != null)
16885                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16886                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16887                        && (replacingPackage != null
16888                        && !replacingPackage.hasChildPackage(childPs.name))
16889                        ? flags & ~DELETE_KEEP_DATA : flags;
16890                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16891                        deleteFlags, writeSettings);
16892            }
16893        }
16894
16895        // Delete application code and resources only for parent packages
16896        if (ps.parentPackageName == null) {
16897            if (deleteCodeAndResources && (outInfo != null)) {
16898                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16899                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16900                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16901            }
16902        }
16903
16904        return true;
16905    }
16906
16907    @Override
16908    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16909            int userId) {
16910        mContext.enforceCallingOrSelfPermission(
16911                android.Manifest.permission.DELETE_PACKAGES, null);
16912        synchronized (mPackages) {
16913            PackageSetting ps = mSettings.mPackages.get(packageName);
16914            if (ps == null) {
16915                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16916                return false;
16917            }
16918            if (!ps.getInstalled(userId)) {
16919                // Can't block uninstall for an app that is not installed or enabled.
16920                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16921                return false;
16922            }
16923            ps.setBlockUninstall(blockUninstall, userId);
16924            mSettings.writePackageRestrictionsLPr(userId);
16925        }
16926        return true;
16927    }
16928
16929    @Override
16930    public boolean getBlockUninstallForUser(String packageName, int userId) {
16931        synchronized (mPackages) {
16932            PackageSetting ps = mSettings.mPackages.get(packageName);
16933            if (ps == null) {
16934                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16935                return false;
16936            }
16937            return ps.getBlockUninstall(userId);
16938        }
16939    }
16940
16941    @Override
16942    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16943        int callingUid = Binder.getCallingUid();
16944        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16945            throw new SecurityException(
16946                    "setRequiredForSystemUser can only be run by the system or root");
16947        }
16948        synchronized (mPackages) {
16949            PackageSetting ps = mSettings.mPackages.get(packageName);
16950            if (ps == null) {
16951                Log.w(TAG, "Package doesn't exist: " + packageName);
16952                return false;
16953            }
16954            if (systemUserApp) {
16955                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16956            } else {
16957                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16958            }
16959            mSettings.writeLPr();
16960        }
16961        return true;
16962    }
16963
16964    /*
16965     * This method handles package deletion in general
16966     */
16967    private boolean deletePackageLIF(String packageName, UserHandle user,
16968            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16969            PackageRemovedInfo outInfo, boolean writeSettings,
16970            PackageParser.Package replacingPackage) {
16971        if (packageName == null) {
16972            Slog.w(TAG, "Attempt to delete null packageName.");
16973            return false;
16974        }
16975
16976        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16977
16978        PackageSetting ps;
16979
16980        synchronized (mPackages) {
16981            ps = mSettings.mPackages.get(packageName);
16982            if (ps == null) {
16983                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16984                return false;
16985            }
16986
16987            if (ps.parentPackageName != null && (!isSystemApp(ps)
16988                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16989                if (DEBUG_REMOVE) {
16990                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16991                            + ((user == null) ? UserHandle.USER_ALL : user));
16992                }
16993                final int removedUserId = (user != null) ? user.getIdentifier()
16994                        : UserHandle.USER_ALL;
16995                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16996                    return false;
16997                }
16998                markPackageUninstalledForUserLPw(ps, user);
16999                scheduleWritePackageRestrictionsLocked(user);
17000                return true;
17001            }
17002        }
17003
17004        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17005                && user.getIdentifier() != UserHandle.USER_ALL)) {
17006            // The caller is asking that the package only be deleted for a single
17007            // user.  To do this, we just mark its uninstalled state and delete
17008            // its data. If this is a system app, we only allow this to happen if
17009            // they have set the special DELETE_SYSTEM_APP which requests different
17010            // semantics than normal for uninstalling system apps.
17011            markPackageUninstalledForUserLPw(ps, user);
17012
17013            if (!isSystemApp(ps)) {
17014                // Do not uninstall the APK if an app should be cached
17015                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17016                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17017                    // Other user still have this package installed, so all
17018                    // we need to do is clear this user's data and save that
17019                    // it is uninstalled.
17020                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17021                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17022                        return false;
17023                    }
17024                    scheduleWritePackageRestrictionsLocked(user);
17025                    return true;
17026                } else {
17027                    // We need to set it back to 'installed' so the uninstall
17028                    // broadcasts will be sent correctly.
17029                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17030                    ps.setInstalled(true, user.getIdentifier());
17031                }
17032            } else {
17033                // This is a system app, so we assume that the
17034                // other users still have this package installed, so all
17035                // we need to do is clear this user's data and save that
17036                // it is uninstalled.
17037                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17038                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17039                    return false;
17040                }
17041                scheduleWritePackageRestrictionsLocked(user);
17042                return true;
17043            }
17044        }
17045
17046        // If we are deleting a composite package for all users, keep track
17047        // of result for each child.
17048        if (ps.childPackageNames != null && outInfo != null) {
17049            synchronized (mPackages) {
17050                final int childCount = ps.childPackageNames.size();
17051                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17052                for (int i = 0; i < childCount; i++) {
17053                    String childPackageName = ps.childPackageNames.get(i);
17054                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17055                    childInfo.removedPackage = childPackageName;
17056                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17057                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17058                    if (childPs != null) {
17059                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17060                    }
17061                }
17062            }
17063        }
17064
17065        boolean ret = false;
17066        if (isSystemApp(ps)) {
17067            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17068            // When an updated system application is deleted we delete the existing resources
17069            // as well and fall back to existing code in system partition
17070            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17071        } else {
17072            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17073            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17074                    outInfo, writeSettings, replacingPackage);
17075        }
17076
17077        // Take a note whether we deleted the package for all users
17078        if (outInfo != null) {
17079            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17080            if (outInfo.removedChildPackages != null) {
17081                synchronized (mPackages) {
17082                    final int childCount = outInfo.removedChildPackages.size();
17083                    for (int i = 0; i < childCount; i++) {
17084                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17085                        if (childInfo != null) {
17086                            childInfo.removedForAllUsers = mPackages.get(
17087                                    childInfo.removedPackage) == null;
17088                        }
17089                    }
17090                }
17091            }
17092            // If we uninstalled an update to a system app there may be some
17093            // child packages that appeared as they are declared in the system
17094            // app but were not declared in the update.
17095            if (isSystemApp(ps)) {
17096                synchronized (mPackages) {
17097                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17098                    final int childCount = (updatedPs.childPackageNames != null)
17099                            ? updatedPs.childPackageNames.size() : 0;
17100                    for (int i = 0; i < childCount; i++) {
17101                        String childPackageName = updatedPs.childPackageNames.get(i);
17102                        if (outInfo.removedChildPackages == null
17103                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17104                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17105                            if (childPs == null) {
17106                                continue;
17107                            }
17108                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17109                            installRes.name = childPackageName;
17110                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17111                            installRes.pkg = mPackages.get(childPackageName);
17112                            installRes.uid = childPs.pkg.applicationInfo.uid;
17113                            if (outInfo.appearedChildPackages == null) {
17114                                outInfo.appearedChildPackages = new ArrayMap<>();
17115                            }
17116                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17117                        }
17118                    }
17119                }
17120            }
17121        }
17122
17123        return ret;
17124    }
17125
17126    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17127        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17128                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17129        for (int nextUserId : userIds) {
17130            if (DEBUG_REMOVE) {
17131                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17132            }
17133            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17134                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
17135                    false /*hidden*/, false /*suspended*/, null, null, null,
17136                    false /*blockUninstall*/,
17137                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
17138                    PackageManager.INSTALL_REASON_UNKNOWN);
17139        }
17140    }
17141
17142    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17143            PackageRemovedInfo outInfo) {
17144        final PackageParser.Package pkg;
17145        synchronized (mPackages) {
17146            pkg = mPackages.get(ps.name);
17147        }
17148
17149        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17150                : new int[] {userId};
17151        for (int nextUserId : userIds) {
17152            if (DEBUG_REMOVE) {
17153                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17154                        + nextUserId);
17155            }
17156
17157            destroyAppDataLIF(pkg, userId,
17158                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17159            destroyAppProfilesLIF(pkg, userId);
17160            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17161            schedulePackageCleaning(ps.name, nextUserId, false);
17162            synchronized (mPackages) {
17163                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17164                    scheduleWritePackageRestrictionsLocked(nextUserId);
17165                }
17166                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17167            }
17168        }
17169
17170        if (outInfo != null) {
17171            outInfo.removedPackage = ps.name;
17172            outInfo.removedAppId = ps.appId;
17173            outInfo.removedUsers = userIds;
17174        }
17175
17176        return true;
17177    }
17178
17179    private final class ClearStorageConnection implements ServiceConnection {
17180        IMediaContainerService mContainerService;
17181
17182        @Override
17183        public void onServiceConnected(ComponentName name, IBinder service) {
17184            synchronized (this) {
17185                mContainerService = IMediaContainerService.Stub
17186                        .asInterface(Binder.allowBlocking(service));
17187                notifyAll();
17188            }
17189        }
17190
17191        @Override
17192        public void onServiceDisconnected(ComponentName name) {
17193        }
17194    }
17195
17196    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17197        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17198
17199        final boolean mounted;
17200        if (Environment.isExternalStorageEmulated()) {
17201            mounted = true;
17202        } else {
17203            final String status = Environment.getExternalStorageState();
17204
17205            mounted = status.equals(Environment.MEDIA_MOUNTED)
17206                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17207        }
17208
17209        if (!mounted) {
17210            return;
17211        }
17212
17213        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17214        int[] users;
17215        if (userId == UserHandle.USER_ALL) {
17216            users = sUserManager.getUserIds();
17217        } else {
17218            users = new int[] { userId };
17219        }
17220        final ClearStorageConnection conn = new ClearStorageConnection();
17221        if (mContext.bindServiceAsUser(
17222                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17223            try {
17224                for (int curUser : users) {
17225                    long timeout = SystemClock.uptimeMillis() + 5000;
17226                    synchronized (conn) {
17227                        long now;
17228                        while (conn.mContainerService == null &&
17229                                (now = SystemClock.uptimeMillis()) < timeout) {
17230                            try {
17231                                conn.wait(timeout - now);
17232                            } catch (InterruptedException e) {
17233                            }
17234                        }
17235                    }
17236                    if (conn.mContainerService == null) {
17237                        return;
17238                    }
17239
17240                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17241                    clearDirectory(conn.mContainerService,
17242                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17243                    if (allData) {
17244                        clearDirectory(conn.mContainerService,
17245                                userEnv.buildExternalStorageAppDataDirs(packageName));
17246                        clearDirectory(conn.mContainerService,
17247                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17248                    }
17249                }
17250            } finally {
17251                mContext.unbindService(conn);
17252            }
17253        }
17254    }
17255
17256    @Override
17257    public void clearApplicationProfileData(String packageName) {
17258        enforceSystemOrRoot("Only the system can clear all profile data");
17259
17260        final PackageParser.Package pkg;
17261        synchronized (mPackages) {
17262            pkg = mPackages.get(packageName);
17263        }
17264
17265        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17266            synchronized (mInstallLock) {
17267                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17268                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17269                        true /* removeBaseMarker */);
17270            }
17271        }
17272    }
17273
17274    @Override
17275    public void clearApplicationUserData(final String packageName,
17276            final IPackageDataObserver observer, final int userId) {
17277        mContext.enforceCallingOrSelfPermission(
17278                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17279
17280        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17281                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17282
17283        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17284            throw new SecurityException("Cannot clear data for a protected package: "
17285                    + packageName);
17286        }
17287        // Queue up an async operation since the package deletion may take a little while.
17288        mHandler.post(new Runnable() {
17289            public void run() {
17290                mHandler.removeCallbacks(this);
17291                final boolean succeeded;
17292                try (PackageFreezer freezer = freezePackage(packageName,
17293                        "clearApplicationUserData")) {
17294                    synchronized (mInstallLock) {
17295                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17296                    }
17297                    clearExternalStorageDataSync(packageName, userId, true);
17298                }
17299                if (succeeded) {
17300                    // invoke DeviceStorageMonitor's update method to clear any notifications
17301                    DeviceStorageMonitorInternal dsm = LocalServices
17302                            .getService(DeviceStorageMonitorInternal.class);
17303                    if (dsm != null) {
17304                        dsm.checkMemory();
17305                    }
17306                }
17307                if(observer != null) {
17308                    try {
17309                        observer.onRemoveCompleted(packageName, succeeded);
17310                    } catch (RemoteException e) {
17311                        Log.i(TAG, "Observer no longer exists.");
17312                    }
17313                } //end if observer
17314            } //end run
17315        });
17316    }
17317
17318    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17319        if (packageName == null) {
17320            Slog.w(TAG, "Attempt to delete null packageName.");
17321            return false;
17322        }
17323
17324        // Try finding details about the requested package
17325        PackageParser.Package pkg;
17326        synchronized (mPackages) {
17327            pkg = mPackages.get(packageName);
17328            if (pkg == null) {
17329                final PackageSetting ps = mSettings.mPackages.get(packageName);
17330                if (ps != null) {
17331                    pkg = ps.pkg;
17332                }
17333            }
17334
17335            if (pkg == null) {
17336                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17337                return false;
17338            }
17339
17340            PackageSetting ps = (PackageSetting) pkg.mExtras;
17341            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17342        }
17343
17344        clearAppDataLIF(pkg, userId,
17345                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17346
17347        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17348        removeKeystoreDataIfNeeded(userId, appId);
17349
17350        UserManagerInternal umInternal = getUserManagerInternal();
17351        final int flags;
17352        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17353            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17354        } else if (umInternal.isUserRunning(userId)) {
17355            flags = StorageManager.FLAG_STORAGE_DE;
17356        } else {
17357            flags = 0;
17358        }
17359        prepareAppDataContentsLIF(pkg, userId, flags);
17360
17361        return true;
17362    }
17363
17364    /**
17365     * Reverts user permission state changes (permissions and flags) in
17366     * all packages for a given user.
17367     *
17368     * @param userId The device user for which to do a reset.
17369     */
17370    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17371        final int packageCount = mPackages.size();
17372        for (int i = 0; i < packageCount; i++) {
17373            PackageParser.Package pkg = mPackages.valueAt(i);
17374            PackageSetting ps = (PackageSetting) pkg.mExtras;
17375            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17376        }
17377    }
17378
17379    private void resetNetworkPolicies(int userId) {
17380        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17381    }
17382
17383    /**
17384     * Reverts user permission state changes (permissions and flags).
17385     *
17386     * @param ps The package for which to reset.
17387     * @param userId The device user for which to do a reset.
17388     */
17389    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17390            final PackageSetting ps, final int userId) {
17391        if (ps.pkg == null) {
17392            return;
17393        }
17394
17395        // These are flags that can change base on user actions.
17396        final int userSettableMask = FLAG_PERMISSION_USER_SET
17397                | FLAG_PERMISSION_USER_FIXED
17398                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17399                | FLAG_PERMISSION_REVIEW_REQUIRED;
17400
17401        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17402                | FLAG_PERMISSION_POLICY_FIXED;
17403
17404        boolean writeInstallPermissions = false;
17405        boolean writeRuntimePermissions = false;
17406
17407        final int permissionCount = ps.pkg.requestedPermissions.size();
17408        for (int i = 0; i < permissionCount; i++) {
17409            String permission = ps.pkg.requestedPermissions.get(i);
17410
17411            BasePermission bp = mSettings.mPermissions.get(permission);
17412            if (bp == null) {
17413                continue;
17414            }
17415
17416            // If shared user we just reset the state to which only this app contributed.
17417            if (ps.sharedUser != null) {
17418                boolean used = false;
17419                final int packageCount = ps.sharedUser.packages.size();
17420                for (int j = 0; j < packageCount; j++) {
17421                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17422                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17423                            && pkg.pkg.requestedPermissions.contains(permission)) {
17424                        used = true;
17425                        break;
17426                    }
17427                }
17428                if (used) {
17429                    continue;
17430                }
17431            }
17432
17433            PermissionsState permissionsState = ps.getPermissionsState();
17434
17435            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17436
17437            // Always clear the user settable flags.
17438            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17439                    bp.name) != null;
17440            // If permission review is enabled and this is a legacy app, mark the
17441            // permission as requiring a review as this is the initial state.
17442            int flags = 0;
17443            if (mPermissionReviewRequired
17444                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17445                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17446            }
17447            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17448                if (hasInstallState) {
17449                    writeInstallPermissions = true;
17450                } else {
17451                    writeRuntimePermissions = true;
17452                }
17453            }
17454
17455            // Below is only runtime permission handling.
17456            if (!bp.isRuntime()) {
17457                continue;
17458            }
17459
17460            // Never clobber system or policy.
17461            if ((oldFlags & policyOrSystemFlags) != 0) {
17462                continue;
17463            }
17464
17465            // If this permission was granted by default, make sure it is.
17466            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17467                if (permissionsState.grantRuntimePermission(bp, userId)
17468                        != PERMISSION_OPERATION_FAILURE) {
17469                    writeRuntimePermissions = true;
17470                }
17471            // If permission review is enabled the permissions for a legacy apps
17472            // are represented as constantly granted runtime ones, so don't revoke.
17473            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17474                // Otherwise, reset the permission.
17475                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17476                switch (revokeResult) {
17477                    case PERMISSION_OPERATION_SUCCESS:
17478                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17479                        writeRuntimePermissions = true;
17480                        final int appId = ps.appId;
17481                        mHandler.post(new Runnable() {
17482                            @Override
17483                            public void run() {
17484                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17485                            }
17486                        });
17487                    } break;
17488                }
17489            }
17490        }
17491
17492        // Synchronously write as we are taking permissions away.
17493        if (writeRuntimePermissions) {
17494            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17495        }
17496
17497        // Synchronously write as we are taking permissions away.
17498        if (writeInstallPermissions) {
17499            mSettings.writeLPr();
17500        }
17501    }
17502
17503    /**
17504     * Remove entries from the keystore daemon. Will only remove it if the
17505     * {@code appId} is valid.
17506     */
17507    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17508        if (appId < 0) {
17509            return;
17510        }
17511
17512        final KeyStore keyStore = KeyStore.getInstance();
17513        if (keyStore != null) {
17514            if (userId == UserHandle.USER_ALL) {
17515                for (final int individual : sUserManager.getUserIds()) {
17516                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17517                }
17518            } else {
17519                keyStore.clearUid(UserHandle.getUid(userId, appId));
17520            }
17521        } else {
17522            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17523        }
17524    }
17525
17526    @Override
17527    public void deleteApplicationCacheFiles(final String packageName,
17528            final IPackageDataObserver observer) {
17529        final int userId = UserHandle.getCallingUserId();
17530        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17531    }
17532
17533    @Override
17534    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17535            final IPackageDataObserver observer) {
17536        mContext.enforceCallingOrSelfPermission(
17537                android.Manifest.permission.DELETE_CACHE_FILES, null);
17538        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17539                /* requireFullPermission= */ true, /* checkShell= */ false,
17540                "delete application cache files");
17541
17542        final PackageParser.Package pkg;
17543        synchronized (mPackages) {
17544            pkg = mPackages.get(packageName);
17545        }
17546
17547        // Queue up an async operation since the package deletion may take a little while.
17548        mHandler.post(new Runnable() {
17549            public void run() {
17550                synchronized (mInstallLock) {
17551                    final int flags = StorageManager.FLAG_STORAGE_DE
17552                            | StorageManager.FLAG_STORAGE_CE;
17553                    // We're only clearing cache files, so we don't care if the
17554                    // app is unfrozen and still able to run
17555                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17556                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17557                }
17558                clearExternalStorageDataSync(packageName, userId, false);
17559                if (observer != null) {
17560                    try {
17561                        observer.onRemoveCompleted(packageName, true);
17562                    } catch (RemoteException e) {
17563                        Log.i(TAG, "Observer no longer exists.");
17564                    }
17565                }
17566            }
17567        });
17568    }
17569
17570    @Override
17571    public void getPackageSizeInfo(final String packageName, int userHandle,
17572            final IPackageStatsObserver observer) {
17573        mContext.enforceCallingOrSelfPermission(
17574                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17575        if (packageName == null) {
17576            throw new IllegalArgumentException("Attempt to get size of null packageName");
17577        }
17578
17579        PackageStats stats = new PackageStats(packageName, userHandle);
17580
17581        /*
17582         * Queue up an async operation since the package measurement may take a
17583         * little while.
17584         */
17585        Message msg = mHandler.obtainMessage(INIT_COPY);
17586        msg.obj = new MeasureParams(stats, observer);
17587        mHandler.sendMessage(msg);
17588    }
17589
17590    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17591        final PackageSetting ps;
17592        synchronized (mPackages) {
17593            ps = mSettings.mPackages.get(packageName);
17594            if (ps == null) {
17595                Slog.w(TAG, "Failed to find settings for " + packageName);
17596                return false;
17597            }
17598        }
17599
17600        final String[] packageNames = { packageName };
17601        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
17602        final String[] codePaths = { ps.codePathString };
17603
17604        try {
17605            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
17606                    ps.appId, ceDataInodes, codePaths, stats);
17607
17608            // For now, ignore code size of packages on system partition
17609            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17610                stats.codeSize = 0;
17611            }
17612
17613            // External clients expect these to be tracked separately
17614            stats.dataSize -= stats.cacheSize;
17615
17616        } catch (InstallerException e) {
17617            Slog.w(TAG, String.valueOf(e));
17618            return false;
17619        }
17620
17621        return true;
17622    }
17623
17624    private int getUidTargetSdkVersionLockedLPr(int uid) {
17625        Object obj = mSettings.getUserIdLPr(uid);
17626        if (obj instanceof SharedUserSetting) {
17627            final SharedUserSetting sus = (SharedUserSetting) obj;
17628            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17629            final Iterator<PackageSetting> it = sus.packages.iterator();
17630            while (it.hasNext()) {
17631                final PackageSetting ps = it.next();
17632                if (ps.pkg != null) {
17633                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17634                    if (v < vers) vers = v;
17635                }
17636            }
17637            return vers;
17638        } else if (obj instanceof PackageSetting) {
17639            final PackageSetting ps = (PackageSetting) obj;
17640            if (ps.pkg != null) {
17641                return ps.pkg.applicationInfo.targetSdkVersion;
17642            }
17643        }
17644        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17645    }
17646
17647    @Override
17648    public void addPreferredActivity(IntentFilter filter, int match,
17649            ComponentName[] set, ComponentName activity, int userId) {
17650        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17651                "Adding preferred");
17652    }
17653
17654    private void addPreferredActivityInternal(IntentFilter filter, int match,
17655            ComponentName[] set, ComponentName activity, boolean always, int userId,
17656            String opname) {
17657        // writer
17658        int callingUid = Binder.getCallingUid();
17659        enforceCrossUserPermission(callingUid, userId,
17660                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17661        if (filter.countActions() == 0) {
17662            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17663            return;
17664        }
17665        synchronized (mPackages) {
17666            if (mContext.checkCallingOrSelfPermission(
17667                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17668                    != PackageManager.PERMISSION_GRANTED) {
17669                if (getUidTargetSdkVersionLockedLPr(callingUid)
17670                        < Build.VERSION_CODES.FROYO) {
17671                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17672                            + callingUid);
17673                    return;
17674                }
17675                mContext.enforceCallingOrSelfPermission(
17676                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17677            }
17678
17679            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17680            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17681                    + userId + ":");
17682            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17683            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17684            scheduleWritePackageRestrictionsLocked(userId);
17685            postPreferredActivityChangedBroadcast(userId);
17686        }
17687    }
17688
17689    private void postPreferredActivityChangedBroadcast(int userId) {
17690        mHandler.post(() -> {
17691            final IActivityManager am = ActivityManager.getService();
17692            if (am == null) {
17693                return;
17694            }
17695
17696            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17697            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17698            try {
17699                am.broadcastIntent(null, intent, null, null,
17700                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17701                        null, false, false, userId);
17702            } catch (RemoteException e) {
17703            }
17704        });
17705    }
17706
17707    @Override
17708    public void replacePreferredActivity(IntentFilter filter, int match,
17709            ComponentName[] set, ComponentName activity, int userId) {
17710        if (filter.countActions() != 1) {
17711            throw new IllegalArgumentException(
17712                    "replacePreferredActivity expects filter to have only 1 action.");
17713        }
17714        if (filter.countDataAuthorities() != 0
17715                || filter.countDataPaths() != 0
17716                || filter.countDataSchemes() > 1
17717                || filter.countDataTypes() != 0) {
17718            throw new IllegalArgumentException(
17719                    "replacePreferredActivity expects filter to have no data authorities, " +
17720                    "paths, or types; and at most one scheme.");
17721        }
17722
17723        final int callingUid = Binder.getCallingUid();
17724        enforceCrossUserPermission(callingUid, userId,
17725                true /* requireFullPermission */, false /* checkShell */,
17726                "replace preferred activity");
17727        synchronized (mPackages) {
17728            if (mContext.checkCallingOrSelfPermission(
17729                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17730                    != PackageManager.PERMISSION_GRANTED) {
17731                if (getUidTargetSdkVersionLockedLPr(callingUid)
17732                        < Build.VERSION_CODES.FROYO) {
17733                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17734                            + Binder.getCallingUid());
17735                    return;
17736                }
17737                mContext.enforceCallingOrSelfPermission(
17738                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17739            }
17740
17741            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17742            if (pir != null) {
17743                // Get all of the existing entries that exactly match this filter.
17744                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17745                if (existing != null && existing.size() == 1) {
17746                    PreferredActivity cur = existing.get(0);
17747                    if (DEBUG_PREFERRED) {
17748                        Slog.i(TAG, "Checking replace of preferred:");
17749                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17750                        if (!cur.mPref.mAlways) {
17751                            Slog.i(TAG, "  -- CUR; not mAlways!");
17752                        } else {
17753                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17754                            Slog.i(TAG, "  -- CUR: mSet="
17755                                    + Arrays.toString(cur.mPref.mSetComponents));
17756                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17757                            Slog.i(TAG, "  -- NEW: mMatch="
17758                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17759                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17760                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17761                        }
17762                    }
17763                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17764                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17765                            && cur.mPref.sameSet(set)) {
17766                        // Setting the preferred activity to what it happens to be already
17767                        if (DEBUG_PREFERRED) {
17768                            Slog.i(TAG, "Replacing with same preferred activity "
17769                                    + cur.mPref.mShortComponent + " for user "
17770                                    + userId + ":");
17771                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17772                        }
17773                        return;
17774                    }
17775                }
17776
17777                if (existing != null) {
17778                    if (DEBUG_PREFERRED) {
17779                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17780                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17781                    }
17782                    for (int i = 0; i < existing.size(); i++) {
17783                        PreferredActivity pa = existing.get(i);
17784                        if (DEBUG_PREFERRED) {
17785                            Slog.i(TAG, "Removing existing preferred activity "
17786                                    + pa.mPref.mComponent + ":");
17787                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17788                        }
17789                        pir.removeFilter(pa);
17790                    }
17791                }
17792            }
17793            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17794                    "Replacing preferred");
17795        }
17796    }
17797
17798    @Override
17799    public void clearPackagePreferredActivities(String packageName) {
17800        final int uid = Binder.getCallingUid();
17801        // writer
17802        synchronized (mPackages) {
17803            PackageParser.Package pkg = mPackages.get(packageName);
17804            if (pkg == null || pkg.applicationInfo.uid != uid) {
17805                if (mContext.checkCallingOrSelfPermission(
17806                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17807                        != PackageManager.PERMISSION_GRANTED) {
17808                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17809                            < Build.VERSION_CODES.FROYO) {
17810                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17811                                + Binder.getCallingUid());
17812                        return;
17813                    }
17814                    mContext.enforceCallingOrSelfPermission(
17815                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17816                }
17817            }
17818
17819            int user = UserHandle.getCallingUserId();
17820            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17821                scheduleWritePackageRestrictionsLocked(user);
17822            }
17823        }
17824    }
17825
17826    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17827    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17828        ArrayList<PreferredActivity> removed = null;
17829        boolean changed = false;
17830        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17831            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17832            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17833            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17834                continue;
17835            }
17836            Iterator<PreferredActivity> it = pir.filterIterator();
17837            while (it.hasNext()) {
17838                PreferredActivity pa = it.next();
17839                // Mark entry for removal only if it matches the package name
17840                // and the entry is of type "always".
17841                if (packageName == null ||
17842                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17843                                && pa.mPref.mAlways)) {
17844                    if (removed == null) {
17845                        removed = new ArrayList<PreferredActivity>();
17846                    }
17847                    removed.add(pa);
17848                }
17849            }
17850            if (removed != null) {
17851                for (int j=0; j<removed.size(); j++) {
17852                    PreferredActivity pa = removed.get(j);
17853                    pir.removeFilter(pa);
17854                }
17855                changed = true;
17856            }
17857        }
17858        if (changed) {
17859            postPreferredActivityChangedBroadcast(userId);
17860        }
17861        return changed;
17862    }
17863
17864    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17865    private void clearIntentFilterVerificationsLPw(int userId) {
17866        final int packageCount = mPackages.size();
17867        for (int i = 0; i < packageCount; i++) {
17868            PackageParser.Package pkg = mPackages.valueAt(i);
17869            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17870        }
17871    }
17872
17873    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17874    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17875        if (userId == UserHandle.USER_ALL) {
17876            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17877                    sUserManager.getUserIds())) {
17878                for (int oneUserId : sUserManager.getUserIds()) {
17879                    scheduleWritePackageRestrictionsLocked(oneUserId);
17880                }
17881            }
17882        } else {
17883            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17884                scheduleWritePackageRestrictionsLocked(userId);
17885            }
17886        }
17887    }
17888
17889    void clearDefaultBrowserIfNeeded(String packageName) {
17890        for (int oneUserId : sUserManager.getUserIds()) {
17891            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17892            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17893            if (packageName.equals(defaultBrowserPackageName)) {
17894                setDefaultBrowserPackageName(null, oneUserId);
17895            }
17896        }
17897    }
17898
17899    @Override
17900    public void resetApplicationPreferences(int userId) {
17901        mContext.enforceCallingOrSelfPermission(
17902                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17903        final long identity = Binder.clearCallingIdentity();
17904        // writer
17905        try {
17906            synchronized (mPackages) {
17907                clearPackagePreferredActivitiesLPw(null, userId);
17908                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17909                // TODO: We have to reset the default SMS and Phone. This requires
17910                // significant refactoring to keep all default apps in the package
17911                // manager (cleaner but more work) or have the services provide
17912                // callbacks to the package manager to request a default app reset.
17913                applyFactoryDefaultBrowserLPw(userId);
17914                clearIntentFilterVerificationsLPw(userId);
17915                primeDomainVerificationsLPw(userId);
17916                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17917                scheduleWritePackageRestrictionsLocked(userId);
17918            }
17919            resetNetworkPolicies(userId);
17920        } finally {
17921            Binder.restoreCallingIdentity(identity);
17922        }
17923    }
17924
17925    @Override
17926    public int getPreferredActivities(List<IntentFilter> outFilters,
17927            List<ComponentName> outActivities, String packageName) {
17928
17929        int num = 0;
17930        final int userId = UserHandle.getCallingUserId();
17931        // reader
17932        synchronized (mPackages) {
17933            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17934            if (pir != null) {
17935                final Iterator<PreferredActivity> it = pir.filterIterator();
17936                while (it.hasNext()) {
17937                    final PreferredActivity pa = it.next();
17938                    if (packageName == null
17939                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17940                                    && pa.mPref.mAlways)) {
17941                        if (outFilters != null) {
17942                            outFilters.add(new IntentFilter(pa));
17943                        }
17944                        if (outActivities != null) {
17945                            outActivities.add(pa.mPref.mComponent);
17946                        }
17947                    }
17948                }
17949            }
17950        }
17951
17952        return num;
17953    }
17954
17955    @Override
17956    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17957            int userId) {
17958        int callingUid = Binder.getCallingUid();
17959        if (callingUid != Process.SYSTEM_UID) {
17960            throw new SecurityException(
17961                    "addPersistentPreferredActivity can only be run by the system");
17962        }
17963        if (filter.countActions() == 0) {
17964            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17965            return;
17966        }
17967        synchronized (mPackages) {
17968            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17969                    ":");
17970            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17971            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17972                    new PersistentPreferredActivity(filter, activity));
17973            scheduleWritePackageRestrictionsLocked(userId);
17974            postPreferredActivityChangedBroadcast(userId);
17975        }
17976    }
17977
17978    @Override
17979    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17980        int callingUid = Binder.getCallingUid();
17981        if (callingUid != Process.SYSTEM_UID) {
17982            throw new SecurityException(
17983                    "clearPackagePersistentPreferredActivities can only be run by the system");
17984        }
17985        ArrayList<PersistentPreferredActivity> removed = null;
17986        boolean changed = false;
17987        synchronized (mPackages) {
17988            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17989                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17990                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17991                        .valueAt(i);
17992                if (userId != thisUserId) {
17993                    continue;
17994                }
17995                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17996                while (it.hasNext()) {
17997                    PersistentPreferredActivity ppa = it.next();
17998                    // Mark entry for removal only if it matches the package name.
17999                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18000                        if (removed == null) {
18001                            removed = new ArrayList<PersistentPreferredActivity>();
18002                        }
18003                        removed.add(ppa);
18004                    }
18005                }
18006                if (removed != null) {
18007                    for (int j=0; j<removed.size(); j++) {
18008                        PersistentPreferredActivity ppa = removed.get(j);
18009                        ppir.removeFilter(ppa);
18010                    }
18011                    changed = true;
18012                }
18013            }
18014
18015            if (changed) {
18016                scheduleWritePackageRestrictionsLocked(userId);
18017                postPreferredActivityChangedBroadcast(userId);
18018            }
18019        }
18020    }
18021
18022    /**
18023     * Common machinery for picking apart a restored XML blob and passing
18024     * it to a caller-supplied functor to be applied to the running system.
18025     */
18026    private void restoreFromXml(XmlPullParser parser, int userId,
18027            String expectedStartTag, BlobXmlRestorer functor)
18028            throws IOException, XmlPullParserException {
18029        int type;
18030        while ((type = parser.next()) != XmlPullParser.START_TAG
18031                && type != XmlPullParser.END_DOCUMENT) {
18032        }
18033        if (type != XmlPullParser.START_TAG) {
18034            // oops didn't find a start tag?!
18035            if (DEBUG_BACKUP) {
18036                Slog.e(TAG, "Didn't find start tag during restore");
18037            }
18038            return;
18039        }
18040Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18041        // this is supposed to be TAG_PREFERRED_BACKUP
18042        if (!expectedStartTag.equals(parser.getName())) {
18043            if (DEBUG_BACKUP) {
18044                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18045            }
18046            return;
18047        }
18048
18049        // skip interfering stuff, then we're aligned with the backing implementation
18050        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18051Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18052        functor.apply(parser, userId);
18053    }
18054
18055    private interface BlobXmlRestorer {
18056        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18057    }
18058
18059    /**
18060     * Non-Binder method, support for the backup/restore mechanism: write the
18061     * full set of preferred activities in its canonical XML format.  Returns the
18062     * XML output as a byte array, or null if there is none.
18063     */
18064    @Override
18065    public byte[] getPreferredActivityBackup(int userId) {
18066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18067            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18068        }
18069
18070        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18071        try {
18072            final XmlSerializer serializer = new FastXmlSerializer();
18073            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18074            serializer.startDocument(null, true);
18075            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18076
18077            synchronized (mPackages) {
18078                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18079            }
18080
18081            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18082            serializer.endDocument();
18083            serializer.flush();
18084        } catch (Exception e) {
18085            if (DEBUG_BACKUP) {
18086                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18087            }
18088            return null;
18089        }
18090
18091        return dataStream.toByteArray();
18092    }
18093
18094    @Override
18095    public void restorePreferredActivities(byte[] backup, int userId) {
18096        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18097            throw new SecurityException("Only the system may call restorePreferredActivities()");
18098        }
18099
18100        try {
18101            final XmlPullParser parser = Xml.newPullParser();
18102            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18103            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18104                    new BlobXmlRestorer() {
18105                        @Override
18106                        public void apply(XmlPullParser parser, int userId)
18107                                throws XmlPullParserException, IOException {
18108                            synchronized (mPackages) {
18109                                mSettings.readPreferredActivitiesLPw(parser, userId);
18110                            }
18111                        }
18112                    } );
18113        } catch (Exception e) {
18114            if (DEBUG_BACKUP) {
18115                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18116            }
18117        }
18118    }
18119
18120    /**
18121     * Non-Binder method, support for the backup/restore mechanism: write the
18122     * default browser (etc) settings in its canonical XML format.  Returns the default
18123     * browser XML representation as a byte array, or null if there is none.
18124     */
18125    @Override
18126    public byte[] getDefaultAppsBackup(int userId) {
18127        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18128            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18129        }
18130
18131        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18132        try {
18133            final XmlSerializer serializer = new FastXmlSerializer();
18134            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18135            serializer.startDocument(null, true);
18136            serializer.startTag(null, TAG_DEFAULT_APPS);
18137
18138            synchronized (mPackages) {
18139                mSettings.writeDefaultAppsLPr(serializer, userId);
18140            }
18141
18142            serializer.endTag(null, TAG_DEFAULT_APPS);
18143            serializer.endDocument();
18144            serializer.flush();
18145        } catch (Exception e) {
18146            if (DEBUG_BACKUP) {
18147                Slog.e(TAG, "Unable to write default apps for backup", e);
18148            }
18149            return null;
18150        }
18151
18152        return dataStream.toByteArray();
18153    }
18154
18155    @Override
18156    public void restoreDefaultApps(byte[] backup, int userId) {
18157        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18158            throw new SecurityException("Only the system may call restoreDefaultApps()");
18159        }
18160
18161        try {
18162            final XmlPullParser parser = Xml.newPullParser();
18163            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18164            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18165                    new BlobXmlRestorer() {
18166                        @Override
18167                        public void apply(XmlPullParser parser, int userId)
18168                                throws XmlPullParserException, IOException {
18169                            synchronized (mPackages) {
18170                                mSettings.readDefaultAppsLPw(parser, userId);
18171                            }
18172                        }
18173                    } );
18174        } catch (Exception e) {
18175            if (DEBUG_BACKUP) {
18176                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18177            }
18178        }
18179    }
18180
18181    @Override
18182    public byte[] getIntentFilterVerificationBackup(int userId) {
18183        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18184            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18185        }
18186
18187        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18188        try {
18189            final XmlSerializer serializer = new FastXmlSerializer();
18190            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18191            serializer.startDocument(null, true);
18192            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18193
18194            synchronized (mPackages) {
18195                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18196            }
18197
18198            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18199            serializer.endDocument();
18200            serializer.flush();
18201        } catch (Exception e) {
18202            if (DEBUG_BACKUP) {
18203                Slog.e(TAG, "Unable to write default apps for backup", e);
18204            }
18205            return null;
18206        }
18207
18208        return dataStream.toByteArray();
18209    }
18210
18211    @Override
18212    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18213        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18214            throw new SecurityException("Only the system may call restorePreferredActivities()");
18215        }
18216
18217        try {
18218            final XmlPullParser parser = Xml.newPullParser();
18219            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18220            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18221                    new BlobXmlRestorer() {
18222                        @Override
18223                        public void apply(XmlPullParser parser, int userId)
18224                                throws XmlPullParserException, IOException {
18225                            synchronized (mPackages) {
18226                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18227                                mSettings.writeLPr();
18228                            }
18229                        }
18230                    } );
18231        } catch (Exception e) {
18232            if (DEBUG_BACKUP) {
18233                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18234            }
18235        }
18236    }
18237
18238    @Override
18239    public byte[] getPermissionGrantBackup(int userId) {
18240        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18241            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18242        }
18243
18244        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18245        try {
18246            final XmlSerializer serializer = new FastXmlSerializer();
18247            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18248            serializer.startDocument(null, true);
18249            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18250
18251            synchronized (mPackages) {
18252                serializeRuntimePermissionGrantsLPr(serializer, userId);
18253            }
18254
18255            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18256            serializer.endDocument();
18257            serializer.flush();
18258        } catch (Exception e) {
18259            if (DEBUG_BACKUP) {
18260                Slog.e(TAG, "Unable to write default apps for backup", e);
18261            }
18262            return null;
18263        }
18264
18265        return dataStream.toByteArray();
18266    }
18267
18268    @Override
18269    public void restorePermissionGrants(byte[] backup, int userId) {
18270        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18271            throw new SecurityException("Only the system may call restorePermissionGrants()");
18272        }
18273
18274        try {
18275            final XmlPullParser parser = Xml.newPullParser();
18276            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18277            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18278                    new BlobXmlRestorer() {
18279                        @Override
18280                        public void apply(XmlPullParser parser, int userId)
18281                                throws XmlPullParserException, IOException {
18282                            synchronized (mPackages) {
18283                                processRestoredPermissionGrantsLPr(parser, userId);
18284                            }
18285                        }
18286                    } );
18287        } catch (Exception e) {
18288            if (DEBUG_BACKUP) {
18289                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18290            }
18291        }
18292    }
18293
18294    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18295            throws IOException {
18296        serializer.startTag(null, TAG_ALL_GRANTS);
18297
18298        final int N = mSettings.mPackages.size();
18299        for (int i = 0; i < N; i++) {
18300            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18301            boolean pkgGrantsKnown = false;
18302
18303            PermissionsState packagePerms = ps.getPermissionsState();
18304
18305            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18306                final int grantFlags = state.getFlags();
18307                // only look at grants that are not system/policy fixed
18308                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18309                    final boolean isGranted = state.isGranted();
18310                    // And only back up the user-twiddled state bits
18311                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18312                        final String packageName = mSettings.mPackages.keyAt(i);
18313                        if (!pkgGrantsKnown) {
18314                            serializer.startTag(null, TAG_GRANT);
18315                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18316                            pkgGrantsKnown = true;
18317                        }
18318
18319                        final boolean userSet =
18320                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18321                        final boolean userFixed =
18322                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18323                        final boolean revoke =
18324                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18325
18326                        serializer.startTag(null, TAG_PERMISSION);
18327                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18328                        if (isGranted) {
18329                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18330                        }
18331                        if (userSet) {
18332                            serializer.attribute(null, ATTR_USER_SET, "true");
18333                        }
18334                        if (userFixed) {
18335                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18336                        }
18337                        if (revoke) {
18338                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18339                        }
18340                        serializer.endTag(null, TAG_PERMISSION);
18341                    }
18342                }
18343            }
18344
18345            if (pkgGrantsKnown) {
18346                serializer.endTag(null, TAG_GRANT);
18347            }
18348        }
18349
18350        serializer.endTag(null, TAG_ALL_GRANTS);
18351    }
18352
18353    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18354            throws XmlPullParserException, IOException {
18355        String pkgName = null;
18356        int outerDepth = parser.getDepth();
18357        int type;
18358        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18359                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18360            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18361                continue;
18362            }
18363
18364            final String tagName = parser.getName();
18365            if (tagName.equals(TAG_GRANT)) {
18366                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18367                if (DEBUG_BACKUP) {
18368                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18369                }
18370            } else if (tagName.equals(TAG_PERMISSION)) {
18371
18372                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18373                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18374
18375                int newFlagSet = 0;
18376                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18377                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18378                }
18379                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18380                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18381                }
18382                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18383                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18384                }
18385                if (DEBUG_BACKUP) {
18386                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18387                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18388                }
18389                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18390                if (ps != null) {
18391                    // Already installed so we apply the grant immediately
18392                    if (DEBUG_BACKUP) {
18393                        Slog.v(TAG, "        + already installed; applying");
18394                    }
18395                    PermissionsState perms = ps.getPermissionsState();
18396                    BasePermission bp = mSettings.mPermissions.get(permName);
18397                    if (bp != null) {
18398                        if (isGranted) {
18399                            perms.grantRuntimePermission(bp, userId);
18400                        }
18401                        if (newFlagSet != 0) {
18402                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18403                        }
18404                    }
18405                } else {
18406                    // Need to wait for post-restore install to apply the grant
18407                    if (DEBUG_BACKUP) {
18408                        Slog.v(TAG, "        - not yet installed; saving for later");
18409                    }
18410                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18411                            isGranted, newFlagSet, userId);
18412                }
18413            } else {
18414                PackageManagerService.reportSettingsProblem(Log.WARN,
18415                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18416                XmlUtils.skipCurrentTag(parser);
18417            }
18418        }
18419
18420        scheduleWriteSettingsLocked();
18421        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18422    }
18423
18424    @Override
18425    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18426            int sourceUserId, int targetUserId, int flags) {
18427        mContext.enforceCallingOrSelfPermission(
18428                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18429        int callingUid = Binder.getCallingUid();
18430        enforceOwnerRights(ownerPackage, callingUid);
18431        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18432        if (intentFilter.countActions() == 0) {
18433            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18434            return;
18435        }
18436        synchronized (mPackages) {
18437            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18438                    ownerPackage, targetUserId, flags);
18439            CrossProfileIntentResolver resolver =
18440                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18441            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18442            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18443            if (existing != null) {
18444                int size = existing.size();
18445                for (int i = 0; i < size; i++) {
18446                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18447                        return;
18448                    }
18449                }
18450            }
18451            resolver.addFilter(newFilter);
18452            scheduleWritePackageRestrictionsLocked(sourceUserId);
18453        }
18454    }
18455
18456    @Override
18457    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18458        mContext.enforceCallingOrSelfPermission(
18459                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18460        int callingUid = Binder.getCallingUid();
18461        enforceOwnerRights(ownerPackage, callingUid);
18462        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18463        synchronized (mPackages) {
18464            CrossProfileIntentResolver resolver =
18465                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18466            ArraySet<CrossProfileIntentFilter> set =
18467                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18468            for (CrossProfileIntentFilter filter : set) {
18469                if (filter.getOwnerPackage().equals(ownerPackage)) {
18470                    resolver.removeFilter(filter);
18471                }
18472            }
18473            scheduleWritePackageRestrictionsLocked(sourceUserId);
18474        }
18475    }
18476
18477    // Enforcing that callingUid is owning pkg on userId
18478    private void enforceOwnerRights(String pkg, int callingUid) {
18479        // The system owns everything.
18480        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18481            return;
18482        }
18483        int callingUserId = UserHandle.getUserId(callingUid);
18484        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18485        if (pi == null) {
18486            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18487                    + callingUserId);
18488        }
18489        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18490            throw new SecurityException("Calling uid " + callingUid
18491                    + " does not own package " + pkg);
18492        }
18493    }
18494
18495    @Override
18496    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18497        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18498    }
18499
18500    private Intent getHomeIntent() {
18501        Intent intent = new Intent(Intent.ACTION_MAIN);
18502        intent.addCategory(Intent.CATEGORY_HOME);
18503        intent.addCategory(Intent.CATEGORY_DEFAULT);
18504        return intent;
18505    }
18506
18507    private IntentFilter getHomeFilter() {
18508        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18509        filter.addCategory(Intent.CATEGORY_HOME);
18510        filter.addCategory(Intent.CATEGORY_DEFAULT);
18511        return filter;
18512    }
18513
18514    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18515            int userId) {
18516        Intent intent  = getHomeIntent();
18517        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18518                PackageManager.GET_META_DATA, userId);
18519        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18520                true, false, false, userId);
18521
18522        allHomeCandidates.clear();
18523        if (list != null) {
18524            for (ResolveInfo ri : list) {
18525                allHomeCandidates.add(ri);
18526            }
18527        }
18528        return (preferred == null || preferred.activityInfo == null)
18529                ? null
18530                : new ComponentName(preferred.activityInfo.packageName,
18531                        preferred.activityInfo.name);
18532    }
18533
18534    @Override
18535    public void setHomeActivity(ComponentName comp, int userId) {
18536        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18537        getHomeActivitiesAsUser(homeActivities, userId);
18538
18539        boolean found = false;
18540
18541        final int size = homeActivities.size();
18542        final ComponentName[] set = new ComponentName[size];
18543        for (int i = 0; i < size; i++) {
18544            final ResolveInfo candidate = homeActivities.get(i);
18545            final ActivityInfo info = candidate.activityInfo;
18546            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18547            set[i] = activityName;
18548            if (!found && activityName.equals(comp)) {
18549                found = true;
18550            }
18551        }
18552        if (!found) {
18553            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18554                    + userId);
18555        }
18556        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18557                set, comp, userId);
18558    }
18559
18560    private @Nullable String getSetupWizardPackageName() {
18561        final Intent intent = new Intent(Intent.ACTION_MAIN);
18562        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18563
18564        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18565                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18566                        | MATCH_DISABLED_COMPONENTS,
18567                UserHandle.myUserId());
18568        if (matches.size() == 1) {
18569            return matches.get(0).getComponentInfo().packageName;
18570        } else {
18571            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18572                    + ": matches=" + matches);
18573            return null;
18574        }
18575    }
18576
18577    private @Nullable String getStorageManagerPackageName() {
18578        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18579
18580        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18581                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18582                        | MATCH_DISABLED_COMPONENTS,
18583                UserHandle.myUserId());
18584        if (matches.size() == 1) {
18585            return matches.get(0).getComponentInfo().packageName;
18586        } else {
18587            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18588                    + matches.size() + ": matches=" + matches);
18589            return null;
18590        }
18591    }
18592
18593    @Override
18594    public void setApplicationEnabledSetting(String appPackageName,
18595            int newState, int flags, int userId, String callingPackage) {
18596        if (!sUserManager.exists(userId)) return;
18597        if (callingPackage == null) {
18598            callingPackage = Integer.toString(Binder.getCallingUid());
18599        }
18600        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18601    }
18602
18603    @Override
18604    public void setComponentEnabledSetting(ComponentName componentName,
18605            int newState, int flags, int userId) {
18606        if (!sUserManager.exists(userId)) return;
18607        setEnabledSetting(componentName.getPackageName(),
18608                componentName.getClassName(), newState, flags, userId, null);
18609    }
18610
18611    private void setEnabledSetting(final String packageName, String className, int newState,
18612            final int flags, int userId, String callingPackage) {
18613        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18614              || newState == COMPONENT_ENABLED_STATE_ENABLED
18615              || newState == COMPONENT_ENABLED_STATE_DISABLED
18616              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18617              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18618            throw new IllegalArgumentException("Invalid new component state: "
18619                    + newState);
18620        }
18621        PackageSetting pkgSetting;
18622        final int uid = Binder.getCallingUid();
18623        final int permission;
18624        if (uid == Process.SYSTEM_UID) {
18625            permission = PackageManager.PERMISSION_GRANTED;
18626        } else {
18627            permission = mContext.checkCallingOrSelfPermission(
18628                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18629        }
18630        enforceCrossUserPermission(uid, userId,
18631                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18632        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18633        boolean sendNow = false;
18634        boolean isApp = (className == null);
18635        String componentName = isApp ? packageName : className;
18636        int packageUid = -1;
18637        ArrayList<String> components;
18638
18639        // writer
18640        synchronized (mPackages) {
18641            pkgSetting = mSettings.mPackages.get(packageName);
18642            if (pkgSetting == null) {
18643                if (className == null) {
18644                    throw new IllegalArgumentException("Unknown package: " + packageName);
18645                }
18646                throw new IllegalArgumentException(
18647                        "Unknown component: " + packageName + "/" + className);
18648            }
18649        }
18650
18651        // Limit who can change which apps
18652        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18653            // Don't allow apps that don't have permission to modify other apps
18654            if (!allowedByPermission) {
18655                throw new SecurityException(
18656                        "Permission Denial: attempt to change component state from pid="
18657                        + Binder.getCallingPid()
18658                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18659            }
18660            // Don't allow changing protected packages.
18661            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18662                throw new SecurityException("Cannot disable a protected package: " + packageName);
18663            }
18664        }
18665
18666        synchronized (mPackages) {
18667            if (uid == Process.SHELL_UID
18668                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18669                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18670                // unless it is a test package.
18671                int oldState = pkgSetting.getEnabled(userId);
18672                if (className == null
18673                    &&
18674                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18675                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18676                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18677                    &&
18678                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18679                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18680                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18681                    // ok
18682                } else {
18683                    throw new SecurityException(
18684                            "Shell cannot change component state for " + packageName + "/"
18685                            + className + " to " + newState);
18686                }
18687            }
18688            if (className == null) {
18689                // We're dealing with an application/package level state change
18690                if (pkgSetting.getEnabled(userId) == newState) {
18691                    // Nothing to do
18692                    return;
18693                }
18694                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18695                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18696                    // Don't care about who enables an app.
18697                    callingPackage = null;
18698                }
18699                pkgSetting.setEnabled(newState, userId, callingPackage);
18700                // pkgSetting.pkg.mSetEnabled = newState;
18701            } else {
18702                // We're dealing with a component level state change
18703                // First, verify that this is a valid class name.
18704                PackageParser.Package pkg = pkgSetting.pkg;
18705                if (pkg == null || !pkg.hasComponentClassName(className)) {
18706                    if (pkg != null &&
18707                            pkg.applicationInfo.targetSdkVersion >=
18708                                    Build.VERSION_CODES.JELLY_BEAN) {
18709                        throw new IllegalArgumentException("Component class " + className
18710                                + " does not exist in " + packageName);
18711                    } else {
18712                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18713                                + className + " does not exist in " + packageName);
18714                    }
18715                }
18716                switch (newState) {
18717                case COMPONENT_ENABLED_STATE_ENABLED:
18718                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18719                        return;
18720                    }
18721                    break;
18722                case COMPONENT_ENABLED_STATE_DISABLED:
18723                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18724                        return;
18725                    }
18726                    break;
18727                case COMPONENT_ENABLED_STATE_DEFAULT:
18728                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18729                        return;
18730                    }
18731                    break;
18732                default:
18733                    Slog.e(TAG, "Invalid new component state: " + newState);
18734                    return;
18735                }
18736            }
18737            scheduleWritePackageRestrictionsLocked(userId);
18738            components = mPendingBroadcasts.get(userId, packageName);
18739            final boolean newPackage = components == null;
18740            if (newPackage) {
18741                components = new ArrayList<String>();
18742            }
18743            if (!components.contains(componentName)) {
18744                components.add(componentName);
18745            }
18746            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18747                sendNow = true;
18748                // Purge entry from pending broadcast list if another one exists already
18749                // since we are sending one right away.
18750                mPendingBroadcasts.remove(userId, packageName);
18751            } else {
18752                if (newPackage) {
18753                    mPendingBroadcasts.put(userId, packageName, components);
18754                }
18755                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18756                    // Schedule a message
18757                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18758                }
18759            }
18760        }
18761
18762        long callingId = Binder.clearCallingIdentity();
18763        try {
18764            if (sendNow) {
18765                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18766                sendPackageChangedBroadcast(packageName,
18767                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18768            }
18769        } finally {
18770            Binder.restoreCallingIdentity(callingId);
18771        }
18772    }
18773
18774    @Override
18775    public void flushPackageRestrictionsAsUser(int userId) {
18776        if (!sUserManager.exists(userId)) {
18777            return;
18778        }
18779        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18780                false /* checkShell */, "flushPackageRestrictions");
18781        synchronized (mPackages) {
18782            mSettings.writePackageRestrictionsLPr(userId);
18783            mDirtyUsers.remove(userId);
18784            if (mDirtyUsers.isEmpty()) {
18785                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18786            }
18787        }
18788    }
18789
18790    private void sendPackageChangedBroadcast(String packageName,
18791            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18792        if (DEBUG_INSTALL)
18793            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18794                    + componentNames);
18795        Bundle extras = new Bundle(4);
18796        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18797        String nameList[] = new String[componentNames.size()];
18798        componentNames.toArray(nameList);
18799        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18800        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18801        extras.putInt(Intent.EXTRA_UID, packageUid);
18802        // If this is not reporting a change of the overall package, then only send it
18803        // to registered receivers.  We don't want to launch a swath of apps for every
18804        // little component state change.
18805        final int flags = !componentNames.contains(packageName)
18806                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18807        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18808                new int[] {UserHandle.getUserId(packageUid)});
18809    }
18810
18811    @Override
18812    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18813        if (!sUserManager.exists(userId)) return;
18814        final int uid = Binder.getCallingUid();
18815        final int permission = mContext.checkCallingOrSelfPermission(
18816                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18817        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18818        enforceCrossUserPermission(uid, userId,
18819                true /* requireFullPermission */, true /* checkShell */, "stop package");
18820        // writer
18821        synchronized (mPackages) {
18822            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18823                    allowedByPermission, uid, userId)) {
18824                scheduleWritePackageRestrictionsLocked(userId);
18825            }
18826        }
18827    }
18828
18829    @Override
18830    public String getInstallerPackageName(String packageName) {
18831        // reader
18832        synchronized (mPackages) {
18833            return mSettings.getInstallerPackageNameLPr(packageName);
18834        }
18835    }
18836
18837    public boolean isOrphaned(String packageName) {
18838        // reader
18839        synchronized (mPackages) {
18840            return mSettings.isOrphaned(packageName);
18841        }
18842    }
18843
18844    @Override
18845    public int getApplicationEnabledSetting(String packageName, int userId) {
18846        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18847        int uid = Binder.getCallingUid();
18848        enforceCrossUserPermission(uid, userId,
18849                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18850        // reader
18851        synchronized (mPackages) {
18852            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18853        }
18854    }
18855
18856    @Override
18857    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18858        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18859        int uid = Binder.getCallingUid();
18860        enforceCrossUserPermission(uid, userId,
18861                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18862        // reader
18863        synchronized (mPackages) {
18864            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18865        }
18866    }
18867
18868    @Override
18869    public void enterSafeMode() {
18870        enforceSystemOrRoot("Only the system can request entering safe mode");
18871
18872        if (!mSystemReady) {
18873            mSafeMode = true;
18874        }
18875    }
18876
18877    @Override
18878    public void systemReady() {
18879        mSystemReady = true;
18880
18881        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18882        // disabled after already being started.
18883        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18884                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18885
18886        // Read the compatibilty setting when the system is ready.
18887        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18888                mContext.getContentResolver(),
18889                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18890        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18891        if (DEBUG_SETTINGS) {
18892            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18893        }
18894
18895        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18896
18897        synchronized (mPackages) {
18898            // Verify that all of the preferred activity components actually
18899            // exist.  It is possible for applications to be updated and at
18900            // that point remove a previously declared activity component that
18901            // had been set as a preferred activity.  We try to clean this up
18902            // the next time we encounter that preferred activity, but it is
18903            // possible for the user flow to never be able to return to that
18904            // situation so here we do a sanity check to make sure we haven't
18905            // left any junk around.
18906            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18907            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18908                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18909                removed.clear();
18910                for (PreferredActivity pa : pir.filterSet()) {
18911                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18912                        removed.add(pa);
18913                    }
18914                }
18915                if (removed.size() > 0) {
18916                    for (int r=0; r<removed.size(); r++) {
18917                        PreferredActivity pa = removed.get(r);
18918                        Slog.w(TAG, "Removing dangling preferred activity: "
18919                                + pa.mPref.mComponent);
18920                        pir.removeFilter(pa);
18921                    }
18922                    mSettings.writePackageRestrictionsLPr(
18923                            mSettings.mPreferredActivities.keyAt(i));
18924                }
18925            }
18926
18927            for (int userId : UserManagerService.getInstance().getUserIds()) {
18928                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18929                    grantPermissionsUserIds = ArrayUtils.appendInt(
18930                            grantPermissionsUserIds, userId);
18931                }
18932            }
18933        }
18934        sUserManager.systemReady();
18935
18936        // If we upgraded grant all default permissions before kicking off.
18937        for (int userId : grantPermissionsUserIds) {
18938            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18939        }
18940
18941        // If we did not grant default permissions, we preload from this the
18942        // default permission exceptions lazily to ensure we don't hit the
18943        // disk on a new user creation.
18944        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18945            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18946        }
18947
18948        // Kick off any messages waiting for system ready
18949        if (mPostSystemReadyMessages != null) {
18950            for (Message msg : mPostSystemReadyMessages) {
18951                msg.sendToTarget();
18952            }
18953            mPostSystemReadyMessages = null;
18954        }
18955
18956        // Watch for external volumes that come and go over time
18957        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18958        storage.registerListener(mStorageListener);
18959
18960        mInstallerService.systemReady();
18961        mPackageDexOptimizer.systemReady();
18962
18963        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18964                StorageManagerInternal.class);
18965        StorageManagerInternal.addExternalStoragePolicy(
18966                new StorageManagerInternal.ExternalStorageMountPolicy() {
18967            @Override
18968            public int getMountMode(int uid, String packageName) {
18969                if (Process.isIsolated(uid)) {
18970                    return Zygote.MOUNT_EXTERNAL_NONE;
18971                }
18972                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18973                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18974                }
18975                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18976                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18977                }
18978                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18979                    return Zygote.MOUNT_EXTERNAL_READ;
18980                }
18981                return Zygote.MOUNT_EXTERNAL_WRITE;
18982            }
18983
18984            @Override
18985            public boolean hasExternalStorage(int uid, String packageName) {
18986                return true;
18987            }
18988        });
18989
18990        // Now that we're mostly running, clean up stale users and apps
18991        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18992        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18993    }
18994
18995    @Override
18996    public boolean isSafeMode() {
18997        return mSafeMode;
18998    }
18999
19000    @Override
19001    public boolean hasSystemUidErrors() {
19002        return mHasSystemUidErrors;
19003    }
19004
19005    static String arrayToString(int[] array) {
19006        StringBuffer buf = new StringBuffer(128);
19007        buf.append('[');
19008        if (array != null) {
19009            for (int i=0; i<array.length; i++) {
19010                if (i > 0) buf.append(", ");
19011                buf.append(array[i]);
19012            }
19013        }
19014        buf.append(']');
19015        return buf.toString();
19016    }
19017
19018    static class DumpState {
19019        public static final int DUMP_LIBS = 1 << 0;
19020        public static final int DUMP_FEATURES = 1 << 1;
19021        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19022        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19023        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19024        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19025        public static final int DUMP_PERMISSIONS = 1 << 6;
19026        public static final int DUMP_PACKAGES = 1 << 7;
19027        public static final int DUMP_SHARED_USERS = 1 << 8;
19028        public static final int DUMP_MESSAGES = 1 << 9;
19029        public static final int DUMP_PROVIDERS = 1 << 10;
19030        public static final int DUMP_VERIFIERS = 1 << 11;
19031        public static final int DUMP_PREFERRED = 1 << 12;
19032        public static final int DUMP_PREFERRED_XML = 1 << 13;
19033        public static final int DUMP_KEYSETS = 1 << 14;
19034        public static final int DUMP_VERSION = 1 << 15;
19035        public static final int DUMP_INSTALLS = 1 << 16;
19036        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19037        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19038        public static final int DUMP_FROZEN = 1 << 19;
19039        public static final int DUMP_DEXOPT = 1 << 20;
19040        public static final int DUMP_COMPILER_STATS = 1 << 21;
19041
19042        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19043
19044        private int mTypes;
19045
19046        private int mOptions;
19047
19048        private boolean mTitlePrinted;
19049
19050        private SharedUserSetting mSharedUser;
19051
19052        public boolean isDumping(int type) {
19053            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19054                return true;
19055            }
19056
19057            return (mTypes & type) != 0;
19058        }
19059
19060        public void setDump(int type) {
19061            mTypes |= type;
19062        }
19063
19064        public boolean isOptionEnabled(int option) {
19065            return (mOptions & option) != 0;
19066        }
19067
19068        public void setOptionEnabled(int option) {
19069            mOptions |= option;
19070        }
19071
19072        public boolean onTitlePrinted() {
19073            final boolean printed = mTitlePrinted;
19074            mTitlePrinted = true;
19075            return printed;
19076        }
19077
19078        public boolean getTitlePrinted() {
19079            return mTitlePrinted;
19080        }
19081
19082        public void setTitlePrinted(boolean enabled) {
19083            mTitlePrinted = enabled;
19084        }
19085
19086        public SharedUserSetting getSharedUser() {
19087            return mSharedUser;
19088        }
19089
19090        public void setSharedUser(SharedUserSetting user) {
19091            mSharedUser = user;
19092        }
19093    }
19094
19095    @Override
19096    public void onShellCommand(FileDescriptor in, FileDescriptor out,
19097            FileDescriptor err, String[] args, ShellCallback callback,
19098            ResultReceiver resultReceiver) {
19099        (new PackageManagerShellCommand(this)).exec(
19100                this, in, out, err, args, callback, resultReceiver);
19101    }
19102
19103    @Override
19104    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
19105        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
19106                != PackageManager.PERMISSION_GRANTED) {
19107            pw.println("Permission Denial: can't dump ActivityManager from from pid="
19108                    + Binder.getCallingPid()
19109                    + ", uid=" + Binder.getCallingUid()
19110                    + " without permission "
19111                    + android.Manifest.permission.DUMP);
19112            return;
19113        }
19114
19115        DumpState dumpState = new DumpState();
19116        boolean fullPreferred = false;
19117        boolean checkin = false;
19118
19119        String packageName = null;
19120        ArraySet<String> permissionNames = null;
19121
19122        int opti = 0;
19123        while (opti < args.length) {
19124            String opt = args[opti];
19125            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
19126                break;
19127            }
19128            opti++;
19129
19130            if ("-a".equals(opt)) {
19131                // Right now we only know how to print all.
19132            } else if ("-h".equals(opt)) {
19133                pw.println("Package manager dump options:");
19134                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
19135                pw.println("    --checkin: dump for a checkin");
19136                pw.println("    -f: print details of intent filters");
19137                pw.println("    -h: print this help");
19138                pw.println("  cmd may be one of:");
19139                pw.println("    l[ibraries]: list known shared libraries");
19140                pw.println("    f[eatures]: list device features");
19141                pw.println("    k[eysets]: print known keysets");
19142                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
19143                pw.println("    perm[issions]: dump permissions");
19144                pw.println("    permission [name ...]: dump declaration and use of given permission");
19145                pw.println("    pref[erred]: print preferred package settings");
19146                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
19147                pw.println("    prov[iders]: dump content providers");
19148                pw.println("    p[ackages]: dump installed packages");
19149                pw.println("    s[hared-users]: dump shared user IDs");
19150                pw.println("    m[essages]: print collected runtime messages");
19151                pw.println("    v[erifiers]: print package verifier info");
19152                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
19153                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
19154                pw.println("    version: print database version info");
19155                pw.println("    write: write current settings now");
19156                pw.println("    installs: details about install sessions");
19157                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
19158                pw.println("    dexopt: dump dexopt state");
19159                pw.println("    compiler-stats: dump compiler statistics");
19160                pw.println("    <package.name>: info about given package");
19161                return;
19162            } else if ("--checkin".equals(opt)) {
19163                checkin = true;
19164            } else if ("-f".equals(opt)) {
19165                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19166            } else {
19167                pw.println("Unknown argument: " + opt + "; use -h for help");
19168            }
19169        }
19170
19171        // Is the caller requesting to dump a particular piece of data?
19172        if (opti < args.length) {
19173            String cmd = args[opti];
19174            opti++;
19175            // Is this a package name?
19176            if ("android".equals(cmd) || cmd.contains(".")) {
19177                packageName = cmd;
19178                // When dumping a single package, we always dump all of its
19179                // filter information since the amount of data will be reasonable.
19180                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19181            } else if ("check-permission".equals(cmd)) {
19182                if (opti >= args.length) {
19183                    pw.println("Error: check-permission missing permission argument");
19184                    return;
19185                }
19186                String perm = args[opti];
19187                opti++;
19188                if (opti >= args.length) {
19189                    pw.println("Error: check-permission missing package argument");
19190                    return;
19191                }
19192                String pkg = args[opti];
19193                opti++;
19194                int user = UserHandle.getUserId(Binder.getCallingUid());
19195                if (opti < args.length) {
19196                    try {
19197                        user = Integer.parseInt(args[opti]);
19198                    } catch (NumberFormatException e) {
19199                        pw.println("Error: check-permission user argument is not a number: "
19200                                + args[opti]);
19201                        return;
19202                    }
19203                }
19204                pw.println(checkPermission(perm, pkg, user));
19205                return;
19206            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
19207                dumpState.setDump(DumpState.DUMP_LIBS);
19208            } else if ("f".equals(cmd) || "features".equals(cmd)) {
19209                dumpState.setDump(DumpState.DUMP_FEATURES);
19210            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
19211                if (opti >= args.length) {
19212                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
19213                            | DumpState.DUMP_SERVICE_RESOLVERS
19214                            | DumpState.DUMP_RECEIVER_RESOLVERS
19215                            | DumpState.DUMP_CONTENT_RESOLVERS);
19216                } else {
19217                    while (opti < args.length) {
19218                        String name = args[opti];
19219                        if ("a".equals(name) || "activity".equals(name)) {
19220                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
19221                        } else if ("s".equals(name) || "service".equals(name)) {
19222                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
19223                        } else if ("r".equals(name) || "receiver".equals(name)) {
19224                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19225                        } else if ("c".equals(name) || "content".equals(name)) {
19226                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19227                        } else {
19228                            pw.println("Error: unknown resolver table type: " + name);
19229                            return;
19230                        }
19231                        opti++;
19232                    }
19233                }
19234            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19235                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19236            } else if ("permission".equals(cmd)) {
19237                if (opti >= args.length) {
19238                    pw.println("Error: permission requires permission name");
19239                    return;
19240                }
19241                permissionNames = new ArraySet<>();
19242                while (opti < args.length) {
19243                    permissionNames.add(args[opti]);
19244                    opti++;
19245                }
19246                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19247                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19248            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19249                dumpState.setDump(DumpState.DUMP_PREFERRED);
19250            } else if ("preferred-xml".equals(cmd)) {
19251                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19252                if (opti < args.length && "--full".equals(args[opti])) {
19253                    fullPreferred = true;
19254                    opti++;
19255                }
19256            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19257                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19258            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19259                dumpState.setDump(DumpState.DUMP_PACKAGES);
19260            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19261                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19262            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19263                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19264            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19265                dumpState.setDump(DumpState.DUMP_MESSAGES);
19266            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19267                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19268            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19269                    || "intent-filter-verifiers".equals(cmd)) {
19270                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19271            } else if ("version".equals(cmd)) {
19272                dumpState.setDump(DumpState.DUMP_VERSION);
19273            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19274                dumpState.setDump(DumpState.DUMP_KEYSETS);
19275            } else if ("installs".equals(cmd)) {
19276                dumpState.setDump(DumpState.DUMP_INSTALLS);
19277            } else if ("frozen".equals(cmd)) {
19278                dumpState.setDump(DumpState.DUMP_FROZEN);
19279            } else if ("dexopt".equals(cmd)) {
19280                dumpState.setDump(DumpState.DUMP_DEXOPT);
19281            } else if ("compiler-stats".equals(cmd)) {
19282                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19283            } else if ("write".equals(cmd)) {
19284                synchronized (mPackages) {
19285                    mSettings.writeLPr();
19286                    pw.println("Settings written.");
19287                    return;
19288                }
19289            }
19290        }
19291
19292        if (checkin) {
19293            pw.println("vers,1");
19294        }
19295
19296        // reader
19297        synchronized (mPackages) {
19298            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19299                if (!checkin) {
19300                    if (dumpState.onTitlePrinted())
19301                        pw.println();
19302                    pw.println("Database versions:");
19303                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19304                }
19305            }
19306
19307            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19308                if (!checkin) {
19309                    if (dumpState.onTitlePrinted())
19310                        pw.println();
19311                    pw.println("Verifiers:");
19312                    pw.print("  Required: ");
19313                    pw.print(mRequiredVerifierPackage);
19314                    pw.print(" (uid=");
19315                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19316                            UserHandle.USER_SYSTEM));
19317                    pw.println(")");
19318                } else if (mRequiredVerifierPackage != null) {
19319                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19320                    pw.print(",");
19321                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19322                            UserHandle.USER_SYSTEM));
19323                }
19324            }
19325
19326            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19327                    packageName == null) {
19328                if (mIntentFilterVerifierComponent != null) {
19329                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19330                    if (!checkin) {
19331                        if (dumpState.onTitlePrinted())
19332                            pw.println();
19333                        pw.println("Intent Filter Verifier:");
19334                        pw.print("  Using: ");
19335                        pw.print(verifierPackageName);
19336                        pw.print(" (uid=");
19337                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19338                                UserHandle.USER_SYSTEM));
19339                        pw.println(")");
19340                    } else if (verifierPackageName != null) {
19341                        pw.print("ifv,"); pw.print(verifierPackageName);
19342                        pw.print(",");
19343                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19344                                UserHandle.USER_SYSTEM));
19345                    }
19346                } else {
19347                    pw.println();
19348                    pw.println("No Intent Filter Verifier available!");
19349                }
19350            }
19351
19352            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19353                boolean printedHeader = false;
19354                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19355                while (it.hasNext()) {
19356                    String name = it.next();
19357                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19358                    if (!checkin) {
19359                        if (!printedHeader) {
19360                            if (dumpState.onTitlePrinted())
19361                                pw.println();
19362                            pw.println("Libraries:");
19363                            printedHeader = true;
19364                        }
19365                        pw.print("  ");
19366                    } else {
19367                        pw.print("lib,");
19368                    }
19369                    pw.print(name);
19370                    if (!checkin) {
19371                        pw.print(" -> ");
19372                    }
19373                    if (ent.path != null) {
19374                        if (!checkin) {
19375                            pw.print("(jar) ");
19376                            pw.print(ent.path);
19377                        } else {
19378                            pw.print(",jar,");
19379                            pw.print(ent.path);
19380                        }
19381                    } else {
19382                        if (!checkin) {
19383                            pw.print("(apk) ");
19384                            pw.print(ent.apk);
19385                        } else {
19386                            pw.print(",apk,");
19387                            pw.print(ent.apk);
19388                        }
19389                    }
19390                    pw.println();
19391                }
19392            }
19393
19394            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19395                if (dumpState.onTitlePrinted())
19396                    pw.println();
19397                if (!checkin) {
19398                    pw.println("Features:");
19399                }
19400
19401                for (FeatureInfo feat : mAvailableFeatures.values()) {
19402                    if (checkin) {
19403                        pw.print("feat,");
19404                        pw.print(feat.name);
19405                        pw.print(",");
19406                        pw.println(feat.version);
19407                    } else {
19408                        pw.print("  ");
19409                        pw.print(feat.name);
19410                        if (feat.version > 0) {
19411                            pw.print(" version=");
19412                            pw.print(feat.version);
19413                        }
19414                        pw.println();
19415                    }
19416                }
19417            }
19418
19419            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19420                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19421                        : "Activity Resolver Table:", "  ", packageName,
19422                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19423                    dumpState.setTitlePrinted(true);
19424                }
19425            }
19426            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19427                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19428                        : "Receiver Resolver Table:", "  ", packageName,
19429                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19430                    dumpState.setTitlePrinted(true);
19431                }
19432            }
19433            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19434                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19435                        : "Service Resolver Table:", "  ", packageName,
19436                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19437                    dumpState.setTitlePrinted(true);
19438                }
19439            }
19440            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19441                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19442                        : "Provider Resolver Table:", "  ", packageName,
19443                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19444                    dumpState.setTitlePrinted(true);
19445                }
19446            }
19447
19448            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19449                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19450                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19451                    int user = mSettings.mPreferredActivities.keyAt(i);
19452                    if (pir.dump(pw,
19453                            dumpState.getTitlePrinted()
19454                                ? "\nPreferred Activities User " + user + ":"
19455                                : "Preferred Activities User " + user + ":", "  ",
19456                            packageName, true, false)) {
19457                        dumpState.setTitlePrinted(true);
19458                    }
19459                }
19460            }
19461
19462            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19463                pw.flush();
19464                FileOutputStream fout = new FileOutputStream(fd);
19465                BufferedOutputStream str = new BufferedOutputStream(fout);
19466                XmlSerializer serializer = new FastXmlSerializer();
19467                try {
19468                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19469                    serializer.startDocument(null, true);
19470                    serializer.setFeature(
19471                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19472                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19473                    serializer.endDocument();
19474                    serializer.flush();
19475                } catch (IllegalArgumentException e) {
19476                    pw.println("Failed writing: " + e);
19477                } catch (IllegalStateException e) {
19478                    pw.println("Failed writing: " + e);
19479                } catch (IOException e) {
19480                    pw.println("Failed writing: " + e);
19481                }
19482            }
19483
19484            if (!checkin
19485                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19486                    && packageName == null) {
19487                pw.println();
19488                int count = mSettings.mPackages.size();
19489                if (count == 0) {
19490                    pw.println("No applications!");
19491                    pw.println();
19492                } else {
19493                    final String prefix = "  ";
19494                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19495                    if (allPackageSettings.size() == 0) {
19496                        pw.println("No domain preferred apps!");
19497                        pw.println();
19498                    } else {
19499                        pw.println("App verification status:");
19500                        pw.println();
19501                        count = 0;
19502                        for (PackageSetting ps : allPackageSettings) {
19503                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19504                            if (ivi == null || ivi.getPackageName() == null) continue;
19505                            pw.println(prefix + "Package: " + ivi.getPackageName());
19506                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19507                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19508                            pw.println();
19509                            count++;
19510                        }
19511                        if (count == 0) {
19512                            pw.println(prefix + "No app verification established.");
19513                            pw.println();
19514                        }
19515                        for (int userId : sUserManager.getUserIds()) {
19516                            pw.println("App linkages for user " + userId + ":");
19517                            pw.println();
19518                            count = 0;
19519                            for (PackageSetting ps : allPackageSettings) {
19520                                final long status = ps.getDomainVerificationStatusForUser(userId);
19521                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19522                                    continue;
19523                                }
19524                                pw.println(prefix + "Package: " + ps.name);
19525                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19526                                String statusStr = IntentFilterVerificationInfo.
19527                                        getStatusStringFromValue(status);
19528                                pw.println(prefix + "Status:  " + statusStr);
19529                                pw.println();
19530                                count++;
19531                            }
19532                            if (count == 0) {
19533                                pw.println(prefix + "No configured app linkages.");
19534                                pw.println();
19535                            }
19536                        }
19537                    }
19538                }
19539            }
19540
19541            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19542                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19543                if (packageName == null && permissionNames == null) {
19544                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19545                        if (iperm == 0) {
19546                            if (dumpState.onTitlePrinted())
19547                                pw.println();
19548                            pw.println("AppOp Permissions:");
19549                        }
19550                        pw.print("  AppOp Permission ");
19551                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19552                        pw.println(":");
19553                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19554                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19555                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19556                        }
19557                    }
19558                }
19559            }
19560
19561            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19562                boolean printedSomething = false;
19563                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19564                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19565                        continue;
19566                    }
19567                    if (!printedSomething) {
19568                        if (dumpState.onTitlePrinted())
19569                            pw.println();
19570                        pw.println("Registered ContentProviders:");
19571                        printedSomething = true;
19572                    }
19573                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19574                    pw.print("    "); pw.println(p.toString());
19575                }
19576                printedSomething = false;
19577                for (Map.Entry<String, PackageParser.Provider> entry :
19578                        mProvidersByAuthority.entrySet()) {
19579                    PackageParser.Provider p = entry.getValue();
19580                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19581                        continue;
19582                    }
19583                    if (!printedSomething) {
19584                        if (dumpState.onTitlePrinted())
19585                            pw.println();
19586                        pw.println("ContentProvider Authorities:");
19587                        printedSomething = true;
19588                    }
19589                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19590                    pw.print("    "); pw.println(p.toString());
19591                    if (p.info != null && p.info.applicationInfo != null) {
19592                        final String appInfo = p.info.applicationInfo.toString();
19593                        pw.print("      applicationInfo="); pw.println(appInfo);
19594                    }
19595                }
19596            }
19597
19598            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19599                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19600            }
19601
19602            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19603                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19604            }
19605
19606            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19607                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19608            }
19609
19610            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19611                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19612            }
19613
19614            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19615                // XXX should handle packageName != null by dumping only install data that
19616                // the given package is involved with.
19617                if (dumpState.onTitlePrinted()) pw.println();
19618                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19619            }
19620
19621            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19622                // XXX should handle packageName != null by dumping only install data that
19623                // the given package is involved with.
19624                if (dumpState.onTitlePrinted()) pw.println();
19625
19626                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19627                ipw.println();
19628                ipw.println("Frozen packages:");
19629                ipw.increaseIndent();
19630                if (mFrozenPackages.size() == 0) {
19631                    ipw.println("(none)");
19632                } else {
19633                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19634                        ipw.println(mFrozenPackages.valueAt(i));
19635                    }
19636                }
19637                ipw.decreaseIndent();
19638            }
19639
19640            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19641                if (dumpState.onTitlePrinted()) pw.println();
19642                dumpDexoptStateLPr(pw, packageName);
19643            }
19644
19645            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19646                if (dumpState.onTitlePrinted()) pw.println();
19647                dumpCompilerStatsLPr(pw, packageName);
19648            }
19649
19650            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19651                if (dumpState.onTitlePrinted()) pw.println();
19652                mSettings.dumpReadMessagesLPr(pw, dumpState);
19653
19654                pw.println();
19655                pw.println("Package warning messages:");
19656                BufferedReader in = null;
19657                String line = null;
19658                try {
19659                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19660                    while ((line = in.readLine()) != null) {
19661                        if (line.contains("ignored: updated version")) continue;
19662                        pw.println(line);
19663                    }
19664                } catch (IOException ignored) {
19665                } finally {
19666                    IoUtils.closeQuietly(in);
19667                }
19668            }
19669
19670            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19671                BufferedReader in = null;
19672                String line = null;
19673                try {
19674                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19675                    while ((line = in.readLine()) != null) {
19676                        if (line.contains("ignored: updated version")) continue;
19677                        pw.print("msg,");
19678                        pw.println(line);
19679                    }
19680                } catch (IOException ignored) {
19681                } finally {
19682                    IoUtils.closeQuietly(in);
19683                }
19684            }
19685        }
19686    }
19687
19688    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19689        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19690        ipw.println();
19691        ipw.println("Dexopt state:");
19692        ipw.increaseIndent();
19693        Collection<PackageParser.Package> packages = null;
19694        if (packageName != null) {
19695            PackageParser.Package targetPackage = mPackages.get(packageName);
19696            if (targetPackage != null) {
19697                packages = Collections.singletonList(targetPackage);
19698            } else {
19699                ipw.println("Unable to find package: " + packageName);
19700                return;
19701            }
19702        } else {
19703            packages = mPackages.values();
19704        }
19705
19706        for (PackageParser.Package pkg : packages) {
19707            ipw.println("[" + pkg.packageName + "]");
19708            ipw.increaseIndent();
19709            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19710            ipw.decreaseIndent();
19711        }
19712    }
19713
19714    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19715        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19716        ipw.println();
19717        ipw.println("Compiler stats:");
19718        ipw.increaseIndent();
19719        Collection<PackageParser.Package> packages = null;
19720        if (packageName != null) {
19721            PackageParser.Package targetPackage = mPackages.get(packageName);
19722            if (targetPackage != null) {
19723                packages = Collections.singletonList(targetPackage);
19724            } else {
19725                ipw.println("Unable to find package: " + packageName);
19726                return;
19727            }
19728        } else {
19729            packages = mPackages.values();
19730        }
19731
19732        for (PackageParser.Package pkg : packages) {
19733            ipw.println("[" + pkg.packageName + "]");
19734            ipw.increaseIndent();
19735
19736            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19737            if (stats == null) {
19738                ipw.println("(No recorded stats)");
19739            } else {
19740                stats.dump(ipw);
19741            }
19742            ipw.decreaseIndent();
19743        }
19744    }
19745
19746    private String dumpDomainString(String packageName) {
19747        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19748                .getList();
19749        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19750
19751        ArraySet<String> result = new ArraySet<>();
19752        if (iviList.size() > 0) {
19753            for (IntentFilterVerificationInfo ivi : iviList) {
19754                for (String host : ivi.getDomains()) {
19755                    result.add(host);
19756                }
19757            }
19758        }
19759        if (filters != null && filters.size() > 0) {
19760            for (IntentFilter filter : filters) {
19761                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19762                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19763                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19764                    result.addAll(filter.getHostsList());
19765                }
19766            }
19767        }
19768
19769        StringBuilder sb = new StringBuilder(result.size() * 16);
19770        for (String domain : result) {
19771            if (sb.length() > 0) sb.append(" ");
19772            sb.append(domain);
19773        }
19774        return sb.toString();
19775    }
19776
19777    // ------- apps on sdcard specific code -------
19778    static final boolean DEBUG_SD_INSTALL = false;
19779
19780    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19781
19782    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19783
19784    private boolean mMediaMounted = false;
19785
19786    static String getEncryptKey() {
19787        try {
19788            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19789                    SD_ENCRYPTION_KEYSTORE_NAME);
19790            if (sdEncKey == null) {
19791                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19792                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19793                if (sdEncKey == null) {
19794                    Slog.e(TAG, "Failed to create encryption keys");
19795                    return null;
19796                }
19797            }
19798            return sdEncKey;
19799        } catch (NoSuchAlgorithmException nsae) {
19800            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19801            return null;
19802        } catch (IOException ioe) {
19803            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19804            return null;
19805        }
19806    }
19807
19808    /*
19809     * Update media status on PackageManager.
19810     */
19811    @Override
19812    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19813        int callingUid = Binder.getCallingUid();
19814        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19815            throw new SecurityException("Media status can only be updated by the system");
19816        }
19817        // reader; this apparently protects mMediaMounted, but should probably
19818        // be a different lock in that case.
19819        synchronized (mPackages) {
19820            Log.i(TAG, "Updating external media status from "
19821                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19822                    + (mediaStatus ? "mounted" : "unmounted"));
19823            if (DEBUG_SD_INSTALL)
19824                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19825                        + ", mMediaMounted=" + mMediaMounted);
19826            if (mediaStatus == mMediaMounted) {
19827                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19828                        : 0, -1);
19829                mHandler.sendMessage(msg);
19830                return;
19831            }
19832            mMediaMounted = mediaStatus;
19833        }
19834        // Queue up an async operation since the package installation may take a
19835        // little while.
19836        mHandler.post(new Runnable() {
19837            public void run() {
19838                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19839            }
19840        });
19841    }
19842
19843    /**
19844     * Called by StorageManagerService when the initial ASECs to scan are available.
19845     * Should block until all the ASEC containers are finished being scanned.
19846     */
19847    public void scanAvailableAsecs() {
19848        updateExternalMediaStatusInner(true, false, false);
19849    }
19850
19851    /*
19852     * Collect information of applications on external media, map them against
19853     * existing containers and update information based on current mount status.
19854     * Please note that we always have to report status if reportStatus has been
19855     * set to true especially when unloading packages.
19856     */
19857    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19858            boolean externalStorage) {
19859        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19860        int[] uidArr = EmptyArray.INT;
19861
19862        final String[] list = PackageHelper.getSecureContainerList();
19863        if (ArrayUtils.isEmpty(list)) {
19864            Log.i(TAG, "No secure containers found");
19865        } else {
19866            // Process list of secure containers and categorize them
19867            // as active or stale based on their package internal state.
19868
19869            // reader
19870            synchronized (mPackages) {
19871                for (String cid : list) {
19872                    // Leave stages untouched for now; installer service owns them
19873                    if (PackageInstallerService.isStageName(cid)) continue;
19874
19875                    if (DEBUG_SD_INSTALL)
19876                        Log.i(TAG, "Processing container " + cid);
19877                    String pkgName = getAsecPackageName(cid);
19878                    if (pkgName == null) {
19879                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19880                        continue;
19881                    }
19882                    if (DEBUG_SD_INSTALL)
19883                        Log.i(TAG, "Looking for pkg : " + pkgName);
19884
19885                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19886                    if (ps == null) {
19887                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19888                        continue;
19889                    }
19890
19891                    /*
19892                     * Skip packages that are not external if we're unmounting
19893                     * external storage.
19894                     */
19895                    if (externalStorage && !isMounted && !isExternal(ps)) {
19896                        continue;
19897                    }
19898
19899                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19900                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19901                    // The package status is changed only if the code path
19902                    // matches between settings and the container id.
19903                    if (ps.codePathString != null
19904                            && ps.codePathString.startsWith(args.getCodePath())) {
19905                        if (DEBUG_SD_INSTALL) {
19906                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19907                                    + " at code path: " + ps.codePathString);
19908                        }
19909
19910                        // We do have a valid package installed on sdcard
19911                        processCids.put(args, ps.codePathString);
19912                        final int uid = ps.appId;
19913                        if (uid != -1) {
19914                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19915                        }
19916                    } else {
19917                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19918                                + ps.codePathString);
19919                    }
19920                }
19921            }
19922
19923            Arrays.sort(uidArr);
19924        }
19925
19926        // Process packages with valid entries.
19927        if (isMounted) {
19928            if (DEBUG_SD_INSTALL)
19929                Log.i(TAG, "Loading packages");
19930            loadMediaPackages(processCids, uidArr, externalStorage);
19931            startCleaningPackages();
19932            mInstallerService.onSecureContainersAvailable();
19933        } else {
19934            if (DEBUG_SD_INSTALL)
19935                Log.i(TAG, "Unloading packages");
19936            unloadMediaPackages(processCids, uidArr, reportStatus);
19937        }
19938    }
19939
19940    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19941            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19942        final int size = infos.size();
19943        final String[] packageNames = new String[size];
19944        final int[] packageUids = new int[size];
19945        for (int i = 0; i < size; i++) {
19946            final ApplicationInfo info = infos.get(i);
19947            packageNames[i] = info.packageName;
19948            packageUids[i] = info.uid;
19949        }
19950        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19951                finishedReceiver);
19952    }
19953
19954    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19955            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19956        sendResourcesChangedBroadcast(mediaStatus, replacing,
19957                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19958    }
19959
19960    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19961            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19962        int size = pkgList.length;
19963        if (size > 0) {
19964            // Send broadcasts here
19965            Bundle extras = new Bundle();
19966            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19967            if (uidArr != null) {
19968                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19969            }
19970            if (replacing) {
19971                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19972            }
19973            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19974                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19975            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19976        }
19977    }
19978
19979   /*
19980     * Look at potentially valid container ids from processCids If package
19981     * information doesn't match the one on record or package scanning fails,
19982     * the cid is added to list of removeCids. We currently don't delete stale
19983     * containers.
19984     */
19985    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19986            boolean externalStorage) {
19987        ArrayList<String> pkgList = new ArrayList<String>();
19988        Set<AsecInstallArgs> keys = processCids.keySet();
19989
19990        for (AsecInstallArgs args : keys) {
19991            String codePath = processCids.get(args);
19992            if (DEBUG_SD_INSTALL)
19993                Log.i(TAG, "Loading container : " + args.cid);
19994            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19995            try {
19996                // Make sure there are no container errors first.
19997                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19998                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19999                            + " when installing from sdcard");
20000                    continue;
20001                }
20002                // Check code path here.
20003                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20004                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20005                            + " does not match one in settings " + codePath);
20006                    continue;
20007                }
20008                // Parse package
20009                int parseFlags = mDefParseFlags;
20010                if (args.isExternalAsec()) {
20011                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20012                }
20013                if (args.isFwdLocked()) {
20014                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20015                }
20016
20017                synchronized (mInstallLock) {
20018                    PackageParser.Package pkg = null;
20019                    try {
20020                        // Sadly we don't know the package name yet to freeze it
20021                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20022                                SCAN_IGNORE_FROZEN, 0, null);
20023                    } catch (PackageManagerException e) {
20024                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20025                    }
20026                    // Scan the package
20027                    if (pkg != null) {
20028                        /*
20029                         * TODO why is the lock being held? doPostInstall is
20030                         * called in other places without the lock. This needs
20031                         * to be straightened out.
20032                         */
20033                        // writer
20034                        synchronized (mPackages) {
20035                            retCode = PackageManager.INSTALL_SUCCEEDED;
20036                            pkgList.add(pkg.packageName);
20037                            // Post process args
20038                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20039                                    pkg.applicationInfo.uid);
20040                        }
20041                    } else {
20042                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20043                    }
20044                }
20045
20046            } finally {
20047                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20048                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20049                }
20050            }
20051        }
20052        // writer
20053        synchronized (mPackages) {
20054            // If the platform SDK has changed since the last time we booted,
20055            // we need to re-grant app permission to catch any new ones that
20056            // appear. This is really a hack, and means that apps can in some
20057            // cases get permissions that the user didn't initially explicitly
20058            // allow... it would be nice to have some better way to handle
20059            // this situation.
20060            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20061                    : mSettings.getInternalVersion();
20062            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20063                    : StorageManager.UUID_PRIVATE_INTERNAL;
20064
20065            int updateFlags = UPDATE_PERMISSIONS_ALL;
20066            if (ver.sdkVersion != mSdkVersion) {
20067                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20068                        + mSdkVersion + "; regranting permissions for external");
20069                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20070            }
20071            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20072
20073            // Yay, everything is now upgraded
20074            ver.forceCurrent();
20075
20076            // can downgrade to reader
20077            // Persist settings
20078            mSettings.writeLPr();
20079        }
20080        // Send a broadcast to let everyone know we are done processing
20081        if (pkgList.size() > 0) {
20082            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20083        }
20084    }
20085
20086   /*
20087     * Utility method to unload a list of specified containers
20088     */
20089    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
20090        // Just unmount all valid containers.
20091        for (AsecInstallArgs arg : cidArgs) {
20092            synchronized (mInstallLock) {
20093                arg.doPostDeleteLI(false);
20094           }
20095       }
20096   }
20097
20098    /*
20099     * Unload packages mounted on external media. This involves deleting package
20100     * data from internal structures, sending broadcasts about disabled packages,
20101     * gc'ing to free up references, unmounting all secure containers
20102     * corresponding to packages on external media, and posting a
20103     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
20104     * that we always have to post this message if status has been requested no
20105     * matter what.
20106     */
20107    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
20108            final boolean reportStatus) {
20109        if (DEBUG_SD_INSTALL)
20110            Log.i(TAG, "unloading media packages");
20111        ArrayList<String> pkgList = new ArrayList<String>();
20112        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
20113        final Set<AsecInstallArgs> keys = processCids.keySet();
20114        for (AsecInstallArgs args : keys) {
20115            String pkgName = args.getPackageName();
20116            if (DEBUG_SD_INSTALL)
20117                Log.i(TAG, "Trying to unload pkg : " + pkgName);
20118            // Delete package internally
20119            PackageRemovedInfo outInfo = new PackageRemovedInfo();
20120            synchronized (mInstallLock) {
20121                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20122                final boolean res;
20123                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
20124                        "unloadMediaPackages")) {
20125                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
20126                            null);
20127                }
20128                if (res) {
20129                    pkgList.add(pkgName);
20130                } else {
20131                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
20132                    failedList.add(args);
20133                }
20134            }
20135        }
20136
20137        // reader
20138        synchronized (mPackages) {
20139            // We didn't update the settings after removing each package;
20140            // write them now for all packages.
20141            mSettings.writeLPr();
20142        }
20143
20144        // We have to absolutely send UPDATED_MEDIA_STATUS only
20145        // after confirming that all the receivers processed the ordered
20146        // broadcast when packages get disabled, force a gc to clean things up.
20147        // and unload all the containers.
20148        if (pkgList.size() > 0) {
20149            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
20150                    new IIntentReceiver.Stub() {
20151                public void performReceive(Intent intent, int resultCode, String data,
20152                        Bundle extras, boolean ordered, boolean sticky,
20153                        int sendingUser) throws RemoteException {
20154                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
20155                            reportStatus ? 1 : 0, 1, keys);
20156                    mHandler.sendMessage(msg);
20157                }
20158            });
20159        } else {
20160            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
20161                    keys);
20162            mHandler.sendMessage(msg);
20163        }
20164    }
20165
20166    private void loadPrivatePackages(final VolumeInfo vol) {
20167        mHandler.post(new Runnable() {
20168            @Override
20169            public void run() {
20170                loadPrivatePackagesInner(vol);
20171            }
20172        });
20173    }
20174
20175    private void loadPrivatePackagesInner(VolumeInfo vol) {
20176        final String volumeUuid = vol.fsUuid;
20177        if (TextUtils.isEmpty(volumeUuid)) {
20178            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20179            return;
20180        }
20181
20182        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20183        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20184        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20185
20186        final VersionInfo ver;
20187        final List<PackageSetting> packages;
20188        synchronized (mPackages) {
20189            ver = mSettings.findOrCreateVersion(volumeUuid);
20190            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20191        }
20192
20193        for (PackageSetting ps : packages) {
20194            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20195            synchronized (mInstallLock) {
20196                final PackageParser.Package pkg;
20197                try {
20198                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20199                    loaded.add(pkg.applicationInfo);
20200
20201                } catch (PackageManagerException e) {
20202                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20203                }
20204
20205                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20206                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20207                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20208                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20209                }
20210            }
20211        }
20212
20213        // Reconcile app data for all started/unlocked users
20214        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20215        final UserManager um = mContext.getSystemService(UserManager.class);
20216        UserManagerInternal umInternal = getUserManagerInternal();
20217        for (UserInfo user : um.getUsers()) {
20218            final int flags;
20219            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20220                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20221            } else if (umInternal.isUserRunning(user.id)) {
20222                flags = StorageManager.FLAG_STORAGE_DE;
20223            } else {
20224                continue;
20225            }
20226
20227            try {
20228                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20229                synchronized (mInstallLock) {
20230                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20231                }
20232            } catch (IllegalStateException e) {
20233                // Device was probably ejected, and we'll process that event momentarily
20234                Slog.w(TAG, "Failed to prepare storage: " + e);
20235            }
20236        }
20237
20238        synchronized (mPackages) {
20239            int updateFlags = UPDATE_PERMISSIONS_ALL;
20240            if (ver.sdkVersion != mSdkVersion) {
20241                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20242                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20243                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20244            }
20245            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20246
20247            // Yay, everything is now upgraded
20248            ver.forceCurrent();
20249
20250            mSettings.writeLPr();
20251        }
20252
20253        for (PackageFreezer freezer : freezers) {
20254            freezer.close();
20255        }
20256
20257        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20258        sendResourcesChangedBroadcast(true, false, loaded, null);
20259    }
20260
20261    private void unloadPrivatePackages(final VolumeInfo vol) {
20262        mHandler.post(new Runnable() {
20263            @Override
20264            public void run() {
20265                unloadPrivatePackagesInner(vol);
20266            }
20267        });
20268    }
20269
20270    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20271        final String volumeUuid = vol.fsUuid;
20272        if (TextUtils.isEmpty(volumeUuid)) {
20273            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20274            return;
20275        }
20276
20277        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20278        synchronized (mInstallLock) {
20279        synchronized (mPackages) {
20280            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20281            for (PackageSetting ps : packages) {
20282                if (ps.pkg == null) continue;
20283
20284                final ApplicationInfo info = ps.pkg.applicationInfo;
20285                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20286                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20287
20288                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20289                        "unloadPrivatePackagesInner")) {
20290                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20291                            false, null)) {
20292                        unloaded.add(info);
20293                    } else {
20294                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20295                    }
20296                }
20297
20298                // Try very hard to release any references to this package
20299                // so we don't risk the system server being killed due to
20300                // open FDs
20301                AttributeCache.instance().removePackage(ps.name);
20302            }
20303
20304            mSettings.writeLPr();
20305        }
20306        }
20307
20308        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20309        sendResourcesChangedBroadcast(false, false, unloaded, null);
20310
20311        // Try very hard to release any references to this path so we don't risk
20312        // the system server being killed due to open FDs
20313        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20314
20315        for (int i = 0; i < 3; i++) {
20316            System.gc();
20317            System.runFinalization();
20318        }
20319    }
20320
20321    /**
20322     * Prepare storage areas for given user on all mounted devices.
20323     */
20324    void prepareUserData(int userId, int userSerial, int flags) {
20325        synchronized (mInstallLock) {
20326            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20327            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20328                final String volumeUuid = vol.getFsUuid();
20329                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20330            }
20331        }
20332    }
20333
20334    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20335            boolean allowRecover) {
20336        // Prepare storage and verify that serial numbers are consistent; if
20337        // there's a mismatch we need to destroy to avoid leaking data
20338        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20339        try {
20340            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20341
20342            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20343                UserManagerService.enforceSerialNumber(
20344                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20345                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20346                    UserManagerService.enforceSerialNumber(
20347                            Environment.getDataSystemDeDirectory(userId), userSerial);
20348                }
20349            }
20350            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20351                UserManagerService.enforceSerialNumber(
20352                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20353                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20354                    UserManagerService.enforceSerialNumber(
20355                            Environment.getDataSystemCeDirectory(userId), userSerial);
20356                }
20357            }
20358
20359            synchronized (mInstallLock) {
20360                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20361            }
20362        } catch (Exception e) {
20363            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20364                    + " because we failed to prepare: " + e);
20365            destroyUserDataLI(volumeUuid, userId,
20366                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20367
20368            if (allowRecover) {
20369                // Try one last time; if we fail again we're really in trouble
20370                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20371            }
20372        }
20373    }
20374
20375    /**
20376     * Destroy storage areas for given user on all mounted devices.
20377     */
20378    void destroyUserData(int userId, int flags) {
20379        synchronized (mInstallLock) {
20380            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20381            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20382                final String volumeUuid = vol.getFsUuid();
20383                destroyUserDataLI(volumeUuid, userId, flags);
20384            }
20385        }
20386    }
20387
20388    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20389        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20390        try {
20391            // Clean up app data, profile data, and media data
20392            mInstaller.destroyUserData(volumeUuid, userId, flags);
20393
20394            // Clean up system data
20395            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20396                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20397                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20398                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20399                }
20400                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20401                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20402                }
20403            }
20404
20405            // Data with special labels is now gone, so finish the job
20406            storage.destroyUserStorage(volumeUuid, userId, flags);
20407
20408        } catch (Exception e) {
20409            logCriticalInfo(Log.WARN,
20410                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20411        }
20412    }
20413
20414    /**
20415     * Examine all users present on given mounted volume, and destroy data
20416     * belonging to users that are no longer valid, or whose user ID has been
20417     * recycled.
20418     */
20419    private void reconcileUsers(String volumeUuid) {
20420        final List<File> files = new ArrayList<>();
20421        Collections.addAll(files, FileUtils
20422                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20423        Collections.addAll(files, FileUtils
20424                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20425        Collections.addAll(files, FileUtils
20426                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20427        Collections.addAll(files, FileUtils
20428                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20429        for (File file : files) {
20430            if (!file.isDirectory()) continue;
20431
20432            final int userId;
20433            final UserInfo info;
20434            try {
20435                userId = Integer.parseInt(file.getName());
20436                info = sUserManager.getUserInfo(userId);
20437            } catch (NumberFormatException e) {
20438                Slog.w(TAG, "Invalid user directory " + file);
20439                continue;
20440            }
20441
20442            boolean destroyUser = false;
20443            if (info == null) {
20444                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20445                        + " because no matching user was found");
20446                destroyUser = true;
20447            } else if (!mOnlyCore) {
20448                try {
20449                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20450                } catch (IOException e) {
20451                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20452                            + " because we failed to enforce serial number: " + e);
20453                    destroyUser = true;
20454                }
20455            }
20456
20457            if (destroyUser) {
20458                synchronized (mInstallLock) {
20459                    destroyUserDataLI(volumeUuid, userId,
20460                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20461                }
20462            }
20463        }
20464    }
20465
20466    private void assertPackageKnown(String volumeUuid, String packageName)
20467            throws PackageManagerException {
20468        synchronized (mPackages) {
20469            // Normalize package name to handle renamed packages
20470            packageName = normalizePackageNameLPr(packageName);
20471
20472            final PackageSetting ps = mSettings.mPackages.get(packageName);
20473            if (ps == null) {
20474                throw new PackageManagerException("Package " + packageName + " is unknown");
20475            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20476                throw new PackageManagerException(
20477                        "Package " + packageName + " found on unknown volume " + volumeUuid
20478                                + "; expected volume " + ps.volumeUuid);
20479            }
20480        }
20481    }
20482
20483    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20484            throws PackageManagerException {
20485        synchronized (mPackages) {
20486            // Normalize package name to handle renamed packages
20487            packageName = normalizePackageNameLPr(packageName);
20488
20489            final PackageSetting ps = mSettings.mPackages.get(packageName);
20490            if (ps == null) {
20491                throw new PackageManagerException("Package " + packageName + " is unknown");
20492            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20493                throw new PackageManagerException(
20494                        "Package " + packageName + " found on unknown volume " + volumeUuid
20495                                + "; expected volume " + ps.volumeUuid);
20496            } else if (!ps.getInstalled(userId)) {
20497                throw new PackageManagerException(
20498                        "Package " + packageName + " not installed for user " + userId);
20499            }
20500        }
20501    }
20502
20503    /**
20504     * Examine all apps present on given mounted volume, and destroy apps that
20505     * aren't expected, either due to uninstallation or reinstallation on
20506     * another volume.
20507     */
20508    private void reconcileApps(String volumeUuid) {
20509        final File[] files = FileUtils
20510                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20511        for (File file : files) {
20512            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20513                    && !PackageInstallerService.isStageName(file.getName());
20514            if (!isPackage) {
20515                // Ignore entries which are not packages
20516                continue;
20517            }
20518
20519            try {
20520                final PackageLite pkg = PackageParser.parsePackageLite(file,
20521                        PackageParser.PARSE_MUST_BE_APK);
20522                assertPackageKnown(volumeUuid, pkg.packageName);
20523
20524            } catch (PackageParserException | PackageManagerException e) {
20525                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20526                synchronized (mInstallLock) {
20527                    removeCodePathLI(file);
20528                }
20529            }
20530        }
20531    }
20532
20533    /**
20534     * Reconcile all app data for the given user.
20535     * <p>
20536     * Verifies that directories exist and that ownership and labeling is
20537     * correct for all installed apps on all mounted volumes.
20538     */
20539    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20540        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20541        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20542            final String volumeUuid = vol.getFsUuid();
20543            synchronized (mInstallLock) {
20544                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20545            }
20546        }
20547    }
20548
20549    /**
20550     * Reconcile all app data on given mounted volume.
20551     * <p>
20552     * Destroys app data that isn't expected, either due to uninstallation or
20553     * reinstallation on another volume.
20554     * <p>
20555     * Verifies that directories exist and that ownership and labeling is
20556     * correct for all installed apps.
20557     */
20558    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20559            boolean migrateAppData) {
20560        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20561                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20562
20563        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20564        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20565
20566        // First look for stale data that doesn't belong, and check if things
20567        // have changed since we did our last restorecon
20568        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20569            if (StorageManager.isFileEncryptedNativeOrEmulated()
20570                    && !StorageManager.isUserKeyUnlocked(userId)) {
20571                throw new RuntimeException(
20572                        "Yikes, someone asked us to reconcile CE storage while " + userId
20573                                + " was still locked; this would have caused massive data loss!");
20574            }
20575
20576            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20577            for (File file : files) {
20578                final String packageName = file.getName();
20579                try {
20580                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20581                } catch (PackageManagerException e) {
20582                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20583                    try {
20584                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20585                                StorageManager.FLAG_STORAGE_CE, 0);
20586                    } catch (InstallerException e2) {
20587                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20588                    }
20589                }
20590            }
20591        }
20592        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20593            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20594            for (File file : files) {
20595                final String packageName = file.getName();
20596                try {
20597                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20598                } catch (PackageManagerException e) {
20599                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20600                    try {
20601                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20602                                StorageManager.FLAG_STORAGE_DE, 0);
20603                    } catch (InstallerException e2) {
20604                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20605                    }
20606                }
20607            }
20608        }
20609
20610        // Ensure that data directories are ready to roll for all packages
20611        // installed for this volume and user
20612        final List<PackageSetting> packages;
20613        synchronized (mPackages) {
20614            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20615        }
20616        int preparedCount = 0;
20617        for (PackageSetting ps : packages) {
20618            final String packageName = ps.name;
20619            if (ps.pkg == null) {
20620                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20621                // TODO: might be due to legacy ASEC apps; we should circle back
20622                // and reconcile again once they're scanned
20623                continue;
20624            }
20625
20626            if (ps.getInstalled(userId)) {
20627                prepareAppDataLIF(ps.pkg, userId, flags);
20628
20629                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20630                    // We may have just shuffled around app data directories, so
20631                    // prepare them one more time
20632                    prepareAppDataLIF(ps.pkg, userId, flags);
20633                }
20634
20635                preparedCount++;
20636            }
20637        }
20638
20639        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20640    }
20641
20642    /**
20643     * Prepare app data for the given app just after it was installed or
20644     * upgraded. This method carefully only touches users that it's installed
20645     * for, and it forces a restorecon to handle any seinfo changes.
20646     * <p>
20647     * Verifies that directories exist and that ownership and labeling is
20648     * correct for all installed apps. If there is an ownership mismatch, it
20649     * will try recovering system apps by wiping data; third-party app data is
20650     * left intact.
20651     * <p>
20652     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20653     */
20654    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20655        final PackageSetting ps;
20656        synchronized (mPackages) {
20657            ps = mSettings.mPackages.get(pkg.packageName);
20658            mSettings.writeKernelMappingLPr(ps);
20659        }
20660
20661        final UserManager um = mContext.getSystemService(UserManager.class);
20662        UserManagerInternal umInternal = getUserManagerInternal();
20663        for (UserInfo user : um.getUsers()) {
20664            final int flags;
20665            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20666                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20667            } else if (umInternal.isUserRunning(user.id)) {
20668                flags = StorageManager.FLAG_STORAGE_DE;
20669            } else {
20670                continue;
20671            }
20672
20673            if (ps.getInstalled(user.id)) {
20674                // TODO: when user data is locked, mark that we're still dirty
20675                prepareAppDataLIF(pkg, user.id, flags);
20676            }
20677        }
20678    }
20679
20680    /**
20681     * Prepare app data for the given app.
20682     * <p>
20683     * Verifies that directories exist and that ownership and labeling is
20684     * correct for all installed apps. If there is an ownership mismatch, this
20685     * will try recovering system apps by wiping data; third-party app data is
20686     * left intact.
20687     */
20688    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20689        if (pkg == null) {
20690            Slog.wtf(TAG, "Package was null!", new Throwable());
20691            return;
20692        }
20693        prepareAppDataLeafLIF(pkg, userId, flags);
20694        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20695        for (int i = 0; i < childCount; i++) {
20696            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20697        }
20698    }
20699
20700    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20701        if (DEBUG_APP_DATA) {
20702            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20703                    + Integer.toHexString(flags));
20704        }
20705
20706        final String volumeUuid = pkg.volumeUuid;
20707        final String packageName = pkg.packageName;
20708        final ApplicationInfo app = pkg.applicationInfo;
20709        final int appId = UserHandle.getAppId(app.uid);
20710
20711        Preconditions.checkNotNull(app.seinfo);
20712
20713        long ceDataInode = -1;
20714        try {
20715            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20716                    appId, app.seinfo, app.targetSdkVersion);
20717        } catch (InstallerException e) {
20718            if (app.isSystemApp()) {
20719                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20720                        + ", but trying to recover: " + e);
20721                destroyAppDataLeafLIF(pkg, userId, flags);
20722                try {
20723                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20724                            appId, app.seinfo, app.targetSdkVersion);
20725                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20726                } catch (InstallerException e2) {
20727                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20728                }
20729            } else {
20730                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20731            }
20732        }
20733
20734        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20735            // TODO: mark this structure as dirty so we persist it!
20736            synchronized (mPackages) {
20737                final PackageSetting ps = mSettings.mPackages.get(packageName);
20738                if (ps != null) {
20739                    ps.setCeDataInode(ceDataInode, userId);
20740                }
20741            }
20742        }
20743
20744        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20745    }
20746
20747    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20748        if (pkg == null) {
20749            Slog.wtf(TAG, "Package was null!", new Throwable());
20750            return;
20751        }
20752        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20753        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20754        for (int i = 0; i < childCount; i++) {
20755            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20756        }
20757    }
20758
20759    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20760        final String volumeUuid = pkg.volumeUuid;
20761        final String packageName = pkg.packageName;
20762        final ApplicationInfo app = pkg.applicationInfo;
20763
20764        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20765            // Create a native library symlink only if we have native libraries
20766            // and if the native libraries are 32 bit libraries. We do not provide
20767            // this symlink for 64 bit libraries.
20768            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20769                final String nativeLibPath = app.nativeLibraryDir;
20770                try {
20771                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20772                            nativeLibPath, userId);
20773                } catch (InstallerException e) {
20774                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20775                }
20776            }
20777        }
20778    }
20779
20780    /**
20781     * For system apps on non-FBE devices, this method migrates any existing
20782     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20783     * requested by the app.
20784     */
20785    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20786        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20787                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20788            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20789                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20790            try {
20791                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20792                        storageTarget);
20793            } catch (InstallerException e) {
20794                logCriticalInfo(Log.WARN,
20795                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20796            }
20797            return true;
20798        } else {
20799            return false;
20800        }
20801    }
20802
20803    public PackageFreezer freezePackage(String packageName, String killReason) {
20804        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20805    }
20806
20807    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20808        return new PackageFreezer(packageName, userId, killReason);
20809    }
20810
20811    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20812            String killReason) {
20813        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20814    }
20815
20816    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20817            String killReason) {
20818        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20819            return new PackageFreezer();
20820        } else {
20821            return freezePackage(packageName, userId, killReason);
20822        }
20823    }
20824
20825    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20826            String killReason) {
20827        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20828    }
20829
20830    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20831            String killReason) {
20832        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20833            return new PackageFreezer();
20834        } else {
20835            return freezePackage(packageName, userId, killReason);
20836        }
20837    }
20838
20839    /**
20840     * Class that freezes and kills the given package upon creation, and
20841     * unfreezes it upon closing. This is typically used when doing surgery on
20842     * app code/data to prevent the app from running while you're working.
20843     */
20844    private class PackageFreezer implements AutoCloseable {
20845        private final String mPackageName;
20846        private final PackageFreezer[] mChildren;
20847
20848        private final boolean mWeFroze;
20849
20850        private final AtomicBoolean mClosed = new AtomicBoolean();
20851        private final CloseGuard mCloseGuard = CloseGuard.get();
20852
20853        /**
20854         * Create and return a stub freezer that doesn't actually do anything,
20855         * typically used when someone requested
20856         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20857         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20858         */
20859        public PackageFreezer() {
20860            mPackageName = null;
20861            mChildren = null;
20862            mWeFroze = false;
20863            mCloseGuard.open("close");
20864        }
20865
20866        public PackageFreezer(String packageName, int userId, String killReason) {
20867            synchronized (mPackages) {
20868                mPackageName = packageName;
20869                mWeFroze = mFrozenPackages.add(mPackageName);
20870
20871                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20872                if (ps != null) {
20873                    killApplication(ps.name, ps.appId, userId, killReason);
20874                }
20875
20876                final PackageParser.Package p = mPackages.get(packageName);
20877                if (p != null && p.childPackages != null) {
20878                    final int N = p.childPackages.size();
20879                    mChildren = new PackageFreezer[N];
20880                    for (int i = 0; i < N; i++) {
20881                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20882                                userId, killReason);
20883                    }
20884                } else {
20885                    mChildren = null;
20886                }
20887            }
20888            mCloseGuard.open("close");
20889        }
20890
20891        @Override
20892        protected void finalize() throws Throwable {
20893            try {
20894                mCloseGuard.warnIfOpen();
20895                close();
20896            } finally {
20897                super.finalize();
20898            }
20899        }
20900
20901        @Override
20902        public void close() {
20903            mCloseGuard.close();
20904            if (mClosed.compareAndSet(false, true)) {
20905                synchronized (mPackages) {
20906                    if (mWeFroze) {
20907                        mFrozenPackages.remove(mPackageName);
20908                    }
20909
20910                    if (mChildren != null) {
20911                        for (PackageFreezer freezer : mChildren) {
20912                            freezer.close();
20913                        }
20914                    }
20915                }
20916            }
20917        }
20918    }
20919
20920    /**
20921     * Verify that given package is currently frozen.
20922     */
20923    private void checkPackageFrozen(String packageName) {
20924        synchronized (mPackages) {
20925            if (!mFrozenPackages.contains(packageName)) {
20926                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20927            }
20928        }
20929    }
20930
20931    @Override
20932    public int movePackage(final String packageName, final String volumeUuid) {
20933        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20934
20935        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20936        final int moveId = mNextMoveId.getAndIncrement();
20937        mHandler.post(new Runnable() {
20938            @Override
20939            public void run() {
20940                try {
20941                    movePackageInternal(packageName, volumeUuid, moveId, user);
20942                } catch (PackageManagerException e) {
20943                    Slog.w(TAG, "Failed to move " + packageName, e);
20944                    mMoveCallbacks.notifyStatusChanged(moveId,
20945                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20946                }
20947            }
20948        });
20949        return moveId;
20950    }
20951
20952    private void movePackageInternal(final String packageName, final String volumeUuid,
20953            final int moveId, UserHandle user) throws PackageManagerException {
20954        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20955        final PackageManager pm = mContext.getPackageManager();
20956
20957        final boolean currentAsec;
20958        final String currentVolumeUuid;
20959        final File codeFile;
20960        final String installerPackageName;
20961        final String packageAbiOverride;
20962        final int appId;
20963        final String seinfo;
20964        final String label;
20965        final int targetSdkVersion;
20966        final PackageFreezer freezer;
20967        final int[] installedUserIds;
20968
20969        // reader
20970        synchronized (mPackages) {
20971            final PackageParser.Package pkg = mPackages.get(packageName);
20972            final PackageSetting ps = mSettings.mPackages.get(packageName);
20973            if (pkg == null || ps == null) {
20974                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20975            }
20976
20977            if (pkg.applicationInfo.isSystemApp()) {
20978                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20979                        "Cannot move system application");
20980            }
20981
20982            if (pkg.applicationInfo.isExternalAsec()) {
20983                currentAsec = true;
20984                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20985            } else if (pkg.applicationInfo.isForwardLocked()) {
20986                currentAsec = true;
20987                currentVolumeUuid = "forward_locked";
20988            } else {
20989                currentAsec = false;
20990                currentVolumeUuid = ps.volumeUuid;
20991
20992                final File probe = new File(pkg.codePath);
20993                final File probeOat = new File(probe, "oat");
20994                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20995                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20996                            "Move only supported for modern cluster style installs");
20997                }
20998            }
20999
21000            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21001                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21002                        "Package already moved to " + volumeUuid);
21003            }
21004            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21005                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21006                        "Device admin cannot be moved");
21007            }
21008
21009            if (mFrozenPackages.contains(packageName)) {
21010                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21011                        "Failed to move already frozen package");
21012            }
21013
21014            codeFile = new File(pkg.codePath);
21015            installerPackageName = ps.installerPackageName;
21016            packageAbiOverride = ps.cpuAbiOverrideString;
21017            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21018            seinfo = pkg.applicationInfo.seinfo;
21019            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21020            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21021            freezer = freezePackage(packageName, "movePackageInternal");
21022            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21023        }
21024
21025        final Bundle extras = new Bundle();
21026        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21027        extras.putString(Intent.EXTRA_TITLE, label);
21028        mMoveCallbacks.notifyCreated(moveId, extras);
21029
21030        int installFlags;
21031        final boolean moveCompleteApp;
21032        final File measurePath;
21033
21034        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21035            installFlags = INSTALL_INTERNAL;
21036            moveCompleteApp = !currentAsec;
21037            measurePath = Environment.getDataAppDirectory(volumeUuid);
21038        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21039            installFlags = INSTALL_EXTERNAL;
21040            moveCompleteApp = false;
21041            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21042        } else {
21043            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21044            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21045                    || !volume.isMountedWritable()) {
21046                freezer.close();
21047                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21048                        "Move location not mounted private volume");
21049            }
21050
21051            Preconditions.checkState(!currentAsec);
21052
21053            installFlags = INSTALL_INTERNAL;
21054            moveCompleteApp = true;
21055            measurePath = Environment.getDataAppDirectory(volumeUuid);
21056        }
21057
21058        final PackageStats stats = new PackageStats(null, -1);
21059        synchronized (mInstaller) {
21060            for (int userId : installedUserIds) {
21061                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21062                    freezer.close();
21063                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21064                            "Failed to measure package size");
21065                }
21066            }
21067        }
21068
21069        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21070                + stats.dataSize);
21071
21072        final long startFreeBytes = measurePath.getFreeSpace();
21073        final long sizeBytes;
21074        if (moveCompleteApp) {
21075            sizeBytes = stats.codeSize + stats.dataSize;
21076        } else {
21077            sizeBytes = stats.codeSize;
21078        }
21079
21080        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21081            freezer.close();
21082            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21083                    "Not enough free space to move");
21084        }
21085
21086        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21087
21088        final CountDownLatch installedLatch = new CountDownLatch(1);
21089        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21090            @Override
21091            public void onUserActionRequired(Intent intent) throws RemoteException {
21092                throw new IllegalStateException();
21093            }
21094
21095            @Override
21096            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21097                    Bundle extras) throws RemoteException {
21098                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21099                        + PackageManager.installStatusToString(returnCode, msg));
21100
21101                installedLatch.countDown();
21102                freezer.close();
21103
21104                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21105                switch (status) {
21106                    case PackageInstaller.STATUS_SUCCESS:
21107                        mMoveCallbacks.notifyStatusChanged(moveId,
21108                                PackageManager.MOVE_SUCCEEDED);
21109                        break;
21110                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21111                        mMoveCallbacks.notifyStatusChanged(moveId,
21112                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21113                        break;
21114                    default:
21115                        mMoveCallbacks.notifyStatusChanged(moveId,
21116                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21117                        break;
21118                }
21119            }
21120        };
21121
21122        final MoveInfo move;
21123        if (moveCompleteApp) {
21124            // Kick off a thread to report progress estimates
21125            new Thread() {
21126                @Override
21127                public void run() {
21128                    while (true) {
21129                        try {
21130                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21131                                break;
21132                            }
21133                        } catch (InterruptedException ignored) {
21134                        }
21135
21136                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
21137                        final int progress = 10 + (int) MathUtils.constrain(
21138                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21139                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21140                    }
21141                }
21142            }.start();
21143
21144            final String dataAppName = codeFile.getName();
21145            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21146                    dataAppName, appId, seinfo, targetSdkVersion);
21147        } else {
21148            move = null;
21149        }
21150
21151        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21152
21153        final Message msg = mHandler.obtainMessage(INIT_COPY);
21154        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21155        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21156                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21157                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21158                PackageManager.INSTALL_REASON_UNKNOWN);
21159        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21160        msg.obj = params;
21161
21162        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21163                System.identityHashCode(msg.obj));
21164        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21165                System.identityHashCode(msg.obj));
21166
21167        mHandler.sendMessage(msg);
21168    }
21169
21170    @Override
21171    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21172        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21173
21174        final int realMoveId = mNextMoveId.getAndIncrement();
21175        final Bundle extras = new Bundle();
21176        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21177        mMoveCallbacks.notifyCreated(realMoveId, extras);
21178
21179        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21180            @Override
21181            public void onCreated(int moveId, Bundle extras) {
21182                // Ignored
21183            }
21184
21185            @Override
21186            public void onStatusChanged(int moveId, int status, long estMillis) {
21187                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21188            }
21189        };
21190
21191        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21192        storage.setPrimaryStorageUuid(volumeUuid, callback);
21193        return realMoveId;
21194    }
21195
21196    @Override
21197    public int getMoveStatus(int moveId) {
21198        mContext.enforceCallingOrSelfPermission(
21199                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21200        return mMoveCallbacks.mLastStatus.get(moveId);
21201    }
21202
21203    @Override
21204    public void registerMoveCallback(IPackageMoveObserver callback) {
21205        mContext.enforceCallingOrSelfPermission(
21206                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21207        mMoveCallbacks.register(callback);
21208    }
21209
21210    @Override
21211    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21212        mContext.enforceCallingOrSelfPermission(
21213                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21214        mMoveCallbacks.unregister(callback);
21215    }
21216
21217    @Override
21218    public boolean setInstallLocation(int loc) {
21219        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21220                null);
21221        if (getInstallLocation() == loc) {
21222            return true;
21223        }
21224        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21225                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21226            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21227                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21228            return true;
21229        }
21230        return false;
21231   }
21232
21233    @Override
21234    public int getInstallLocation() {
21235        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21236                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21237                PackageHelper.APP_INSTALL_AUTO);
21238    }
21239
21240    /** Called by UserManagerService */
21241    void cleanUpUser(UserManagerService userManager, int userHandle) {
21242        synchronized (mPackages) {
21243            mDirtyUsers.remove(userHandle);
21244            mUserNeedsBadging.delete(userHandle);
21245            mSettings.removeUserLPw(userHandle);
21246            mPendingBroadcasts.remove(userHandle);
21247            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21248            removeUnusedPackagesLPw(userManager, userHandle);
21249        }
21250    }
21251
21252    /**
21253     * We're removing userHandle and would like to remove any downloaded packages
21254     * that are no longer in use by any other user.
21255     * @param userHandle the user being removed
21256     */
21257    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21258        final boolean DEBUG_CLEAN_APKS = false;
21259        int [] users = userManager.getUserIds();
21260        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21261        while (psit.hasNext()) {
21262            PackageSetting ps = psit.next();
21263            if (ps.pkg == null) {
21264                continue;
21265            }
21266            final String packageName = ps.pkg.packageName;
21267            // Skip over if system app
21268            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21269                continue;
21270            }
21271            if (DEBUG_CLEAN_APKS) {
21272                Slog.i(TAG, "Checking package " + packageName);
21273            }
21274            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21275            if (keep) {
21276                if (DEBUG_CLEAN_APKS) {
21277                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21278                }
21279            } else {
21280                for (int i = 0; i < users.length; i++) {
21281                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21282                        keep = true;
21283                        if (DEBUG_CLEAN_APKS) {
21284                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21285                                    + users[i]);
21286                        }
21287                        break;
21288                    }
21289                }
21290            }
21291            if (!keep) {
21292                if (DEBUG_CLEAN_APKS) {
21293                    Slog.i(TAG, "  Removing package " + packageName);
21294                }
21295                mHandler.post(new Runnable() {
21296                    public void run() {
21297                        deletePackageX(packageName, userHandle, 0);
21298                    } //end run
21299                });
21300            }
21301        }
21302    }
21303
21304    /** Called by UserManagerService */
21305    void createNewUser(int userId, String[] disallowedPackages) {
21306        synchronized (mInstallLock) {
21307            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21308        }
21309        synchronized (mPackages) {
21310            scheduleWritePackageRestrictionsLocked(userId);
21311            scheduleWritePackageListLocked(userId);
21312            applyFactoryDefaultBrowserLPw(userId);
21313            primeDomainVerificationsLPw(userId);
21314        }
21315    }
21316
21317    void onNewUserCreated(final int userId) {
21318        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21319        // If permission review for legacy apps is required, we represent
21320        // dagerous permissions for such apps as always granted runtime
21321        // permissions to keep per user flag state whether review is needed.
21322        // Hence, if a new user is added we have to propagate dangerous
21323        // permission grants for these legacy apps.
21324        if (mPermissionReviewRequired) {
21325            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21326                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21327        }
21328    }
21329
21330    @Override
21331    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21332        mContext.enforceCallingOrSelfPermission(
21333                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21334                "Only package verification agents can read the verifier device identity");
21335
21336        synchronized (mPackages) {
21337            return mSettings.getVerifierDeviceIdentityLPw();
21338        }
21339    }
21340
21341    @Override
21342    public void setPermissionEnforced(String permission, boolean enforced) {
21343        // TODO: Now that we no longer change GID for storage, this should to away.
21344        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21345                "setPermissionEnforced");
21346        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21347            synchronized (mPackages) {
21348                if (mSettings.mReadExternalStorageEnforced == null
21349                        || mSettings.mReadExternalStorageEnforced != enforced) {
21350                    mSettings.mReadExternalStorageEnforced = enforced;
21351                    mSettings.writeLPr();
21352                }
21353            }
21354            // kill any non-foreground processes so we restart them and
21355            // grant/revoke the GID.
21356            final IActivityManager am = ActivityManager.getService();
21357            if (am != null) {
21358                final long token = Binder.clearCallingIdentity();
21359                try {
21360                    am.killProcessesBelowForeground("setPermissionEnforcement");
21361                } catch (RemoteException e) {
21362                } finally {
21363                    Binder.restoreCallingIdentity(token);
21364                }
21365            }
21366        } else {
21367            throw new IllegalArgumentException("No selective enforcement for " + permission);
21368        }
21369    }
21370
21371    @Override
21372    @Deprecated
21373    public boolean isPermissionEnforced(String permission) {
21374        return true;
21375    }
21376
21377    @Override
21378    public boolean isStorageLow() {
21379        final long token = Binder.clearCallingIdentity();
21380        try {
21381            final DeviceStorageMonitorInternal
21382                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21383            if (dsm != null) {
21384                return dsm.isMemoryLow();
21385            } else {
21386                return false;
21387            }
21388        } finally {
21389            Binder.restoreCallingIdentity(token);
21390        }
21391    }
21392
21393    @Override
21394    public IPackageInstaller getPackageInstaller() {
21395        return mInstallerService;
21396    }
21397
21398    private boolean userNeedsBadging(int userId) {
21399        int index = mUserNeedsBadging.indexOfKey(userId);
21400        if (index < 0) {
21401            final UserInfo userInfo;
21402            final long token = Binder.clearCallingIdentity();
21403            try {
21404                userInfo = sUserManager.getUserInfo(userId);
21405            } finally {
21406                Binder.restoreCallingIdentity(token);
21407            }
21408            final boolean b;
21409            if (userInfo != null && userInfo.isManagedProfile()) {
21410                b = true;
21411            } else {
21412                b = false;
21413            }
21414            mUserNeedsBadging.put(userId, b);
21415            return b;
21416        }
21417        return mUserNeedsBadging.valueAt(index);
21418    }
21419
21420    @Override
21421    public KeySet getKeySetByAlias(String packageName, String alias) {
21422        if (packageName == null || alias == null) {
21423            return null;
21424        }
21425        synchronized(mPackages) {
21426            final PackageParser.Package pkg = mPackages.get(packageName);
21427            if (pkg == null) {
21428                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21429                throw new IllegalArgumentException("Unknown package: " + packageName);
21430            }
21431            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21432            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21433        }
21434    }
21435
21436    @Override
21437    public KeySet getSigningKeySet(String packageName) {
21438        if (packageName == null) {
21439            return null;
21440        }
21441        synchronized(mPackages) {
21442            final PackageParser.Package pkg = mPackages.get(packageName);
21443            if (pkg == null) {
21444                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21445                throw new IllegalArgumentException("Unknown package: " + packageName);
21446            }
21447            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21448                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21449                throw new SecurityException("May not access signing KeySet of other apps.");
21450            }
21451            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21452            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21453        }
21454    }
21455
21456    @Override
21457    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21458        if (packageName == null || ks == null) {
21459            return false;
21460        }
21461        synchronized(mPackages) {
21462            final PackageParser.Package pkg = mPackages.get(packageName);
21463            if (pkg == null) {
21464                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21465                throw new IllegalArgumentException("Unknown package: " + packageName);
21466            }
21467            IBinder ksh = ks.getToken();
21468            if (ksh instanceof KeySetHandle) {
21469                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21470                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21471            }
21472            return false;
21473        }
21474    }
21475
21476    @Override
21477    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21478        if (packageName == null || ks == null) {
21479            return false;
21480        }
21481        synchronized(mPackages) {
21482            final PackageParser.Package pkg = mPackages.get(packageName);
21483            if (pkg == null) {
21484                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21485                throw new IllegalArgumentException("Unknown package: " + packageName);
21486            }
21487            IBinder ksh = ks.getToken();
21488            if (ksh instanceof KeySetHandle) {
21489                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21490                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21491            }
21492            return false;
21493        }
21494    }
21495
21496    private void deletePackageIfUnusedLPr(final String packageName) {
21497        PackageSetting ps = mSettings.mPackages.get(packageName);
21498        if (ps == null) {
21499            return;
21500        }
21501        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21502            // TODO Implement atomic delete if package is unused
21503            // It is currently possible that the package will be deleted even if it is installed
21504            // after this method returns.
21505            mHandler.post(new Runnable() {
21506                public void run() {
21507                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21508                }
21509            });
21510        }
21511    }
21512
21513    /**
21514     * Check and throw if the given before/after packages would be considered a
21515     * downgrade.
21516     */
21517    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21518            throws PackageManagerException {
21519        if (after.versionCode < before.mVersionCode) {
21520            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21521                    "Update version code " + after.versionCode + " is older than current "
21522                    + before.mVersionCode);
21523        } else if (after.versionCode == before.mVersionCode) {
21524            if (after.baseRevisionCode < before.baseRevisionCode) {
21525                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21526                        "Update base revision code " + after.baseRevisionCode
21527                        + " is older than current " + before.baseRevisionCode);
21528            }
21529
21530            if (!ArrayUtils.isEmpty(after.splitNames)) {
21531                for (int i = 0; i < after.splitNames.length; i++) {
21532                    final String splitName = after.splitNames[i];
21533                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21534                    if (j != -1) {
21535                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21536                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21537                                    "Update split " + splitName + " revision code "
21538                                    + after.splitRevisionCodes[i] + " is older than current "
21539                                    + before.splitRevisionCodes[j]);
21540                        }
21541                    }
21542                }
21543            }
21544        }
21545    }
21546
21547    private static class MoveCallbacks extends Handler {
21548        private static final int MSG_CREATED = 1;
21549        private static final int MSG_STATUS_CHANGED = 2;
21550
21551        private final RemoteCallbackList<IPackageMoveObserver>
21552                mCallbacks = new RemoteCallbackList<>();
21553
21554        private final SparseIntArray mLastStatus = new SparseIntArray();
21555
21556        public MoveCallbacks(Looper looper) {
21557            super(looper);
21558        }
21559
21560        public void register(IPackageMoveObserver callback) {
21561            mCallbacks.register(callback);
21562        }
21563
21564        public void unregister(IPackageMoveObserver callback) {
21565            mCallbacks.unregister(callback);
21566        }
21567
21568        @Override
21569        public void handleMessage(Message msg) {
21570            final SomeArgs args = (SomeArgs) msg.obj;
21571            final int n = mCallbacks.beginBroadcast();
21572            for (int i = 0; i < n; i++) {
21573                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21574                try {
21575                    invokeCallback(callback, msg.what, args);
21576                } catch (RemoteException ignored) {
21577                }
21578            }
21579            mCallbacks.finishBroadcast();
21580            args.recycle();
21581        }
21582
21583        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21584                throws RemoteException {
21585            switch (what) {
21586                case MSG_CREATED: {
21587                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21588                    break;
21589                }
21590                case MSG_STATUS_CHANGED: {
21591                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21592                    break;
21593                }
21594            }
21595        }
21596
21597        private void notifyCreated(int moveId, Bundle extras) {
21598            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21599
21600            final SomeArgs args = SomeArgs.obtain();
21601            args.argi1 = moveId;
21602            args.arg2 = extras;
21603            obtainMessage(MSG_CREATED, args).sendToTarget();
21604        }
21605
21606        private void notifyStatusChanged(int moveId, int status) {
21607            notifyStatusChanged(moveId, status, -1);
21608        }
21609
21610        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21611            Slog.v(TAG, "Move " + moveId + " status " + status);
21612
21613            final SomeArgs args = SomeArgs.obtain();
21614            args.argi1 = moveId;
21615            args.argi2 = status;
21616            args.arg3 = estMillis;
21617            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21618
21619            synchronized (mLastStatus) {
21620                mLastStatus.put(moveId, status);
21621            }
21622        }
21623    }
21624
21625    private final static class OnPermissionChangeListeners extends Handler {
21626        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21627
21628        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21629                new RemoteCallbackList<>();
21630
21631        public OnPermissionChangeListeners(Looper looper) {
21632            super(looper);
21633        }
21634
21635        @Override
21636        public void handleMessage(Message msg) {
21637            switch (msg.what) {
21638                case MSG_ON_PERMISSIONS_CHANGED: {
21639                    final int uid = msg.arg1;
21640                    handleOnPermissionsChanged(uid);
21641                } break;
21642            }
21643        }
21644
21645        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21646            mPermissionListeners.register(listener);
21647
21648        }
21649
21650        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21651            mPermissionListeners.unregister(listener);
21652        }
21653
21654        public void onPermissionsChanged(int uid) {
21655            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21656                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21657            }
21658        }
21659
21660        private void handleOnPermissionsChanged(int uid) {
21661            final int count = mPermissionListeners.beginBroadcast();
21662            try {
21663                for (int i = 0; i < count; i++) {
21664                    IOnPermissionsChangeListener callback = mPermissionListeners
21665                            .getBroadcastItem(i);
21666                    try {
21667                        callback.onPermissionsChanged(uid);
21668                    } catch (RemoteException e) {
21669                        Log.e(TAG, "Permission listener is dead", e);
21670                    }
21671                }
21672            } finally {
21673                mPermissionListeners.finishBroadcast();
21674            }
21675        }
21676    }
21677
21678    private class PackageManagerInternalImpl extends PackageManagerInternal {
21679        @Override
21680        public void setLocationPackagesProvider(PackagesProvider provider) {
21681            synchronized (mPackages) {
21682                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21683            }
21684        }
21685
21686        @Override
21687        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21688            synchronized (mPackages) {
21689                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21690            }
21691        }
21692
21693        @Override
21694        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21695            synchronized (mPackages) {
21696                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21697            }
21698        }
21699
21700        @Override
21701        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21702            synchronized (mPackages) {
21703                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21704            }
21705        }
21706
21707        @Override
21708        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21709            synchronized (mPackages) {
21710                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21711            }
21712        }
21713
21714        @Override
21715        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21716            synchronized (mPackages) {
21717                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21718            }
21719        }
21720
21721        @Override
21722        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21723            synchronized (mPackages) {
21724                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21725                        packageName, userId);
21726            }
21727        }
21728
21729        @Override
21730        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21731            synchronized (mPackages) {
21732                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21733                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21734                        packageName, userId);
21735            }
21736        }
21737
21738        @Override
21739        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21740            synchronized (mPackages) {
21741                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21742                        packageName, userId);
21743            }
21744        }
21745
21746        @Override
21747        public void setKeepUninstalledPackages(final List<String> packageList) {
21748            Preconditions.checkNotNull(packageList);
21749            List<String> removedFromList = null;
21750            synchronized (mPackages) {
21751                if (mKeepUninstalledPackages != null) {
21752                    final int packagesCount = mKeepUninstalledPackages.size();
21753                    for (int i = 0; i < packagesCount; i++) {
21754                        String oldPackage = mKeepUninstalledPackages.get(i);
21755                        if (packageList != null && packageList.contains(oldPackage)) {
21756                            continue;
21757                        }
21758                        if (removedFromList == null) {
21759                            removedFromList = new ArrayList<>();
21760                        }
21761                        removedFromList.add(oldPackage);
21762                    }
21763                }
21764                mKeepUninstalledPackages = new ArrayList<>(packageList);
21765                if (removedFromList != null) {
21766                    final int removedCount = removedFromList.size();
21767                    for (int i = 0; i < removedCount; i++) {
21768                        deletePackageIfUnusedLPr(removedFromList.get(i));
21769                    }
21770                }
21771            }
21772        }
21773
21774        @Override
21775        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21776            synchronized (mPackages) {
21777                // If we do not support permission review, done.
21778                if (!mPermissionReviewRequired) {
21779                    return false;
21780                }
21781
21782                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21783                if (packageSetting == null) {
21784                    return false;
21785                }
21786
21787                // Permission review applies only to apps not supporting the new permission model.
21788                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21789                    return false;
21790                }
21791
21792                // Legacy apps have the permission and get user consent on launch.
21793                PermissionsState permissionsState = packageSetting.getPermissionsState();
21794                return permissionsState.isPermissionReviewRequired(userId);
21795            }
21796        }
21797
21798        @Override
21799        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21800            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21801        }
21802
21803        @Override
21804        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21805                int userId) {
21806            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21807        }
21808
21809        @Override
21810        public void setDeviceAndProfileOwnerPackages(
21811                int deviceOwnerUserId, String deviceOwnerPackage,
21812                SparseArray<String> profileOwnerPackages) {
21813            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21814                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21815        }
21816
21817        @Override
21818        public boolean isPackageDataProtected(int userId, String packageName) {
21819            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21820        }
21821
21822        @Override
21823        public boolean isPackageEphemeral(int userId, String packageName) {
21824            synchronized (mPackages) {
21825                PackageParser.Package p = mPackages.get(packageName);
21826                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21827            }
21828        }
21829
21830        @Override
21831        public boolean wasPackageEverLaunched(String packageName, int userId) {
21832            synchronized (mPackages) {
21833                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21834            }
21835        }
21836
21837        @Override
21838        public void grantRuntimePermission(String packageName, String name, int userId,
21839                boolean overridePolicy) {
21840            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21841                    overridePolicy);
21842        }
21843
21844        @Override
21845        public void revokeRuntimePermission(String packageName, String name, int userId,
21846                boolean overridePolicy) {
21847            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21848                    overridePolicy);
21849        }
21850
21851        @Override
21852        public String getNameForUid(int uid) {
21853            return PackageManagerService.this.getNameForUid(uid);
21854        }
21855
21856        @Override
21857        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21858                Intent origIntent, String resolvedType, Intent launchIntent,
21859                String callingPackage, int userId) {
21860            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21861                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21862        }
21863
21864        public String getSetupWizardPackageName() {
21865            return mSetupWizardPackage;
21866        }
21867    }
21868
21869    @Override
21870    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21871        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21872        synchronized (mPackages) {
21873            final long identity = Binder.clearCallingIdentity();
21874            try {
21875                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21876                        packageNames, userId);
21877            } finally {
21878                Binder.restoreCallingIdentity(identity);
21879            }
21880        }
21881    }
21882
21883    private static void enforceSystemOrPhoneCaller(String tag) {
21884        int callingUid = Binder.getCallingUid();
21885        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21886            throw new SecurityException(
21887                    "Cannot call " + tag + " from UID " + callingUid);
21888        }
21889    }
21890
21891    boolean isHistoricalPackageUsageAvailable() {
21892        return mPackageUsage.isHistoricalPackageUsageAvailable();
21893    }
21894
21895    /**
21896     * Return a <b>copy</b> of the collection of packages known to the package manager.
21897     * @return A copy of the values of mPackages.
21898     */
21899    Collection<PackageParser.Package> getPackages() {
21900        synchronized (mPackages) {
21901            return new ArrayList<>(mPackages.values());
21902        }
21903    }
21904
21905    /**
21906     * Logs process start information (including base APK hash) to the security log.
21907     * @hide
21908     */
21909    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21910            String apkFile, int pid) {
21911        if (!SecurityLog.isLoggingEnabled()) {
21912            return;
21913        }
21914        Bundle data = new Bundle();
21915        data.putLong("startTimestamp", System.currentTimeMillis());
21916        data.putString("processName", processName);
21917        data.putInt("uid", uid);
21918        data.putString("seinfo", seinfo);
21919        data.putString("apkFile", apkFile);
21920        data.putInt("pid", pid);
21921        Message msg = mProcessLoggingHandler.obtainMessage(
21922                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21923        msg.setData(data);
21924        mProcessLoggingHandler.sendMessage(msg);
21925    }
21926
21927    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21928        return mCompilerStats.getPackageStats(pkgName);
21929    }
21930
21931    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21932        return getOrCreateCompilerPackageStats(pkg.packageName);
21933    }
21934
21935    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21936        return mCompilerStats.getOrCreatePackageStats(pkgName);
21937    }
21938
21939    public void deleteCompilerPackageStats(String pkgName) {
21940        mCompilerStats.deletePackageStats(pkgName);
21941    }
21942
21943    @Override
21944    public int getInstallReason(String packageName, int userId) {
21945        enforceCrossUserPermission(Binder.getCallingUid(), userId,
21946                true /* requireFullPermission */, false /* checkShell */,
21947                "get install reason");
21948        synchronized (mPackages) {
21949            final PackageSetting ps = mSettings.mPackages.get(packageName);
21950            if (ps != null) {
21951                return ps.getInstallReason(userId);
21952            }
21953        }
21954        return PackageManager.INSTALL_REASON_UNKNOWN;
21955    }
21956}
21957