PackageManagerService.java revision fff1e744e3f72094e81b01134752d8f48c86d8e5
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.
1717            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1718                    >= Build.VERSION_CODES.M) {
1719                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1720            }
1721
1722            final boolean update = res.removedInfo != null
1723                    && res.removedInfo.removedPackage != null;
1724
1725            // If this is the first time we have child packages for a disabled privileged
1726            // app that had no children, we grant requested runtime permissions to the new
1727            // children if the parent on the system image had them already granted.
1728            if (res.pkg.parentPackage != null) {
1729                synchronized (mPackages) {
1730                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1731                }
1732            }
1733
1734            synchronized (mPackages) {
1735                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1736            }
1737
1738            final String packageName = res.pkg.applicationInfo.packageName;
1739
1740            // Determine the set of users who are adding this package for
1741            // the first time vs. those who are seeing an update.
1742            int[] firstUsers = EMPTY_INT_ARRAY;
1743            int[] updateUsers = EMPTY_INT_ARRAY;
1744            if (res.origUsers == null || res.origUsers.length == 0) {
1745                firstUsers = res.newUsers;
1746            } else {
1747                for (int newUser : res.newUsers) {
1748                    boolean isNew = true;
1749                    for (int origUser : res.origUsers) {
1750                        if (origUser == newUser) {
1751                            isNew = false;
1752                            break;
1753                        }
1754                    }
1755                    if (isNew) {
1756                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1757                    } else {
1758                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1759                    }
1760                }
1761            }
1762
1763            // Send installed broadcasts if the install/update is not ephemeral
1764            if (!isEphemeral(res.pkg)) {
1765                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1766
1767                // Send added for users that see the package for the first time
1768                // sendPackageAddedForNewUsers also deals with system apps
1769                int appId = UserHandle.getAppId(res.uid);
1770                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1771                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1772
1773                // Send added for users that don't see the package for the first time
1774                Bundle extras = new Bundle(1);
1775                extras.putInt(Intent.EXTRA_UID, res.uid);
1776                if (update) {
1777                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1778                }
1779                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1780                        extras, 0 /*flags*/, null /*targetPackage*/,
1781                        null /*finishedReceiver*/, updateUsers);
1782
1783                // Send replaced for users that don't see the package for the first time
1784                if (update) {
1785                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1786                            packageName, extras, 0 /*flags*/,
1787                            null /*targetPackage*/, null /*finishedReceiver*/,
1788                            updateUsers);
1789                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1790                            null /*package*/, null /*extras*/, 0 /*flags*/,
1791                            packageName /*targetPackage*/,
1792                            null /*finishedReceiver*/, updateUsers);
1793                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1794                    // First-install and we did a restore, so we're responsible for the
1795                    // first-launch broadcast.
1796                    if (DEBUG_BACKUP) {
1797                        Slog.i(TAG, "Post-restore of " + packageName
1798                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1799                    }
1800                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1801                }
1802
1803                // Send broadcast package appeared if forward locked/external for all users
1804                // treat asec-hosted packages like removable media on upgrade
1805                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1806                    if (DEBUG_INSTALL) {
1807                        Slog.i(TAG, "upgrading pkg " + res.pkg
1808                                + " is ASEC-hosted -> AVAILABLE");
1809                    }
1810                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1811                    ArrayList<String> pkgList = new ArrayList<>(1);
1812                    pkgList.add(packageName);
1813                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1814                }
1815            }
1816
1817            // Work that needs to happen on first install within each user
1818            if (firstUsers != null && firstUsers.length > 0) {
1819                synchronized (mPackages) {
1820                    for (int userId : firstUsers) {
1821                        // If this app is a browser and it's newly-installed for some
1822                        // users, clear any default-browser state in those users. The
1823                        // app's nature doesn't depend on the user, so we can just check
1824                        // its browser nature in any user and generalize.
1825                        if (packageIsBrowser(packageName, userId)) {
1826                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1827                        }
1828
1829                        // We may also need to apply pending (restored) runtime
1830                        // permission grants within these users.
1831                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1832                    }
1833                }
1834            }
1835
1836            // Log current value of "unknown sources" setting
1837            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1838                    getUnknownSourcesSettings());
1839
1840            // Force a gc to clear up things
1841            Runtime.getRuntime().gc();
1842
1843            // Remove the replaced package's older resources safely now
1844            // We delete after a gc for applications  on sdcard.
1845            if (res.removedInfo != null && res.removedInfo.args != null) {
1846                synchronized (mInstallLock) {
1847                    res.removedInfo.args.doPostDeleteLI(true);
1848                }
1849            }
1850        }
1851
1852        // If someone is watching installs - notify them
1853        if (installObserver != null) {
1854            try {
1855                Bundle extras = extrasForInstallResult(res);
1856                installObserver.onPackageInstalled(res.name, res.returnCode,
1857                        res.returnMsg, extras);
1858            } catch (RemoteException e) {
1859                Slog.i(TAG, "Observer no longer exists.");
1860            }
1861        }
1862    }
1863
1864    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1865            PackageParser.Package pkg) {
1866        if (pkg.parentPackage == null) {
1867            return;
1868        }
1869        if (pkg.requestedPermissions == null) {
1870            return;
1871        }
1872        final PackageSetting disabledSysParentPs = mSettings
1873                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1874        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1875                || !disabledSysParentPs.isPrivileged()
1876                || (disabledSysParentPs.childPackageNames != null
1877                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1878            return;
1879        }
1880        final int[] allUserIds = sUserManager.getUserIds();
1881        final int permCount = pkg.requestedPermissions.size();
1882        for (int i = 0; i < permCount; i++) {
1883            String permission = pkg.requestedPermissions.get(i);
1884            BasePermission bp = mSettings.mPermissions.get(permission);
1885            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1886                continue;
1887            }
1888            for (int userId : allUserIds) {
1889                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1890                        permission, userId)) {
1891                    grantRuntimePermission(pkg.packageName, permission, userId);
1892                }
1893            }
1894        }
1895    }
1896
1897    private StorageEventListener mStorageListener = new StorageEventListener() {
1898        @Override
1899        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1900            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1901                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1902                    final String volumeUuid = vol.getFsUuid();
1903
1904                    // Clean up any users or apps that were removed or recreated
1905                    // while this volume was missing
1906                    reconcileUsers(volumeUuid);
1907                    reconcileApps(volumeUuid);
1908
1909                    // Clean up any install sessions that expired or were
1910                    // cancelled while this volume was missing
1911                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1912
1913                    loadPrivatePackages(vol);
1914
1915                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1916                    unloadPrivatePackages(vol);
1917                }
1918            }
1919
1920            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1921                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1922                    updateExternalMediaStatus(true, false);
1923                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1924                    updateExternalMediaStatus(false, false);
1925                }
1926            }
1927        }
1928
1929        @Override
1930        public void onVolumeForgotten(String fsUuid) {
1931            if (TextUtils.isEmpty(fsUuid)) {
1932                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1933                return;
1934            }
1935
1936            // Remove any apps installed on the forgotten volume
1937            synchronized (mPackages) {
1938                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1939                for (PackageSetting ps : packages) {
1940                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1941                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1942                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1943
1944                    // Try very hard to release any references to this package
1945                    // so we don't risk the system server being killed due to
1946                    // open FDs
1947                    AttributeCache.instance().removePackage(ps.name);
1948                }
1949
1950                mSettings.onVolumeForgotten(fsUuid);
1951                mSettings.writeLPr();
1952            }
1953        }
1954    };
1955
1956    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1957            String[] grantedPermissions) {
1958        for (int userId : userIds) {
1959            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1960        }
1961
1962        // We could have touched GID membership, so flush out packages.list
1963        synchronized (mPackages) {
1964            mSettings.writePackageListLPr();
1965        }
1966    }
1967
1968    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1969            String[] grantedPermissions) {
1970        SettingBase sb = (SettingBase) pkg.mExtras;
1971        if (sb == null) {
1972            return;
1973        }
1974
1975        PermissionsState permissionsState = sb.getPermissionsState();
1976
1977        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1978                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
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                // Installer cannot change immutable permissions.
1990                if ((flags & immutableFlags) == 0) {
1991                    grantRuntimePermission(pkg.packageName, permission, userId);
1992                }
1993            }
1994        }
1995    }
1996
1997    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1998        Bundle extras = null;
1999        switch (res.returnCode) {
2000            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2001                extras = new Bundle();
2002                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2003                        res.origPermission);
2004                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2005                        res.origPackage);
2006                break;
2007            }
2008            case PackageManager.INSTALL_SUCCEEDED: {
2009                extras = new Bundle();
2010                extras.putBoolean(Intent.EXTRA_REPLACING,
2011                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2012                break;
2013            }
2014        }
2015        return extras;
2016    }
2017
2018    void scheduleWriteSettingsLocked() {
2019        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2020            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2021        }
2022    }
2023
2024    void scheduleWritePackageListLocked(int userId) {
2025        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2026            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2027            msg.arg1 = userId;
2028            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2029        }
2030    }
2031
2032    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2033        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2034        scheduleWritePackageRestrictionsLocked(userId);
2035    }
2036
2037    void scheduleWritePackageRestrictionsLocked(int userId) {
2038        final int[] userIds = (userId == UserHandle.USER_ALL)
2039                ? sUserManager.getUserIds() : new int[]{userId};
2040        for (int nextUserId : userIds) {
2041            if (!sUserManager.exists(nextUserId)) return;
2042            mDirtyUsers.add(nextUserId);
2043            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2044                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2045            }
2046        }
2047    }
2048
2049    public static PackageManagerService main(Context context, Installer installer,
2050            boolean factoryTest, boolean onlyCore) {
2051        // Self-check for initial settings.
2052        PackageManagerServiceCompilerMapping.checkProperties();
2053
2054        PackageManagerService m = new PackageManagerService(context, installer,
2055                factoryTest, onlyCore);
2056        m.enableSystemUserPackages();
2057        ServiceManager.addService("package", m);
2058        return m;
2059    }
2060
2061    private void enableSystemUserPackages() {
2062        if (!UserManager.isSplitSystemUser()) {
2063            return;
2064        }
2065        // For system user, enable apps based on the following conditions:
2066        // - app is whitelisted or belong to one of these groups:
2067        //   -- system app which has no launcher icons
2068        //   -- system app which has INTERACT_ACROSS_USERS permission
2069        //   -- system IME app
2070        // - app is not in the blacklist
2071        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2072        Set<String> enableApps = new ArraySet<>();
2073        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2074                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2075                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2076        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2077        enableApps.addAll(wlApps);
2078        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2079                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2080        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2081        enableApps.removeAll(blApps);
2082        Log.i(TAG, "Applications installed for system user: " + enableApps);
2083        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2084                UserHandle.SYSTEM);
2085        final int allAppsSize = allAps.size();
2086        synchronized (mPackages) {
2087            for (int i = 0; i < allAppsSize; i++) {
2088                String pName = allAps.get(i);
2089                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2090                // Should not happen, but we shouldn't be failing if it does
2091                if (pkgSetting == null) {
2092                    continue;
2093                }
2094                boolean install = enableApps.contains(pName);
2095                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2096                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2097                            + " for system user");
2098                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2099                }
2100            }
2101        }
2102    }
2103
2104    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2105        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2106                Context.DISPLAY_SERVICE);
2107        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2108    }
2109
2110    /**
2111     * Requests that files preopted on a secondary system partition be copied to the data partition
2112     * if possible.  Note that the actual copying of the files is accomplished by init for security
2113     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2114     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2115     */
2116    private static void requestCopyPreoptedFiles() {
2117        final int WAIT_TIME_MS = 100;
2118        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2119        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2120            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2121            // We will wait for up to 100 seconds.
2122            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2123            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2124                try {
2125                    Thread.sleep(WAIT_TIME_MS);
2126                } catch (InterruptedException e) {
2127                    // Do nothing
2128                }
2129                if (SystemClock.uptimeMillis() > timeEnd) {
2130                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2131                    Slog.wtf(TAG, "cppreopt did not finish!");
2132                    break;
2133                }
2134            }
2135        }
2136    }
2137
2138    public PackageManagerService(Context context, Installer installer,
2139            boolean factoryTest, boolean onlyCore) {
2140        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2141        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2142                SystemClock.uptimeMillis());
2143
2144        if (mSdkVersion <= 0) {
2145            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2146        }
2147
2148        mContext = context;
2149
2150        mPermissionReviewRequired = context.getResources().getBoolean(
2151                R.bool.config_permissionReviewRequired);
2152
2153        mFactoryTest = factoryTest;
2154        mOnlyCore = onlyCore;
2155        mMetrics = new DisplayMetrics();
2156        mSettings = new Settings(mPackages);
2157        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2158                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2159        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2160                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2161        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2162                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2163        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2164                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2165        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2166                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2167        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2168                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2169
2170        String separateProcesses = SystemProperties.get("debug.separate_processes");
2171        if (separateProcesses != null && separateProcesses.length() > 0) {
2172            if ("*".equals(separateProcesses)) {
2173                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2174                mSeparateProcesses = null;
2175                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2176            } else {
2177                mDefParseFlags = 0;
2178                mSeparateProcesses = separateProcesses.split(",");
2179                Slog.w(TAG, "Running with debug.separate_processes: "
2180                        + separateProcesses);
2181            }
2182        } else {
2183            mDefParseFlags = 0;
2184            mSeparateProcesses = null;
2185        }
2186
2187        mInstaller = installer;
2188        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2189                "*dexopt*");
2190        mDexManager = new DexManager();
2191        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2192
2193        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2194                FgThread.get().getLooper());
2195
2196        getDefaultDisplayMetrics(context, mMetrics);
2197
2198        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2199        SystemConfig systemConfig = SystemConfig.getInstance();
2200        mGlobalGids = systemConfig.getGlobalGids();
2201        mSystemPermissions = systemConfig.getSystemPermissions();
2202        mAvailableFeatures = systemConfig.getAvailableFeatures();
2203        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2204
2205        mProtectedPackages = new ProtectedPackages(mContext);
2206
2207        synchronized (mInstallLock) {
2208        // writer
2209        synchronized (mPackages) {
2210            mHandlerThread = new ServiceThread(TAG,
2211                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2212            mHandlerThread.start();
2213            mHandler = new PackageHandler(mHandlerThread.getLooper());
2214            mProcessLoggingHandler = new ProcessLoggingHandler();
2215            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2216
2217            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2218
2219            File dataDir = Environment.getDataDirectory();
2220            mAppInstallDir = new File(dataDir, "app");
2221            mAppLib32InstallDir = new File(dataDir, "app-lib");
2222            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2223            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2224            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2225
2226            sUserManager = new UserManagerService(context, this, mPackages);
2227
2228            // Propagate permission configuration in to package manager.
2229            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2230                    = systemConfig.getPermissions();
2231            for (int i=0; i<permConfig.size(); i++) {
2232                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2233                BasePermission bp = mSettings.mPermissions.get(perm.name);
2234                if (bp == null) {
2235                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2236                    mSettings.mPermissions.put(perm.name, bp);
2237                }
2238                if (perm.gids != null) {
2239                    bp.setGids(perm.gids, perm.perUser);
2240                }
2241            }
2242
2243            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2244            for (int i=0; i<libConfig.size(); i++) {
2245                mSharedLibraries.put(libConfig.keyAt(i),
2246                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2247            }
2248
2249            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2250
2251            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2252            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2253            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2254
2255            // Clean up orphaned packages for which the code path doesn't exist
2256            // and they are an update to a system app - caused by bug/32321269
2257            final int packageSettingCount = mSettings.mPackages.size();
2258            for (int i = packageSettingCount - 1; i >= 0; i--) {
2259                PackageSetting ps = mSettings.mPackages.valueAt(i);
2260                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2261                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2262                    mSettings.mPackages.removeAt(i);
2263                    mSettings.enableSystemPackageLPw(ps.name);
2264                }
2265            }
2266
2267            if (mFirstBoot) {
2268                requestCopyPreoptedFiles();
2269            }
2270
2271            String customResolverActivity = Resources.getSystem().getString(
2272                    R.string.config_customResolverActivity);
2273            if (TextUtils.isEmpty(customResolverActivity)) {
2274                customResolverActivity = null;
2275            } else {
2276                mCustomResolverComponentName = ComponentName.unflattenFromString(
2277                        customResolverActivity);
2278            }
2279
2280            long startTime = SystemClock.uptimeMillis();
2281
2282            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2283                    startTime);
2284
2285            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2286            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2287
2288            if (bootClassPath == null) {
2289                Slog.w(TAG, "No BOOTCLASSPATH found!");
2290            }
2291
2292            if (systemServerClassPath == null) {
2293                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2294            }
2295
2296            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2297            final String[] dexCodeInstructionSets =
2298                    getDexCodeInstructionSets(
2299                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2300
2301            /**
2302             * Ensure all external libraries have had dexopt run on them.
2303             */
2304            if (mSharedLibraries.size() > 0) {
2305                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2306                // NOTE: For now, we're compiling these system "shared libraries"
2307                // (and framework jars) into all available architectures. It's possible
2308                // to compile them only when we come across an app that uses them (there's
2309                // already logic for that in scanPackageLI) but that adds some complexity.
2310                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2311                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2312                        final String lib = libEntry.path;
2313                        if (lib == null) {
2314                            continue;
2315                        }
2316
2317                        try {
2318                            // Shared libraries do not have profiles so we perform a full
2319                            // AOT compilation (if needed).
2320                            int dexoptNeeded = DexFile.getDexOptNeeded(
2321                                    lib, dexCodeInstructionSet,
2322                                    getCompilerFilterForReason(REASON_SHARED_APK),
2323                                    false /* newProfile */);
2324                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2325                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2326                                        dexCodeInstructionSet, dexoptNeeded, null,
2327                                        DEXOPT_PUBLIC,
2328                                        getCompilerFilterForReason(REASON_SHARED_APK),
2329                                        StorageManager.UUID_PRIVATE_INTERNAL,
2330                                        SKIP_SHARED_LIBRARY_CHECK);
2331                            }
2332                        } catch (FileNotFoundException e) {
2333                            Slog.w(TAG, "Library not found: " + lib);
2334                        } catch (IOException | InstallerException e) {
2335                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2336                                    + e.getMessage());
2337                        }
2338                    }
2339                }
2340                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2341            }
2342
2343            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2344
2345            final VersionInfo ver = mSettings.getInternalVersion();
2346            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2347
2348            // when upgrading from pre-M, promote system app permissions from install to runtime
2349            mPromoteSystemApps =
2350                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2351
2352            // When upgrading from pre-N, we need to handle package extraction like first boot,
2353            // as there is no profiling data available.
2354            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2355
2356            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2357
2358            // save off the names of pre-existing system packages prior to scanning; we don't
2359            // want to automatically grant runtime permissions for new system apps
2360            if (mPromoteSystemApps) {
2361                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2362                while (pkgSettingIter.hasNext()) {
2363                    PackageSetting ps = pkgSettingIter.next();
2364                    if (isSystemApp(ps)) {
2365                        mExistingSystemPackages.add(ps.name);
2366                    }
2367                }
2368            }
2369
2370            mCacheDir = preparePackageParserCache(mIsUpgrade);
2371
2372            // Set flag to monitor and not change apk file paths when
2373            // scanning install directories.
2374            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2375
2376            if (mIsUpgrade || mFirstBoot) {
2377                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2378            }
2379
2380            // Collect vendor overlay packages. (Do this before scanning any apps.)
2381            // For security and version matching reason, only consider
2382            // overlay packages if they reside in the right directory.
2383            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2384            if (overlayThemeDir.isEmpty()) {
2385                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2386            }
2387            if (!overlayThemeDir.isEmpty()) {
2388                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2389                        | PackageParser.PARSE_IS_SYSTEM
2390                        | PackageParser.PARSE_IS_SYSTEM_DIR
2391                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2392            }
2393            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2394                    | PackageParser.PARSE_IS_SYSTEM
2395                    | PackageParser.PARSE_IS_SYSTEM_DIR
2396                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2397
2398            // Find base frameworks (resource packages without code).
2399            scanDirTracedLI(frameworkDir, mDefParseFlags
2400                    | PackageParser.PARSE_IS_SYSTEM
2401                    | PackageParser.PARSE_IS_SYSTEM_DIR
2402                    | PackageParser.PARSE_IS_PRIVILEGED,
2403                    scanFlags | SCAN_NO_DEX, 0);
2404
2405            // Collected privileged system packages.
2406            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2407            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2408                    | PackageParser.PARSE_IS_SYSTEM
2409                    | PackageParser.PARSE_IS_SYSTEM_DIR
2410                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2411
2412            // Collect ordinary system packages.
2413            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2414            scanDirTracedLI(systemAppDir, mDefParseFlags
2415                    | PackageParser.PARSE_IS_SYSTEM
2416                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2417
2418            // Collect all vendor packages.
2419            File vendorAppDir = new File("/vendor/app");
2420            try {
2421                vendorAppDir = vendorAppDir.getCanonicalFile();
2422            } catch (IOException e) {
2423                // failed to look up canonical path, continue with original one
2424            }
2425            scanDirTracedLI(vendorAppDir, mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2428
2429            // Collect all OEM packages.
2430            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2431            scanDirTracedLI(oemAppDir, mDefParseFlags
2432                    | PackageParser.PARSE_IS_SYSTEM
2433                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2434
2435            // Prune any system packages that no longer exist.
2436            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2437            if (!mOnlyCore) {
2438                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2439                while (psit.hasNext()) {
2440                    PackageSetting ps = psit.next();
2441
2442                    /*
2443                     * If this is not a system app, it can't be a
2444                     * disable system app.
2445                     */
2446                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2447                        continue;
2448                    }
2449
2450                    /*
2451                     * If the package is scanned, it's not erased.
2452                     */
2453                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2454                    if (scannedPkg != null) {
2455                        /*
2456                         * If the system app is both scanned and in the
2457                         * disabled packages list, then it must have been
2458                         * added via OTA. Remove it from the currently
2459                         * scanned package so the previously user-installed
2460                         * application can be scanned.
2461                         */
2462                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2463                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2464                                    + ps.name + "; removing system app.  Last known codePath="
2465                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2466                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2467                                    + scannedPkg.mVersionCode);
2468                            removePackageLI(scannedPkg, true);
2469                            mExpectingBetter.put(ps.name, ps.codePath);
2470                        }
2471
2472                        continue;
2473                    }
2474
2475                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2476                        psit.remove();
2477                        logCriticalInfo(Log.WARN, "System package " + ps.name
2478                                + " no longer exists; it's data will be wiped");
2479                        // Actual deletion of code and data will be handled by later
2480                        // reconciliation step
2481                    } else {
2482                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2483                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2484                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2485                        }
2486                    }
2487                }
2488            }
2489
2490            //look for any incomplete package installations
2491            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2492            for (int i = 0; i < deletePkgsList.size(); i++) {
2493                // Actual deletion of code and data will be handled by later
2494                // reconciliation step
2495                final String packageName = deletePkgsList.get(i).name;
2496                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2497                synchronized (mPackages) {
2498                    mSettings.removePackageLPw(packageName);
2499                }
2500            }
2501
2502            //delete tmp files
2503            deleteTempPackageFiles();
2504
2505            // Remove any shared userIDs that have no associated packages
2506            mSettings.pruneSharedUsersLPw();
2507
2508            if (!mOnlyCore) {
2509                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2510                        SystemClock.uptimeMillis());
2511                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2512
2513                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2514                        | PackageParser.PARSE_FORWARD_LOCK,
2515                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2516
2517                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2518                        | PackageParser.PARSE_IS_EPHEMERAL,
2519                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2520
2521                /**
2522                 * Remove disable package settings for any updated system
2523                 * apps that were removed via an OTA. If they're not a
2524                 * previously-updated app, remove them completely.
2525                 * Otherwise, just revoke their system-level permissions.
2526                 */
2527                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2528                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2529                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2530
2531                    String msg;
2532                    if (deletedPkg == null) {
2533                        msg = "Updated system package " + deletedAppName
2534                                + " no longer exists; it's data will be wiped";
2535                        // Actual deletion of code and data will be handled by later
2536                        // reconciliation step
2537                    } else {
2538                        msg = "Updated system app + " + deletedAppName
2539                                + " no longer present; removing system privileges for "
2540                                + deletedAppName;
2541
2542                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2543
2544                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2545                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2546                    }
2547                    logCriticalInfo(Log.WARN, msg);
2548                }
2549
2550                /**
2551                 * Make sure all system apps that we expected to appear on
2552                 * the userdata partition actually showed up. If they never
2553                 * appeared, crawl back and revive the system version.
2554                 */
2555                for (int i = 0; i < mExpectingBetter.size(); i++) {
2556                    final String packageName = mExpectingBetter.keyAt(i);
2557                    if (!mPackages.containsKey(packageName)) {
2558                        final File scanFile = mExpectingBetter.valueAt(i);
2559
2560                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2561                                + " but never showed up; reverting to system");
2562
2563                        int reparseFlags = mDefParseFlags;
2564                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2565                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2566                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2567                                    | PackageParser.PARSE_IS_PRIVILEGED;
2568                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2569                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2570                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2571                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2572                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2573                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2574                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2575                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2576                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2577                        } else {
2578                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2579                            continue;
2580                        }
2581
2582                        mSettings.enableSystemPackageLPw(packageName);
2583
2584                        try {
2585                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2586                        } catch (PackageManagerException e) {
2587                            Slog.e(TAG, "Failed to parse original system package: "
2588                                    + e.getMessage());
2589                        }
2590                    }
2591                }
2592            }
2593            mExpectingBetter.clear();
2594
2595            // Resolve the storage manager.
2596            mStorageManagerPackage = getStorageManagerPackageName();
2597
2598            // Resolve protected action filters. Only the setup wizard is allowed to
2599            // have a high priority filter for these actions.
2600            mSetupWizardPackage = getSetupWizardPackageName();
2601            if (mProtectedFilters.size() > 0) {
2602                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2603                    Slog.i(TAG, "No setup wizard;"
2604                        + " All protected intents capped to priority 0");
2605                }
2606                for (ActivityIntentInfo filter : mProtectedFilters) {
2607                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2608                        if (DEBUG_FILTERS) {
2609                            Slog.i(TAG, "Found setup wizard;"
2610                                + " allow priority " + filter.getPriority() + ";"
2611                                + " package: " + filter.activity.info.packageName
2612                                + " activity: " + filter.activity.className
2613                                + " priority: " + filter.getPriority());
2614                        }
2615                        // skip setup wizard; allow it to keep the high priority filter
2616                        continue;
2617                    }
2618                    Slog.w(TAG, "Protected action; cap priority to 0;"
2619                            + " package: " + filter.activity.info.packageName
2620                            + " activity: " + filter.activity.className
2621                            + " origPrio: " + filter.getPriority());
2622                    filter.setPriority(0);
2623                }
2624            }
2625            mDeferProtectedFilters = false;
2626            mProtectedFilters.clear();
2627
2628            // Now that we know all of the shared libraries, update all clients to have
2629            // the correct library paths.
2630            updateAllSharedLibrariesLPw();
2631
2632            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2633                // NOTE: We ignore potential failures here during a system scan (like
2634                // the rest of the commands above) because there's precious little we
2635                // can do about it. A settings error is reported, though.
2636                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2637            }
2638
2639            // Now that we know all the packages we are keeping,
2640            // read and update their last usage times.
2641            mPackageUsage.read(mPackages);
2642            mCompilerStats.read();
2643
2644            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2645                    SystemClock.uptimeMillis());
2646            Slog.i(TAG, "Time to scan packages: "
2647                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2648                    + " seconds");
2649
2650            // If the platform SDK has changed since the last time we booted,
2651            // we need to re-grant app permission to catch any new ones that
2652            // appear.  This is really a hack, and means that apps can in some
2653            // cases get permissions that the user didn't initially explicitly
2654            // allow...  it would be nice to have some better way to handle
2655            // this situation.
2656            int updateFlags = UPDATE_PERMISSIONS_ALL;
2657            if (ver.sdkVersion != mSdkVersion) {
2658                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2659                        + mSdkVersion + "; regranting permissions for internal storage");
2660                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2661            }
2662            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2663            ver.sdkVersion = mSdkVersion;
2664
2665            // If this is the first boot or an update from pre-M, and it is a normal
2666            // boot, then we need to initialize the default preferred apps across
2667            // all defined users.
2668            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2669                for (UserInfo user : sUserManager.getUsers(true)) {
2670                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2671                    applyFactoryDefaultBrowserLPw(user.id);
2672                    primeDomainVerificationsLPw(user.id);
2673                }
2674            }
2675
2676            // Prepare storage for system user really early during boot,
2677            // since core system apps like SettingsProvider and SystemUI
2678            // can't wait for user to start
2679            final int storageFlags;
2680            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2681                storageFlags = StorageManager.FLAG_STORAGE_DE;
2682            } else {
2683                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2684            }
2685            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2686                    storageFlags, true /* migrateAppData */);
2687
2688            // If this is first boot after an OTA, and a normal boot, then
2689            // we need to clear code cache directories.
2690            // Note that we do *not* clear the application profiles. These remain valid
2691            // across OTAs and are used to drive profile verification (post OTA) and
2692            // profile compilation (without waiting to collect a fresh set of profiles).
2693            if (mIsUpgrade && !onlyCore) {
2694                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2695                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2696                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2697                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2698                        // No apps are running this early, so no need to freeze
2699                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2700                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2701                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2702                    }
2703                }
2704                ver.fingerprint = Build.FINGERPRINT;
2705            }
2706
2707            checkDefaultBrowser();
2708
2709            // clear only after permissions and other defaults have been updated
2710            mExistingSystemPackages.clear();
2711            mPromoteSystemApps = false;
2712
2713            // All the changes are done during package scanning.
2714            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2715
2716            // can downgrade to reader
2717            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2718            mSettings.writeLPr();
2719            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2720
2721            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2722            // early on (before the package manager declares itself as early) because other
2723            // components in the system server might ask for package contexts for these apps.
2724            //
2725            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2726            // (i.e, that the data partition is unavailable).
2727            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2728                long start = System.nanoTime();
2729                List<PackageParser.Package> coreApps = new ArrayList<>();
2730                for (PackageParser.Package pkg : mPackages.values()) {
2731                    if (pkg.coreApp) {
2732                        coreApps.add(pkg);
2733                    }
2734                }
2735
2736                int[] stats = performDexOptUpgrade(coreApps, false,
2737                        getCompilerFilterForReason(REASON_CORE_APP));
2738
2739                final int elapsedTimeSeconds =
2740                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2741                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2742
2743                if (DEBUG_DEXOPT) {
2744                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2745                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2746                }
2747
2748
2749                // TODO: Should we log these stats to tron too ?
2750                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2751                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2752                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2753                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2754            }
2755
2756            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2757                    SystemClock.uptimeMillis());
2758
2759            if (!mOnlyCore) {
2760                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2761                mRequiredInstallerPackage = getRequiredInstallerLPr();
2762                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2763                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2764                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2765                        mIntentFilterVerifierComponent);
2766                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2767                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2768                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2769                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2770            } else {
2771                mRequiredVerifierPackage = null;
2772                mRequiredInstallerPackage = null;
2773                mRequiredUninstallerPackage = null;
2774                mIntentFilterVerifierComponent = null;
2775                mIntentFilterVerifier = null;
2776                mServicesSystemSharedLibraryPackageName = null;
2777                mSharedSystemSharedLibraryPackageName = null;
2778            }
2779
2780            mInstallerService = new PackageInstallerService(context, this);
2781
2782            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2783            if (ephemeralResolverComponent != null) {
2784                if (DEBUG_EPHEMERAL) {
2785                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2786                }
2787                mEphemeralResolverConnection =
2788                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2789            } else {
2790                mEphemeralResolverConnection = null;
2791            }
2792            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2793            if (mEphemeralInstallerComponent != null) {
2794                if (DEBUG_EPHEMERAL) {
2795                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2796                }
2797                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2798            }
2799
2800            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2801
2802            // Read and update the usage of dex files.
2803            // Do this at the end of PM init so that all the packages have their
2804            // data directory reconciled.
2805            // At this point we know the code paths of the packages, so we can validate
2806            // the disk file and build the internal cache.
2807            // The usage file is expected to be small so loading and verifying it
2808            // should take a fairly small time compare to the other activities (e.g. package
2809            // scanning).
2810            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2811            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2812            for (int userId : currentUserIds) {
2813                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2814            }
2815            mDexManager.load(userPackages);
2816        } // synchronized (mPackages)
2817        } // synchronized (mInstallLock)
2818
2819        // Now after opening every single application zip, make sure they
2820        // are all flushed.  Not really needed, but keeps things nice and
2821        // tidy.
2822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2823        Runtime.getRuntime().gc();
2824        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2825
2826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2827        FallbackCategoryProvider.loadFallbacks();
2828        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2829
2830        // The initial scanning above does many calls into installd while
2831        // holding the mPackages lock, but we're mostly interested in yelling
2832        // once we have a booted system.
2833        mInstaller.setWarnIfHeld(mPackages);
2834
2835        // Expose private service for system components to use.
2836        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2837        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2838    }
2839
2840    private static File preparePackageParserCache(boolean isUpgrade) {
2841        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2842            return null;
2843        }
2844
2845        // Disable package parsing on eng builds to allow for faster incremental development.
2846        if ("eng".equals(Build.TYPE)) {
2847            return null;
2848        }
2849
2850        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2851            Slog.i(TAG, "Disabling package parser cache due to system property.");
2852            return null;
2853        }
2854
2855        // The base directory for the package parser cache lives under /data/system/.
2856        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2857                "package_cache");
2858        if (cacheBaseDir == null) {
2859            return null;
2860        }
2861
2862        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2863        // This also serves to "GC" unused entries when the package cache version changes (which
2864        // can only happen during upgrades).
2865        if (isUpgrade) {
2866            FileUtils.deleteContents(cacheBaseDir);
2867        }
2868
2869
2870        // Return the versioned package cache directory. This is something like
2871        // "/data/system/package_cache/1"
2872        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2873
2874        // The following is a workaround to aid development on non-numbered userdebug
2875        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2876        // the system partition is newer.
2877        //
2878        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2879        // that starts with "eng." to signify that this is an engineering build and not
2880        // destined for release.
2881        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2882            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2883
2884            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2885            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2886            // in general and should not be used for production changes. In this specific case,
2887            // we know that they will work.
2888            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2889            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2890                FileUtils.deleteContents(cacheBaseDir);
2891                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2892            }
2893        }
2894
2895        return cacheDir;
2896    }
2897
2898    @Override
2899    public boolean isFirstBoot() {
2900        return mFirstBoot;
2901    }
2902
2903    @Override
2904    public boolean isOnlyCoreApps() {
2905        return mOnlyCore;
2906    }
2907
2908    @Override
2909    public boolean isUpgrade() {
2910        return mIsUpgrade;
2911    }
2912
2913    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2914        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2915
2916        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2917                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2918                UserHandle.USER_SYSTEM);
2919        if (matches.size() == 1) {
2920            return matches.get(0).getComponentInfo().packageName;
2921        } else if (matches.size() == 0) {
2922            Log.e(TAG, "There should probably be a verifier, but, none were found");
2923            return null;
2924        }
2925        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2926    }
2927
2928    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2929        synchronized (mPackages) {
2930            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2931            if (libraryEntry == null) {
2932                throw new IllegalStateException("Missing required shared library:" + libraryName);
2933            }
2934            return libraryEntry.apk;
2935        }
2936    }
2937
2938    private @NonNull String getRequiredInstallerLPr() {
2939        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2940        intent.addCategory(Intent.CATEGORY_DEFAULT);
2941        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2942
2943        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2944                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2945                UserHandle.USER_SYSTEM);
2946        if (matches.size() == 1) {
2947            ResolveInfo resolveInfo = matches.get(0);
2948            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2949                throw new RuntimeException("The installer must be a privileged app");
2950            }
2951            return matches.get(0).getComponentInfo().packageName;
2952        } else {
2953            throw new RuntimeException("There must be exactly one installer; found " + matches);
2954        }
2955    }
2956
2957    private @NonNull String getRequiredUninstallerLPr() {
2958        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2959        intent.addCategory(Intent.CATEGORY_DEFAULT);
2960        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2961
2962        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2963                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2964                UserHandle.USER_SYSTEM);
2965        if (resolveInfo == null ||
2966                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2967            throw new RuntimeException("There must be exactly one uninstaller; found "
2968                    + resolveInfo);
2969        }
2970        return resolveInfo.getComponentInfo().packageName;
2971    }
2972
2973    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2974        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2975
2976        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2977                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2978                UserHandle.USER_SYSTEM);
2979        ResolveInfo best = null;
2980        final int N = matches.size();
2981        for (int i = 0; i < N; i++) {
2982            final ResolveInfo cur = matches.get(i);
2983            final String packageName = cur.getComponentInfo().packageName;
2984            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2985                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2986                continue;
2987            }
2988
2989            if (best == null || cur.priority > best.priority) {
2990                best = cur;
2991            }
2992        }
2993
2994        if (best != null) {
2995            return best.getComponentInfo().getComponentName();
2996        } else {
2997            throw new RuntimeException("There must be at least one intent filter verifier");
2998        }
2999    }
3000
3001    private @Nullable ComponentName getEphemeralResolverLPr() {
3002        final String[] packageArray =
3003                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3004        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3005            if (DEBUG_EPHEMERAL) {
3006                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3007            }
3008            return null;
3009        }
3010
3011        final int resolveFlags =
3012                MATCH_DIRECT_BOOT_AWARE
3013                | MATCH_DIRECT_BOOT_UNAWARE
3014                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3015        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3016        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3017                resolveFlags, UserHandle.USER_SYSTEM);
3018
3019        final int N = resolvers.size();
3020        if (N == 0) {
3021            if (DEBUG_EPHEMERAL) {
3022                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3023            }
3024            return null;
3025        }
3026
3027        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3028        for (int i = 0; i < N; i++) {
3029            final ResolveInfo info = resolvers.get(i);
3030
3031            if (info.serviceInfo == null) {
3032                continue;
3033            }
3034
3035            final String packageName = info.serviceInfo.packageName;
3036            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3037                if (DEBUG_EPHEMERAL) {
3038                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3039                            + " pkg: " + packageName + ", info:" + info);
3040                }
3041                continue;
3042            }
3043
3044            if (DEBUG_EPHEMERAL) {
3045                Slog.v(TAG, "Ephemeral resolver found;"
3046                        + " pkg: " + packageName + ", info:" + info);
3047            }
3048            return new ComponentName(packageName, info.serviceInfo.name);
3049        }
3050        if (DEBUG_EPHEMERAL) {
3051            Slog.v(TAG, "Ephemeral resolver NOT found");
3052        }
3053        return null;
3054    }
3055
3056    private @Nullable ComponentName getEphemeralInstallerLPr() {
3057        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3058        intent.addCategory(Intent.CATEGORY_DEFAULT);
3059        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3060
3061        final int resolveFlags =
3062                MATCH_DIRECT_BOOT_AWARE
3063                | MATCH_DIRECT_BOOT_UNAWARE
3064                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3065        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3066                resolveFlags, UserHandle.USER_SYSTEM);
3067        Iterator<ResolveInfo> iter = matches.iterator();
3068        while (iter.hasNext()) {
3069            final ResolveInfo rInfo = iter.next();
3070            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3071            if (ps != null) {
3072                final PermissionsState permissionsState = ps.getPermissionsState();
3073                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3074                    continue;
3075                }
3076            }
3077            iter.remove();
3078        }
3079        if (matches.size() == 0) {
3080            return null;
3081        } else if (matches.size() == 1) {
3082            return matches.get(0).getComponentInfo().getComponentName();
3083        } else {
3084            throw new RuntimeException(
3085                    "There must be at most one ephemeral installer; found " + matches);
3086        }
3087    }
3088
3089    private void primeDomainVerificationsLPw(int userId) {
3090        if (DEBUG_DOMAIN_VERIFICATION) {
3091            Slog.d(TAG, "Priming domain verifications in user " + userId);
3092        }
3093
3094        SystemConfig systemConfig = SystemConfig.getInstance();
3095        ArraySet<String> packages = systemConfig.getLinkedApps();
3096
3097        for (String packageName : packages) {
3098            PackageParser.Package pkg = mPackages.get(packageName);
3099            if (pkg != null) {
3100                if (!pkg.isSystemApp()) {
3101                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3102                    continue;
3103                }
3104
3105                ArraySet<String> domains = null;
3106                for (PackageParser.Activity a : pkg.activities) {
3107                    for (ActivityIntentInfo filter : a.intents) {
3108                        if (hasValidDomains(filter)) {
3109                            if (domains == null) {
3110                                domains = new ArraySet<String>();
3111                            }
3112                            domains.addAll(filter.getHostsList());
3113                        }
3114                    }
3115                }
3116
3117                if (domains != null && domains.size() > 0) {
3118                    if (DEBUG_DOMAIN_VERIFICATION) {
3119                        Slog.v(TAG, "      + " + packageName);
3120                    }
3121                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3122                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3123                    // and then 'always' in the per-user state actually used for intent resolution.
3124                    final IntentFilterVerificationInfo ivi;
3125                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3126                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3127                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3128                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3129                } else {
3130                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3131                            + "' does not handle web links");
3132                }
3133            } else {
3134                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3135            }
3136        }
3137
3138        scheduleWritePackageRestrictionsLocked(userId);
3139        scheduleWriteSettingsLocked();
3140    }
3141
3142    private void applyFactoryDefaultBrowserLPw(int userId) {
3143        // The default browser app's package name is stored in a string resource,
3144        // with a product-specific overlay used for vendor customization.
3145        String browserPkg = mContext.getResources().getString(
3146                com.android.internal.R.string.default_browser);
3147        if (!TextUtils.isEmpty(browserPkg)) {
3148            // non-empty string => required to be a known package
3149            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3150            if (ps == null) {
3151                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3152                browserPkg = null;
3153            } else {
3154                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3155            }
3156        }
3157
3158        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3159        // default.  If there's more than one, just leave everything alone.
3160        if (browserPkg == null) {
3161            calculateDefaultBrowserLPw(userId);
3162        }
3163    }
3164
3165    private void calculateDefaultBrowserLPw(int userId) {
3166        List<String> allBrowsers = resolveAllBrowserApps(userId);
3167        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3168        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3169    }
3170
3171    private List<String> resolveAllBrowserApps(int userId) {
3172        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3173        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3174                PackageManager.MATCH_ALL, userId);
3175
3176        final int count = list.size();
3177        List<String> result = new ArrayList<String>(count);
3178        for (int i=0; i<count; i++) {
3179            ResolveInfo info = list.get(i);
3180            if (info.activityInfo == null
3181                    || !info.handleAllWebDataURI
3182                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3183                    || result.contains(info.activityInfo.packageName)) {
3184                continue;
3185            }
3186            result.add(info.activityInfo.packageName);
3187        }
3188
3189        return result;
3190    }
3191
3192    private boolean packageIsBrowser(String packageName, int userId) {
3193        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3194                PackageManager.MATCH_ALL, userId);
3195        final int N = list.size();
3196        for (int i = 0; i < N; i++) {
3197            ResolveInfo info = list.get(i);
3198            if (packageName.equals(info.activityInfo.packageName)) {
3199                return true;
3200            }
3201        }
3202        return false;
3203    }
3204
3205    private void checkDefaultBrowser() {
3206        final int myUserId = UserHandle.myUserId();
3207        final String packageName = getDefaultBrowserPackageName(myUserId);
3208        if (packageName != null) {
3209            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3210            if (info == null) {
3211                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3212                synchronized (mPackages) {
3213                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3214                }
3215            }
3216        }
3217    }
3218
3219    @Override
3220    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3221            throws RemoteException {
3222        try {
3223            return super.onTransact(code, data, reply, flags);
3224        } catch (RuntimeException e) {
3225            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3226                Slog.wtf(TAG, "Package Manager Crash", e);
3227            }
3228            throw e;
3229        }
3230    }
3231
3232    static int[] appendInts(int[] cur, int[] add) {
3233        if (add == null) return cur;
3234        if (cur == null) return add;
3235        final int N = add.length;
3236        for (int i=0; i<N; i++) {
3237            cur = appendInt(cur, add[i]);
3238        }
3239        return cur;
3240    }
3241
3242    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3243        if (!sUserManager.exists(userId)) return null;
3244        if (ps == null) {
3245            return null;
3246        }
3247        final PackageParser.Package p = ps.pkg;
3248        if (p == null) {
3249            return null;
3250        }
3251
3252        final PermissionsState permissionsState = ps.getPermissionsState();
3253
3254        // Compute GIDs only if requested
3255        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3256                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3257        // Compute granted permissions only if package has requested permissions
3258        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3259                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3260        final PackageUserState state = ps.readUserState(userId);
3261
3262        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3263                && ps.isSystem()) {
3264            flags |= MATCH_ANY_USER;
3265        }
3266
3267        return PackageParser.generatePackageInfo(p, gids, flags,
3268                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3269    }
3270
3271    @Override
3272    public void checkPackageStartable(String packageName, int userId) {
3273        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3274
3275        synchronized (mPackages) {
3276            final PackageSetting ps = mSettings.mPackages.get(packageName);
3277            if (ps == null) {
3278                throw new SecurityException("Package " + packageName + " was not found!");
3279            }
3280
3281            if (!ps.getInstalled(userId)) {
3282                throw new SecurityException(
3283                        "Package " + packageName + " was not installed for user " + userId + "!");
3284            }
3285
3286            if (mSafeMode && !ps.isSystem()) {
3287                throw new SecurityException("Package " + packageName + " not a system app!");
3288            }
3289
3290            if (mFrozenPackages.contains(packageName)) {
3291                throw new SecurityException("Package " + packageName + " is currently frozen!");
3292            }
3293
3294            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3295                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3296                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3297            }
3298        }
3299    }
3300
3301    @Override
3302    public boolean isPackageAvailable(String packageName, int userId) {
3303        if (!sUserManager.exists(userId)) return false;
3304        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3305                false /* requireFullPermission */, false /* checkShell */, "is package available");
3306        synchronized (mPackages) {
3307            PackageParser.Package p = mPackages.get(packageName);
3308            if (p != null) {
3309                final PackageSetting ps = (PackageSetting) p.mExtras;
3310                if (ps != null) {
3311                    final PackageUserState state = ps.readUserState(userId);
3312                    if (state != null) {
3313                        return PackageParser.isAvailable(state);
3314                    }
3315                }
3316            }
3317        }
3318        return false;
3319    }
3320
3321    @Override
3322    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3323        if (!sUserManager.exists(userId)) return null;
3324        flags = updateFlagsForPackage(flags, userId, packageName);
3325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3326                false /* requireFullPermission */, false /* checkShell */, "get package info");
3327
3328        // reader
3329        synchronized (mPackages) {
3330            // Normalize package name to hanlde renamed packages
3331            packageName = normalizePackageNameLPr(packageName);
3332
3333            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3334            PackageParser.Package p = null;
3335            if (matchFactoryOnly) {
3336                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3337                if (ps != null) {
3338                    return generatePackageInfo(ps, flags, userId);
3339                }
3340            }
3341            if (p == null) {
3342                p = mPackages.get(packageName);
3343                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3344                    return null;
3345                }
3346            }
3347            if (DEBUG_PACKAGE_INFO)
3348                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3349            if (p != null) {
3350                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3351            }
3352            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3353                final PackageSetting ps = mSettings.mPackages.get(packageName);
3354                return generatePackageInfo(ps, flags, userId);
3355            }
3356        }
3357        return null;
3358    }
3359
3360    @Override
3361    public String[] currentToCanonicalPackageNames(String[] names) {
3362        String[] out = new String[names.length];
3363        // reader
3364        synchronized (mPackages) {
3365            for (int i=names.length-1; i>=0; i--) {
3366                PackageSetting ps = mSettings.mPackages.get(names[i]);
3367                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3368            }
3369        }
3370        return out;
3371    }
3372
3373    @Override
3374    public String[] canonicalToCurrentPackageNames(String[] names) {
3375        String[] out = new String[names.length];
3376        // reader
3377        synchronized (mPackages) {
3378            for (int i=names.length-1; i>=0; i--) {
3379                String cur = mSettings.getRenamedPackageLPr(names[i]);
3380                out[i] = cur != null ? cur : names[i];
3381            }
3382        }
3383        return out;
3384    }
3385
3386    @Override
3387    public int getPackageUid(String packageName, int flags, int userId) {
3388        if (!sUserManager.exists(userId)) return -1;
3389        flags = updateFlagsForPackage(flags, userId, packageName);
3390        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3391                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3392
3393        // reader
3394        synchronized (mPackages) {
3395            final PackageParser.Package p = mPackages.get(packageName);
3396            if (p != null && p.isMatch(flags)) {
3397                return UserHandle.getUid(userId, p.applicationInfo.uid);
3398            }
3399            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3400                final PackageSetting ps = mSettings.mPackages.get(packageName);
3401                if (ps != null && ps.isMatch(flags)) {
3402                    return UserHandle.getUid(userId, ps.appId);
3403                }
3404            }
3405        }
3406
3407        return -1;
3408    }
3409
3410    @Override
3411    public int[] getPackageGids(String packageName, int flags, int userId) {
3412        if (!sUserManager.exists(userId)) return null;
3413        flags = updateFlagsForPackage(flags, userId, packageName);
3414        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3415                false /* requireFullPermission */, false /* checkShell */,
3416                "getPackageGids");
3417
3418        // reader
3419        synchronized (mPackages) {
3420            final PackageParser.Package p = mPackages.get(packageName);
3421            if (p != null && p.isMatch(flags)) {
3422                PackageSetting ps = (PackageSetting) p.mExtras;
3423                // TODO: Shouldn't this be checking for package installed state for userId and
3424                // return null?
3425                return ps.getPermissionsState().computeGids(userId);
3426            }
3427            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3428                final PackageSetting ps = mSettings.mPackages.get(packageName);
3429                if (ps != null && ps.isMatch(flags)) {
3430                    return ps.getPermissionsState().computeGids(userId);
3431                }
3432            }
3433        }
3434
3435        return null;
3436    }
3437
3438    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3439        if (bp.perm != null) {
3440            return PackageParser.generatePermissionInfo(bp.perm, flags);
3441        }
3442        PermissionInfo pi = new PermissionInfo();
3443        pi.name = bp.name;
3444        pi.packageName = bp.sourcePackage;
3445        pi.nonLocalizedLabel = bp.name;
3446        pi.protectionLevel = bp.protectionLevel;
3447        return pi;
3448    }
3449
3450    @Override
3451    public PermissionInfo getPermissionInfo(String name, int flags) {
3452        // reader
3453        synchronized (mPackages) {
3454            final BasePermission p = mSettings.mPermissions.get(name);
3455            if (p != null) {
3456                return generatePermissionInfo(p, flags);
3457            }
3458            return null;
3459        }
3460    }
3461
3462    @Override
3463    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3464            int flags) {
3465        // reader
3466        synchronized (mPackages) {
3467            if (group != null && !mPermissionGroups.containsKey(group)) {
3468                // This is thrown as NameNotFoundException
3469                return null;
3470            }
3471
3472            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3473            for (BasePermission p : mSettings.mPermissions.values()) {
3474                if (group == null) {
3475                    if (p.perm == null || p.perm.info.group == null) {
3476                        out.add(generatePermissionInfo(p, flags));
3477                    }
3478                } else {
3479                    if (p.perm != null && group.equals(p.perm.info.group)) {
3480                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3481                    }
3482                }
3483            }
3484            return new ParceledListSlice<>(out);
3485        }
3486    }
3487
3488    @Override
3489    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3490        // reader
3491        synchronized (mPackages) {
3492            return PackageParser.generatePermissionGroupInfo(
3493                    mPermissionGroups.get(name), flags);
3494        }
3495    }
3496
3497    @Override
3498    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3499        // reader
3500        synchronized (mPackages) {
3501            final int N = mPermissionGroups.size();
3502            ArrayList<PermissionGroupInfo> out
3503                    = new ArrayList<PermissionGroupInfo>(N);
3504            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3505                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3506            }
3507            return new ParceledListSlice<>(out);
3508        }
3509    }
3510
3511    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3512            int userId) {
3513        if (!sUserManager.exists(userId)) return null;
3514        PackageSetting ps = mSettings.mPackages.get(packageName);
3515        if (ps != null) {
3516            if (ps.pkg == null) {
3517                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3518                if (pInfo != null) {
3519                    return pInfo.applicationInfo;
3520                }
3521                return null;
3522            }
3523            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3524                    ps.readUserState(userId), userId);
3525        }
3526        return null;
3527    }
3528
3529    @Override
3530    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3531        if (!sUserManager.exists(userId)) return null;
3532        flags = updateFlagsForApplication(flags, userId, packageName);
3533        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3534                false /* requireFullPermission */, false /* checkShell */, "get application info");
3535
3536        // writer
3537        synchronized (mPackages) {
3538            // Normalize package name to hanlde renamed packages
3539            packageName = normalizePackageNameLPr(packageName);
3540
3541            PackageParser.Package p = mPackages.get(packageName);
3542            if (DEBUG_PACKAGE_INFO) Log.v(
3543                    TAG, "getApplicationInfo " + packageName
3544                    + ": " + p);
3545            if (p != null) {
3546                PackageSetting ps = mSettings.mPackages.get(packageName);
3547                if (ps == null) return null;
3548                // Note: isEnabledLP() does not apply here - always return info
3549                return PackageParser.generateApplicationInfo(
3550                        p, flags, ps.readUserState(userId), userId);
3551            }
3552            if ("android".equals(packageName)||"system".equals(packageName)) {
3553                return mAndroidApplication;
3554            }
3555            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3556                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3557            }
3558        }
3559        return null;
3560    }
3561
3562    private String normalizePackageNameLPr(String packageName) {
3563        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3564        return normalizedPackageName != null ? normalizedPackageName : packageName;
3565    }
3566
3567    @Override
3568    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3569            final IPackageDataObserver observer) {
3570        mContext.enforceCallingOrSelfPermission(
3571                android.Manifest.permission.CLEAR_APP_CACHE, null);
3572        // Queue up an async operation since clearing cache may take a little while.
3573        mHandler.post(new Runnable() {
3574            public void run() {
3575                mHandler.removeCallbacks(this);
3576                boolean success = true;
3577                synchronized (mInstallLock) {
3578                    try {
3579                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3580                    } catch (InstallerException e) {
3581                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3582                        success = false;
3583                    }
3584                }
3585                if (observer != null) {
3586                    try {
3587                        observer.onRemoveCompleted(null, success);
3588                    } catch (RemoteException e) {
3589                        Slog.w(TAG, "RemoveException when invoking call back");
3590                    }
3591                }
3592            }
3593        });
3594    }
3595
3596    @Override
3597    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3598            final IntentSender pi) {
3599        mContext.enforceCallingOrSelfPermission(
3600                android.Manifest.permission.CLEAR_APP_CACHE, null);
3601        // Queue up an async operation since clearing cache may take a little while.
3602        mHandler.post(new Runnable() {
3603            public void run() {
3604                mHandler.removeCallbacks(this);
3605                boolean success = true;
3606                synchronized (mInstallLock) {
3607                    try {
3608                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3609                    } catch (InstallerException e) {
3610                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3611                        success = false;
3612                    }
3613                }
3614                if(pi != null) {
3615                    try {
3616                        // Callback via pending intent
3617                        int code = success ? 1 : 0;
3618                        pi.sendIntent(null, code, null,
3619                                null, null);
3620                    } catch (SendIntentException e1) {
3621                        Slog.i(TAG, "Failed to send pending intent");
3622                    }
3623                }
3624            }
3625        });
3626    }
3627
3628    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3629        synchronized (mInstallLock) {
3630            try {
3631                mInstaller.freeCache(volumeUuid, freeStorageSize);
3632            } catch (InstallerException e) {
3633                throw new IOException("Failed to free enough space", e);
3634            }
3635        }
3636    }
3637
3638    /**
3639     * Update given flags based on encryption status of current user.
3640     */
3641    private int updateFlags(int flags, int userId) {
3642        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3643                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3644            // Caller expressed an explicit opinion about what encryption
3645            // aware/unaware components they want to see, so fall through and
3646            // give them what they want
3647        } else {
3648            // Caller expressed no opinion, so match based on user state
3649            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3650                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3651            } else {
3652                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3653            }
3654        }
3655        return flags;
3656    }
3657
3658    private UserManagerInternal getUserManagerInternal() {
3659        if (mUserManagerInternal == null) {
3660            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3661        }
3662        return mUserManagerInternal;
3663    }
3664
3665    /**
3666     * Update given flags when being used to request {@link PackageInfo}.
3667     */
3668    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3669        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3670        boolean triaged = true;
3671        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3672                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3673            // Caller is asking for component details, so they'd better be
3674            // asking for specific encryption matching behavior, or be triaged
3675            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3676                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3677                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3678                triaged = false;
3679            }
3680        }
3681        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3682                | PackageManager.MATCH_SYSTEM_ONLY
3683                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3684            triaged = false;
3685        }
3686        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3687            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3688                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3689                    + Debug.getCallers(5));
3690        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3691                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3692            // If the caller wants all packages and has a restricted profile associated with it,
3693            // then match all users. This is to make sure that launchers that need to access work
3694            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3695            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3696            flags |= PackageManager.MATCH_ANY_USER;
3697        }
3698        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3699            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3700                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3701        }
3702        return updateFlags(flags, userId);
3703    }
3704
3705    /**
3706     * Update given flags when being used to request {@link ApplicationInfo}.
3707     */
3708    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3709        return updateFlagsForPackage(flags, userId, cookie);
3710    }
3711
3712    /**
3713     * Update given flags when being used to request {@link ComponentInfo}.
3714     */
3715    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3716        if (cookie instanceof Intent) {
3717            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3718                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3719            }
3720        }
3721
3722        boolean triaged = true;
3723        // Caller is asking for component details, so they'd better be
3724        // asking for specific encryption matching behavior, or be triaged
3725        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3726                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3727                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3728            triaged = false;
3729        }
3730        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3731            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3732                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3733        }
3734
3735        return updateFlags(flags, userId);
3736    }
3737
3738    /**
3739     * Update given flags when being used to request {@link ResolveInfo}.
3740     */
3741    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3742        // Safe mode means we shouldn't match any third-party components
3743        if (mSafeMode) {
3744            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3745        }
3746        final int callingUid = Binder.getCallingUid();
3747        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3748            // The system sees all components
3749            flags |= PackageManager.MATCH_EPHEMERAL;
3750        } else if (getEphemeralPackageName(callingUid) != null) {
3751            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3752            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3753            flags |= PackageManager.MATCH_EPHEMERAL;
3754        } else {
3755            // Otherwise, prevent leaking ephemeral components
3756            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3757            flags &= ~PackageManager.MATCH_EPHEMERAL;
3758        }
3759        return updateFlagsForComponent(flags, userId, cookie);
3760    }
3761
3762    @Override
3763    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3764        if (!sUserManager.exists(userId)) return null;
3765        flags = updateFlagsForComponent(flags, userId, component);
3766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3767                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3768        synchronized (mPackages) {
3769            PackageParser.Activity a = mActivities.mActivities.get(component);
3770
3771            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3772            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3773                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3774                if (ps == null) return null;
3775                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3776                        userId);
3777            }
3778            if (mResolveComponentName.equals(component)) {
3779                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3780                        new PackageUserState(), userId);
3781            }
3782        }
3783        return null;
3784    }
3785
3786    @Override
3787    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3788            String resolvedType) {
3789        synchronized (mPackages) {
3790            if (component.equals(mResolveComponentName)) {
3791                // The resolver supports EVERYTHING!
3792                return true;
3793            }
3794            PackageParser.Activity a = mActivities.mActivities.get(component);
3795            if (a == null) {
3796                return false;
3797            }
3798            for (int i=0; i<a.intents.size(); i++) {
3799                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3800                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3801                    return true;
3802                }
3803            }
3804            return false;
3805        }
3806    }
3807
3808    @Override
3809    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3810        if (!sUserManager.exists(userId)) return null;
3811        flags = updateFlagsForComponent(flags, userId, component);
3812        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3813                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3814        synchronized (mPackages) {
3815            PackageParser.Activity a = mReceivers.mActivities.get(component);
3816            if (DEBUG_PACKAGE_INFO) Log.v(
3817                TAG, "getReceiverInfo " + component + ": " + a);
3818            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3819                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3820                if (ps == null) return null;
3821                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3822                        userId);
3823            }
3824        }
3825        return null;
3826    }
3827
3828    @Override
3829    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3830        if (!sUserManager.exists(userId)) return null;
3831        flags = updateFlagsForComponent(flags, userId, component);
3832        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3833                false /* requireFullPermission */, false /* checkShell */, "get service info");
3834        synchronized (mPackages) {
3835            PackageParser.Service s = mServices.mServices.get(component);
3836            if (DEBUG_PACKAGE_INFO) Log.v(
3837                TAG, "getServiceInfo " + component + ": " + s);
3838            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3839                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3840                if (ps == null) return null;
3841                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3842                        userId);
3843            }
3844        }
3845        return null;
3846    }
3847
3848    @Override
3849    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3850        if (!sUserManager.exists(userId)) return null;
3851        flags = updateFlagsForComponent(flags, userId, component);
3852        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3853                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3854        synchronized (mPackages) {
3855            PackageParser.Provider p = mProviders.mProviders.get(component);
3856            if (DEBUG_PACKAGE_INFO) Log.v(
3857                TAG, "getProviderInfo " + component + ": " + p);
3858            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3859                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3860                if (ps == null) return null;
3861                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3862                        userId);
3863            }
3864        }
3865        return null;
3866    }
3867
3868    @Override
3869    public String[] getSystemSharedLibraryNames() {
3870        Set<String> libSet;
3871        synchronized (mPackages) {
3872            libSet = mSharedLibraries.keySet();
3873            int size = libSet.size();
3874            if (size > 0) {
3875                String[] libs = new String[size];
3876                libSet.toArray(libs);
3877                return libs;
3878            }
3879        }
3880        return null;
3881    }
3882
3883    @Override
3884    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3885        synchronized (mPackages) {
3886            return mServicesSystemSharedLibraryPackageName;
3887        }
3888    }
3889
3890    @Override
3891    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3892        synchronized (mPackages) {
3893            return mSharedSystemSharedLibraryPackageName;
3894        }
3895    }
3896
3897    @Override
3898    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3899        synchronized (mPackages) {
3900            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3901
3902            final FeatureInfo fi = new FeatureInfo();
3903            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3904                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3905            res.add(fi);
3906
3907            return new ParceledListSlice<>(res);
3908        }
3909    }
3910
3911    @Override
3912    public boolean hasSystemFeature(String name, int version) {
3913        synchronized (mPackages) {
3914            final FeatureInfo feat = mAvailableFeatures.get(name);
3915            if (feat == null) {
3916                return false;
3917            } else {
3918                return feat.version >= version;
3919            }
3920        }
3921    }
3922
3923    @Override
3924    public int checkPermission(String permName, String pkgName, int userId) {
3925        if (!sUserManager.exists(userId)) {
3926            return PackageManager.PERMISSION_DENIED;
3927        }
3928
3929        synchronized (mPackages) {
3930            final PackageParser.Package p = mPackages.get(pkgName);
3931            if (p != null && p.mExtras != null) {
3932                final PackageSetting ps = (PackageSetting) p.mExtras;
3933                final PermissionsState permissionsState = ps.getPermissionsState();
3934                if (permissionsState.hasPermission(permName, userId)) {
3935                    return PackageManager.PERMISSION_GRANTED;
3936                }
3937                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3938                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3939                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3940                    return PackageManager.PERMISSION_GRANTED;
3941                }
3942            }
3943        }
3944
3945        return PackageManager.PERMISSION_DENIED;
3946    }
3947
3948    @Override
3949    public int checkUidPermission(String permName, int uid) {
3950        final int userId = UserHandle.getUserId(uid);
3951
3952        if (!sUserManager.exists(userId)) {
3953            return PackageManager.PERMISSION_DENIED;
3954        }
3955
3956        synchronized (mPackages) {
3957            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3958            if (obj != null) {
3959                final SettingBase ps = (SettingBase) obj;
3960                final PermissionsState permissionsState = ps.getPermissionsState();
3961                if (permissionsState.hasPermission(permName, userId)) {
3962                    return PackageManager.PERMISSION_GRANTED;
3963                }
3964                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3965                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3966                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3967                    return PackageManager.PERMISSION_GRANTED;
3968                }
3969            } else {
3970                ArraySet<String> perms = mSystemPermissions.get(uid);
3971                if (perms != null) {
3972                    if (perms.contains(permName)) {
3973                        return PackageManager.PERMISSION_GRANTED;
3974                    }
3975                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3976                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3977                        return PackageManager.PERMISSION_GRANTED;
3978                    }
3979                }
3980            }
3981        }
3982
3983        return PackageManager.PERMISSION_DENIED;
3984    }
3985
3986    @Override
3987    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3988        if (UserHandle.getCallingUserId() != userId) {
3989            mContext.enforceCallingPermission(
3990                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3991                    "isPermissionRevokedByPolicy for user " + userId);
3992        }
3993
3994        if (checkPermission(permission, packageName, userId)
3995                == PackageManager.PERMISSION_GRANTED) {
3996            return false;
3997        }
3998
3999        final long identity = Binder.clearCallingIdentity();
4000        try {
4001            final int flags = getPermissionFlags(permission, packageName, userId);
4002            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4003        } finally {
4004            Binder.restoreCallingIdentity(identity);
4005        }
4006    }
4007
4008    @Override
4009    public String getPermissionControllerPackageName() {
4010        synchronized (mPackages) {
4011            return mRequiredInstallerPackage;
4012        }
4013    }
4014
4015    /**
4016     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4017     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4018     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4019     * @param message the message to log on security exception
4020     */
4021    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4022            boolean checkShell, String message) {
4023        if (userId < 0) {
4024            throw new IllegalArgumentException("Invalid userId " + userId);
4025        }
4026        if (checkShell) {
4027            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4028        }
4029        if (userId == UserHandle.getUserId(callingUid)) return;
4030        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4031            if (requireFullPermission) {
4032                mContext.enforceCallingOrSelfPermission(
4033                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4034            } else {
4035                try {
4036                    mContext.enforceCallingOrSelfPermission(
4037                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4038                } catch (SecurityException se) {
4039                    mContext.enforceCallingOrSelfPermission(
4040                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4041                }
4042            }
4043        }
4044    }
4045
4046    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4047        if (callingUid == Process.SHELL_UID) {
4048            if (userHandle >= 0
4049                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4050                throw new SecurityException("Shell does not have permission to access user "
4051                        + userHandle);
4052            } else if (userHandle < 0) {
4053                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4054                        + Debug.getCallers(3));
4055            }
4056        }
4057    }
4058
4059    private BasePermission findPermissionTreeLP(String permName) {
4060        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4061            if (permName.startsWith(bp.name) &&
4062                    permName.length() > bp.name.length() &&
4063                    permName.charAt(bp.name.length()) == '.') {
4064                return bp;
4065            }
4066        }
4067        return null;
4068    }
4069
4070    private BasePermission checkPermissionTreeLP(String permName) {
4071        if (permName != null) {
4072            BasePermission bp = findPermissionTreeLP(permName);
4073            if (bp != null) {
4074                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4075                    return bp;
4076                }
4077                throw new SecurityException("Calling uid "
4078                        + Binder.getCallingUid()
4079                        + " is not allowed to add to permission tree "
4080                        + bp.name + " owned by uid " + bp.uid);
4081            }
4082        }
4083        throw new SecurityException("No permission tree found for " + permName);
4084    }
4085
4086    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4087        if (s1 == null) {
4088            return s2 == null;
4089        }
4090        if (s2 == null) {
4091            return false;
4092        }
4093        if (s1.getClass() != s2.getClass()) {
4094            return false;
4095        }
4096        return s1.equals(s2);
4097    }
4098
4099    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4100        if (pi1.icon != pi2.icon) return false;
4101        if (pi1.logo != pi2.logo) return false;
4102        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4103        if (!compareStrings(pi1.name, pi2.name)) return false;
4104        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4105        // We'll take care of setting this one.
4106        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4107        // These are not currently stored in settings.
4108        //if (!compareStrings(pi1.group, pi2.group)) return false;
4109        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4110        //if (pi1.labelRes != pi2.labelRes) return false;
4111        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4112        return true;
4113    }
4114
4115    int permissionInfoFootprint(PermissionInfo info) {
4116        int size = info.name.length();
4117        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4118        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4119        return size;
4120    }
4121
4122    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4123        int size = 0;
4124        for (BasePermission perm : mSettings.mPermissions.values()) {
4125            if (perm.uid == tree.uid) {
4126                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4127            }
4128        }
4129        return size;
4130    }
4131
4132    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4133        // We calculate the max size of permissions defined by this uid and throw
4134        // if that plus the size of 'info' would exceed our stated maximum.
4135        if (tree.uid != Process.SYSTEM_UID) {
4136            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4137            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4138                throw new SecurityException("Permission tree size cap exceeded");
4139            }
4140        }
4141    }
4142
4143    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4144        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4145            throw new SecurityException("Label must be specified in permission");
4146        }
4147        BasePermission tree = checkPermissionTreeLP(info.name);
4148        BasePermission bp = mSettings.mPermissions.get(info.name);
4149        boolean added = bp == null;
4150        boolean changed = true;
4151        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4152        if (added) {
4153            enforcePermissionCapLocked(info, tree);
4154            bp = new BasePermission(info.name, tree.sourcePackage,
4155                    BasePermission.TYPE_DYNAMIC);
4156        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4157            throw new SecurityException(
4158                    "Not allowed to modify non-dynamic permission "
4159                    + info.name);
4160        } else {
4161            if (bp.protectionLevel == fixedLevel
4162                    && bp.perm.owner.equals(tree.perm.owner)
4163                    && bp.uid == tree.uid
4164                    && comparePermissionInfos(bp.perm.info, info)) {
4165                changed = false;
4166            }
4167        }
4168        bp.protectionLevel = fixedLevel;
4169        info = new PermissionInfo(info);
4170        info.protectionLevel = fixedLevel;
4171        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4172        bp.perm.info.packageName = tree.perm.info.packageName;
4173        bp.uid = tree.uid;
4174        if (added) {
4175            mSettings.mPermissions.put(info.name, bp);
4176        }
4177        if (changed) {
4178            if (!async) {
4179                mSettings.writeLPr();
4180            } else {
4181                scheduleWriteSettingsLocked();
4182            }
4183        }
4184        return added;
4185    }
4186
4187    @Override
4188    public boolean addPermission(PermissionInfo info) {
4189        synchronized (mPackages) {
4190            return addPermissionLocked(info, false);
4191        }
4192    }
4193
4194    @Override
4195    public boolean addPermissionAsync(PermissionInfo info) {
4196        synchronized (mPackages) {
4197            return addPermissionLocked(info, true);
4198        }
4199    }
4200
4201    @Override
4202    public void removePermission(String name) {
4203        synchronized (mPackages) {
4204            checkPermissionTreeLP(name);
4205            BasePermission bp = mSettings.mPermissions.get(name);
4206            if (bp != null) {
4207                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4208                    throw new SecurityException(
4209                            "Not allowed to modify non-dynamic permission "
4210                            + name);
4211                }
4212                mSettings.mPermissions.remove(name);
4213                mSettings.writeLPr();
4214            }
4215        }
4216    }
4217
4218    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4219            BasePermission bp) {
4220        int index = pkg.requestedPermissions.indexOf(bp.name);
4221        if (index == -1) {
4222            throw new SecurityException("Package " + pkg.packageName
4223                    + " has not requested permission " + bp.name);
4224        }
4225        if (!bp.isRuntime() && !bp.isDevelopment()) {
4226            throw new SecurityException("Permission " + bp.name
4227                    + " is not a changeable permission type");
4228        }
4229    }
4230
4231    @Override
4232    public void grantRuntimePermission(String packageName, String name, final int userId) {
4233        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4234    }
4235
4236    private void grantRuntimePermission(String packageName, String name, final int userId,
4237            boolean overridePolicy) {
4238        if (!sUserManager.exists(userId)) {
4239            Log.e(TAG, "No such user:" + userId);
4240            return;
4241        }
4242
4243        mContext.enforceCallingOrSelfPermission(
4244                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4245                "grantRuntimePermission");
4246
4247        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4248                true /* requireFullPermission */, true /* checkShell */,
4249                "grantRuntimePermission");
4250
4251        final int uid;
4252        final SettingBase sb;
4253
4254        synchronized (mPackages) {
4255            final PackageParser.Package pkg = mPackages.get(packageName);
4256            if (pkg == null) {
4257                throw new IllegalArgumentException("Unknown package: " + packageName);
4258            }
4259
4260            final BasePermission bp = mSettings.mPermissions.get(name);
4261            if (bp == null) {
4262                throw new IllegalArgumentException("Unknown permission: " + name);
4263            }
4264
4265            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4266
4267            // If a permission review is required for legacy apps we represent
4268            // their permissions as always granted runtime ones since we need
4269            // to keep the review required permission flag per user while an
4270            // install permission's state is shared across all users.
4271            if (mPermissionReviewRequired
4272                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4273                    && bp.isRuntime()) {
4274                return;
4275            }
4276
4277            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4278            sb = (SettingBase) pkg.mExtras;
4279            if (sb == null) {
4280                throw new IllegalArgumentException("Unknown package: " + packageName);
4281            }
4282
4283            final PermissionsState permissionsState = sb.getPermissionsState();
4284
4285            final int flags = permissionsState.getPermissionFlags(name, userId);
4286            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4287                throw new SecurityException("Cannot grant system fixed permission "
4288                        + name + " for package " + packageName);
4289            }
4290            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4291                throw new SecurityException("Cannot grant policy fixed permission "
4292                        + name + " for package " + packageName);
4293            }
4294
4295            if (bp.isDevelopment()) {
4296                // Development permissions must be handled specially, since they are not
4297                // normal runtime permissions.  For now they apply to all users.
4298                if (permissionsState.grantInstallPermission(bp) !=
4299                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4300                    scheduleWriteSettingsLocked();
4301                }
4302                return;
4303            }
4304
4305            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4306                throw new SecurityException("Cannot grant non-ephemeral permission"
4307                        + name + " for package " + packageName);
4308            }
4309
4310            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4311                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4312                return;
4313            }
4314
4315            final int result = permissionsState.grantRuntimePermission(bp, userId);
4316            switch (result) {
4317                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4318                    return;
4319                }
4320
4321                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4322                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4323                    mHandler.post(new Runnable() {
4324                        @Override
4325                        public void run() {
4326                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4327                        }
4328                    });
4329                }
4330                break;
4331            }
4332
4333            if (bp.isRuntime()) {
4334                logPermissionGranted(mContext, name, packageName);
4335            }
4336
4337            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4338
4339            // Not critical if that is lost - app has to request again.
4340            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4341        }
4342
4343        // Only need to do this if user is initialized. Otherwise it's a new user
4344        // and there are no processes running as the user yet and there's no need
4345        // to make an expensive call to remount processes for the changed permissions.
4346        if (READ_EXTERNAL_STORAGE.equals(name)
4347                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4348            final long token = Binder.clearCallingIdentity();
4349            try {
4350                if (sUserManager.isInitialized(userId)) {
4351                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4352                            StorageManagerInternal.class);
4353                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4354                }
4355            } finally {
4356                Binder.restoreCallingIdentity(token);
4357            }
4358        }
4359    }
4360
4361    @Override
4362    public void revokeRuntimePermission(String packageName, String name, int userId) {
4363        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4364    }
4365
4366    private void revokeRuntimePermission(String packageName, String name, int userId,
4367            boolean overridePolicy) {
4368        if (!sUserManager.exists(userId)) {
4369            Log.e(TAG, "No such user:" + userId);
4370            return;
4371        }
4372
4373        mContext.enforceCallingOrSelfPermission(
4374                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4375                "revokeRuntimePermission");
4376
4377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4378                true /* requireFullPermission */, true /* checkShell */,
4379                "revokeRuntimePermission");
4380
4381        final int appId;
4382
4383        synchronized (mPackages) {
4384            final PackageParser.Package pkg = mPackages.get(packageName);
4385            if (pkg == null) {
4386                throw new IllegalArgumentException("Unknown package: " + packageName);
4387            }
4388
4389            final BasePermission bp = mSettings.mPermissions.get(name);
4390            if (bp == null) {
4391                throw new IllegalArgumentException("Unknown permission: " + name);
4392            }
4393
4394            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4395
4396            // If a permission review is required for legacy apps we represent
4397            // their permissions as always granted runtime ones since we need
4398            // to keep the review required permission flag per user while an
4399            // install permission's state is shared across all users.
4400            if (mPermissionReviewRequired
4401                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4402                    && bp.isRuntime()) {
4403                return;
4404            }
4405
4406            SettingBase sb = (SettingBase) pkg.mExtras;
4407            if (sb == null) {
4408                throw new IllegalArgumentException("Unknown package: " + packageName);
4409            }
4410
4411            final PermissionsState permissionsState = sb.getPermissionsState();
4412
4413            final int flags = permissionsState.getPermissionFlags(name, userId);
4414            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4415                throw new SecurityException("Cannot revoke system fixed permission "
4416                        + name + " for package " + packageName);
4417            }
4418            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4419                throw new SecurityException("Cannot revoke policy fixed permission "
4420                        + name + " for package " + packageName);
4421            }
4422
4423            if (bp.isDevelopment()) {
4424                // Development permissions must be handled specially, since they are not
4425                // normal runtime permissions.  For now they apply to all users.
4426                if (permissionsState.revokeInstallPermission(bp) !=
4427                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4428                    scheduleWriteSettingsLocked();
4429                }
4430                return;
4431            }
4432
4433            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4434                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4435                return;
4436            }
4437
4438            if (bp.isRuntime()) {
4439                logPermissionRevoked(mContext, name, packageName);
4440            }
4441
4442            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4443
4444            // Critical, after this call app should never have the permission.
4445            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4446
4447            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4448        }
4449
4450        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4451    }
4452
4453    /**
4454     * Get the first event id for the permission.
4455     *
4456     * <p>There are four events for each permission: <ul>
4457     *     <li>Request permission: first id + 0</li>
4458     *     <li>Grant permission: first id + 1</li>
4459     *     <li>Request for permission denied: first id + 2</li>
4460     *     <li>Revoke permission: first id + 3</li>
4461     * </ul></p>
4462     *
4463     * @param name name of the permission
4464     *
4465     * @return The first event id for the permission
4466     */
4467    private static int getBaseEventId(@NonNull String name) {
4468        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4469
4470        if (eventIdIndex == -1) {
4471            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4472                    || "user".equals(Build.TYPE)) {
4473                Log.i(TAG, "Unknown permission " + name);
4474
4475                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4476            } else {
4477                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4478                //
4479                // Also update
4480                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4481                // - metrics_constants.proto
4482                throw new IllegalStateException("Unknown permission " + name);
4483            }
4484        }
4485
4486        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4487    }
4488
4489    /**
4490     * Log that a permission was revoked.
4491     *
4492     * @param context Context of the caller
4493     * @param name name of the permission
4494     * @param packageName package permission if for
4495     */
4496    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4497            @NonNull String packageName) {
4498        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4499    }
4500
4501    /**
4502     * Log that a permission request was granted.
4503     *
4504     * @param context Context of the caller
4505     * @param name name of the permission
4506     * @param packageName package permission if for
4507     */
4508    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4509            @NonNull String packageName) {
4510        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4511    }
4512
4513    @Override
4514    public void resetRuntimePermissions() {
4515        mContext.enforceCallingOrSelfPermission(
4516                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4517                "revokeRuntimePermission");
4518
4519        int callingUid = Binder.getCallingUid();
4520        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4521            mContext.enforceCallingOrSelfPermission(
4522                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4523                    "resetRuntimePermissions");
4524        }
4525
4526        synchronized (mPackages) {
4527            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4528            for (int userId : UserManagerService.getInstance().getUserIds()) {
4529                final int packageCount = mPackages.size();
4530                for (int i = 0; i < packageCount; i++) {
4531                    PackageParser.Package pkg = mPackages.valueAt(i);
4532                    if (!(pkg.mExtras instanceof PackageSetting)) {
4533                        continue;
4534                    }
4535                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4536                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4537                }
4538            }
4539        }
4540    }
4541
4542    @Override
4543    public int getPermissionFlags(String name, String packageName, int userId) {
4544        if (!sUserManager.exists(userId)) {
4545            return 0;
4546        }
4547
4548        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4549
4550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4551                true /* requireFullPermission */, false /* checkShell */,
4552                "getPermissionFlags");
4553
4554        synchronized (mPackages) {
4555            final PackageParser.Package pkg = mPackages.get(packageName);
4556            if (pkg == null) {
4557                return 0;
4558            }
4559
4560            final BasePermission bp = mSettings.mPermissions.get(name);
4561            if (bp == null) {
4562                return 0;
4563            }
4564
4565            SettingBase sb = (SettingBase) pkg.mExtras;
4566            if (sb == null) {
4567                return 0;
4568            }
4569
4570            PermissionsState permissionsState = sb.getPermissionsState();
4571            return permissionsState.getPermissionFlags(name, userId);
4572        }
4573    }
4574
4575    @Override
4576    public void updatePermissionFlags(String name, String packageName, int flagMask,
4577            int flagValues, int userId) {
4578        if (!sUserManager.exists(userId)) {
4579            return;
4580        }
4581
4582        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4583
4584        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4585                true /* requireFullPermission */, true /* checkShell */,
4586                "updatePermissionFlags");
4587
4588        // Only the system can change these flags and nothing else.
4589        if (getCallingUid() != Process.SYSTEM_UID) {
4590            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4591            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4592            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4593            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4594            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4595        }
4596
4597        synchronized (mPackages) {
4598            final PackageParser.Package pkg = mPackages.get(packageName);
4599            if (pkg == null) {
4600                throw new IllegalArgumentException("Unknown package: " + packageName);
4601            }
4602
4603            final BasePermission bp = mSettings.mPermissions.get(name);
4604            if (bp == null) {
4605                throw new IllegalArgumentException("Unknown permission: " + name);
4606            }
4607
4608            SettingBase sb = (SettingBase) pkg.mExtras;
4609            if (sb == null) {
4610                throw new IllegalArgumentException("Unknown package: " + packageName);
4611            }
4612
4613            PermissionsState permissionsState = sb.getPermissionsState();
4614
4615            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4616
4617            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4618                // Install and runtime permissions are stored in different places,
4619                // so figure out what permission changed and persist the change.
4620                if (permissionsState.getInstallPermissionState(name) != null) {
4621                    scheduleWriteSettingsLocked();
4622                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4623                        || hadState) {
4624                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4625                }
4626            }
4627        }
4628    }
4629
4630    /**
4631     * Update the permission flags for all packages and runtime permissions of a user in order
4632     * to allow device or profile owner to remove POLICY_FIXED.
4633     */
4634    @Override
4635    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4636        if (!sUserManager.exists(userId)) {
4637            return;
4638        }
4639
4640        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4641
4642        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4643                true /* requireFullPermission */, true /* checkShell */,
4644                "updatePermissionFlagsForAllApps");
4645
4646        // Only the system can change system fixed flags.
4647        if (getCallingUid() != Process.SYSTEM_UID) {
4648            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4649            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4650        }
4651
4652        synchronized (mPackages) {
4653            boolean changed = false;
4654            final int packageCount = mPackages.size();
4655            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4656                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4657                SettingBase sb = (SettingBase) pkg.mExtras;
4658                if (sb == null) {
4659                    continue;
4660                }
4661                PermissionsState permissionsState = sb.getPermissionsState();
4662                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4663                        userId, flagMask, flagValues);
4664            }
4665            if (changed) {
4666                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4667            }
4668        }
4669    }
4670
4671    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4672        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4673                != PackageManager.PERMISSION_GRANTED
4674            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4675                != PackageManager.PERMISSION_GRANTED) {
4676            throw new SecurityException(message + " requires "
4677                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4678                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4679        }
4680    }
4681
4682    @Override
4683    public boolean shouldShowRequestPermissionRationale(String permissionName,
4684            String packageName, int userId) {
4685        if (UserHandle.getCallingUserId() != userId) {
4686            mContext.enforceCallingPermission(
4687                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4688                    "canShowRequestPermissionRationale for user " + userId);
4689        }
4690
4691        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4692        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4693            return false;
4694        }
4695
4696        if (checkPermission(permissionName, packageName, userId)
4697                == PackageManager.PERMISSION_GRANTED) {
4698            return false;
4699        }
4700
4701        final int flags;
4702
4703        final long identity = Binder.clearCallingIdentity();
4704        try {
4705            flags = getPermissionFlags(permissionName,
4706                    packageName, userId);
4707        } finally {
4708            Binder.restoreCallingIdentity(identity);
4709        }
4710
4711        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4712                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4713                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4714
4715        if ((flags & fixedFlags) != 0) {
4716            return false;
4717        }
4718
4719        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4720    }
4721
4722    @Override
4723    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4724        mContext.enforceCallingOrSelfPermission(
4725                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4726                "addOnPermissionsChangeListener");
4727
4728        synchronized (mPackages) {
4729            mOnPermissionChangeListeners.addListenerLocked(listener);
4730        }
4731    }
4732
4733    @Override
4734    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4735        synchronized (mPackages) {
4736            mOnPermissionChangeListeners.removeListenerLocked(listener);
4737        }
4738    }
4739
4740    @Override
4741    public boolean isProtectedBroadcast(String actionName) {
4742        synchronized (mPackages) {
4743            if (mProtectedBroadcasts.contains(actionName)) {
4744                return true;
4745            } else if (actionName != null) {
4746                // TODO: remove these terrible hacks
4747                if (actionName.startsWith("android.net.netmon.lingerExpired")
4748                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4749                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4750                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4751                    return true;
4752                }
4753            }
4754        }
4755        return false;
4756    }
4757
4758    @Override
4759    public int checkSignatures(String pkg1, String pkg2) {
4760        synchronized (mPackages) {
4761            final PackageParser.Package p1 = mPackages.get(pkg1);
4762            final PackageParser.Package p2 = mPackages.get(pkg2);
4763            if (p1 == null || p1.mExtras == null
4764                    || p2 == null || p2.mExtras == null) {
4765                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4766            }
4767            return compareSignatures(p1.mSignatures, p2.mSignatures);
4768        }
4769    }
4770
4771    @Override
4772    public int checkUidSignatures(int uid1, int uid2) {
4773        // Map to base uids.
4774        uid1 = UserHandle.getAppId(uid1);
4775        uid2 = UserHandle.getAppId(uid2);
4776        // reader
4777        synchronized (mPackages) {
4778            Signature[] s1;
4779            Signature[] s2;
4780            Object obj = mSettings.getUserIdLPr(uid1);
4781            if (obj != null) {
4782                if (obj instanceof SharedUserSetting) {
4783                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4784                } else if (obj instanceof PackageSetting) {
4785                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4786                } else {
4787                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4788                }
4789            } else {
4790                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4791            }
4792            obj = mSettings.getUserIdLPr(uid2);
4793            if (obj != null) {
4794                if (obj instanceof SharedUserSetting) {
4795                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4796                } else if (obj instanceof PackageSetting) {
4797                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4798                } else {
4799                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4800                }
4801            } else {
4802                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4803            }
4804            return compareSignatures(s1, s2);
4805        }
4806    }
4807
4808    /**
4809     * This method should typically only be used when granting or revoking
4810     * permissions, since the app may immediately restart after this call.
4811     * <p>
4812     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4813     * guard your work against the app being relaunched.
4814     */
4815    private void killUid(int appId, int userId, String reason) {
4816        final long identity = Binder.clearCallingIdentity();
4817        try {
4818            IActivityManager am = ActivityManager.getService();
4819            if (am != null) {
4820                try {
4821                    am.killUid(appId, userId, reason);
4822                } catch (RemoteException e) {
4823                    /* ignore - same process */
4824                }
4825            }
4826        } finally {
4827            Binder.restoreCallingIdentity(identity);
4828        }
4829    }
4830
4831    /**
4832     * Compares two sets of signatures. Returns:
4833     * <br />
4834     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4835     * <br />
4836     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4837     * <br />
4838     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4839     * <br />
4840     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4841     * <br />
4842     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4843     */
4844    static int compareSignatures(Signature[] s1, Signature[] s2) {
4845        if (s1 == null) {
4846            return s2 == null
4847                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4848                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4849        }
4850
4851        if (s2 == null) {
4852            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4853        }
4854
4855        if (s1.length != s2.length) {
4856            return PackageManager.SIGNATURE_NO_MATCH;
4857        }
4858
4859        // Since both signature sets are of size 1, we can compare without HashSets.
4860        if (s1.length == 1) {
4861            return s1[0].equals(s2[0]) ?
4862                    PackageManager.SIGNATURE_MATCH :
4863                    PackageManager.SIGNATURE_NO_MATCH;
4864        }
4865
4866        ArraySet<Signature> set1 = new ArraySet<Signature>();
4867        for (Signature sig : s1) {
4868            set1.add(sig);
4869        }
4870        ArraySet<Signature> set2 = new ArraySet<Signature>();
4871        for (Signature sig : s2) {
4872            set2.add(sig);
4873        }
4874        // Make sure s2 contains all signatures in s1.
4875        if (set1.equals(set2)) {
4876            return PackageManager.SIGNATURE_MATCH;
4877        }
4878        return PackageManager.SIGNATURE_NO_MATCH;
4879    }
4880
4881    /**
4882     * If the database version for this type of package (internal storage or
4883     * external storage) is less than the version where package signatures
4884     * were updated, return true.
4885     */
4886    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4887        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4888        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4889    }
4890
4891    /**
4892     * Used for backward compatibility to make sure any packages with
4893     * certificate chains get upgraded to the new style. {@code existingSigs}
4894     * will be in the old format (since they were stored on disk from before the
4895     * system upgrade) and {@code scannedSigs} will be in the newer format.
4896     */
4897    private int compareSignaturesCompat(PackageSignatures existingSigs,
4898            PackageParser.Package scannedPkg) {
4899        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4900            return PackageManager.SIGNATURE_NO_MATCH;
4901        }
4902
4903        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4904        for (Signature sig : existingSigs.mSignatures) {
4905            existingSet.add(sig);
4906        }
4907        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4908        for (Signature sig : scannedPkg.mSignatures) {
4909            try {
4910                Signature[] chainSignatures = sig.getChainSignatures();
4911                for (Signature chainSig : chainSignatures) {
4912                    scannedCompatSet.add(chainSig);
4913                }
4914            } catch (CertificateEncodingException e) {
4915                scannedCompatSet.add(sig);
4916            }
4917        }
4918        /*
4919         * Make sure the expanded scanned set contains all signatures in the
4920         * existing one.
4921         */
4922        if (scannedCompatSet.equals(existingSet)) {
4923            // Migrate the old signatures to the new scheme.
4924            existingSigs.assignSignatures(scannedPkg.mSignatures);
4925            // The new KeySets will be re-added later in the scanning process.
4926            synchronized (mPackages) {
4927                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4928            }
4929            return PackageManager.SIGNATURE_MATCH;
4930        }
4931        return PackageManager.SIGNATURE_NO_MATCH;
4932    }
4933
4934    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4935        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4936        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4937    }
4938
4939    private int compareSignaturesRecover(PackageSignatures existingSigs,
4940            PackageParser.Package scannedPkg) {
4941        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4942            return PackageManager.SIGNATURE_NO_MATCH;
4943        }
4944
4945        String msg = null;
4946        try {
4947            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4948                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4949                        + scannedPkg.packageName);
4950                return PackageManager.SIGNATURE_MATCH;
4951            }
4952        } catch (CertificateException e) {
4953            msg = e.getMessage();
4954        }
4955
4956        logCriticalInfo(Log.INFO,
4957                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4958        return PackageManager.SIGNATURE_NO_MATCH;
4959    }
4960
4961    @Override
4962    public List<String> getAllPackages() {
4963        synchronized (mPackages) {
4964            return new ArrayList<String>(mPackages.keySet());
4965        }
4966    }
4967
4968    @Override
4969    public String[] getPackagesForUid(int uid) {
4970        final int userId = UserHandle.getUserId(uid);
4971        uid = UserHandle.getAppId(uid);
4972        // reader
4973        synchronized (mPackages) {
4974            Object obj = mSettings.getUserIdLPr(uid);
4975            if (obj instanceof SharedUserSetting) {
4976                final SharedUserSetting sus = (SharedUserSetting) obj;
4977                final int N = sus.packages.size();
4978                String[] res = new String[N];
4979                final Iterator<PackageSetting> it = sus.packages.iterator();
4980                int i = 0;
4981                while (it.hasNext()) {
4982                    PackageSetting ps = it.next();
4983                    if (ps.getInstalled(userId)) {
4984                        res[i++] = ps.name;
4985                    } else {
4986                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4987                    }
4988                }
4989                return res;
4990            } else if (obj instanceof PackageSetting) {
4991                final PackageSetting ps = (PackageSetting) obj;
4992                return new String[] { ps.name };
4993            }
4994        }
4995        return null;
4996    }
4997
4998    @Override
4999    public String getNameForUid(int uid) {
5000        // reader
5001        synchronized (mPackages) {
5002            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5003            if (obj instanceof SharedUserSetting) {
5004                final SharedUserSetting sus = (SharedUserSetting) obj;
5005                return sus.name + ":" + sus.userId;
5006            } else if (obj instanceof PackageSetting) {
5007                final PackageSetting ps = (PackageSetting) obj;
5008                return ps.name;
5009            }
5010        }
5011        return null;
5012    }
5013
5014    @Override
5015    public int getUidForSharedUser(String sharedUserName) {
5016        if(sharedUserName == null) {
5017            return -1;
5018        }
5019        // reader
5020        synchronized (mPackages) {
5021            SharedUserSetting suid;
5022            try {
5023                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5024                if (suid != null) {
5025                    return suid.userId;
5026                }
5027            } catch (PackageManagerException ignore) {
5028                // can't happen, but, still need to catch it
5029            }
5030            return -1;
5031        }
5032    }
5033
5034    @Override
5035    public int getFlagsForUid(int uid) {
5036        synchronized (mPackages) {
5037            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5038            if (obj instanceof SharedUserSetting) {
5039                final SharedUserSetting sus = (SharedUserSetting) obj;
5040                return sus.pkgFlags;
5041            } else if (obj instanceof PackageSetting) {
5042                final PackageSetting ps = (PackageSetting) obj;
5043                return ps.pkgFlags;
5044            }
5045        }
5046        return 0;
5047    }
5048
5049    @Override
5050    public int getPrivateFlagsForUid(int uid) {
5051        synchronized (mPackages) {
5052            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5053            if (obj instanceof SharedUserSetting) {
5054                final SharedUserSetting sus = (SharedUserSetting) obj;
5055                return sus.pkgPrivateFlags;
5056            } else if (obj instanceof PackageSetting) {
5057                final PackageSetting ps = (PackageSetting) obj;
5058                return ps.pkgPrivateFlags;
5059            }
5060        }
5061        return 0;
5062    }
5063
5064    @Override
5065    public boolean isUidPrivileged(int uid) {
5066        uid = UserHandle.getAppId(uid);
5067        // reader
5068        synchronized (mPackages) {
5069            Object obj = mSettings.getUserIdLPr(uid);
5070            if (obj instanceof SharedUserSetting) {
5071                final SharedUserSetting sus = (SharedUserSetting) obj;
5072                final Iterator<PackageSetting> it = sus.packages.iterator();
5073                while (it.hasNext()) {
5074                    if (it.next().isPrivileged()) {
5075                        return true;
5076                    }
5077                }
5078            } else if (obj instanceof PackageSetting) {
5079                final PackageSetting ps = (PackageSetting) obj;
5080                return ps.isPrivileged();
5081            }
5082        }
5083        return false;
5084    }
5085
5086    @Override
5087    public String[] getAppOpPermissionPackages(String permissionName) {
5088        synchronized (mPackages) {
5089            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5090            if (pkgs == null) {
5091                return null;
5092            }
5093            return pkgs.toArray(new String[pkgs.size()]);
5094        }
5095    }
5096
5097    @Override
5098    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5099            int flags, int userId) {
5100        try {
5101            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5102
5103            if (!sUserManager.exists(userId)) return null;
5104            flags = updateFlagsForResolve(flags, userId, intent);
5105            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5106                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5107
5108            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5109            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5110                    flags, userId);
5111            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5112
5113            final ResolveInfo bestChoice =
5114                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5115            return bestChoice;
5116        } finally {
5117            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5118        }
5119    }
5120
5121    @Override
5122    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5123            IntentFilter filter, int match, ComponentName activity) {
5124        final int userId = UserHandle.getCallingUserId();
5125        if (DEBUG_PREFERRED) {
5126            Log.v(TAG, "setLastChosenActivity intent=" + intent
5127                + " resolvedType=" + resolvedType
5128                + " flags=" + flags
5129                + " filter=" + filter
5130                + " match=" + match
5131                + " activity=" + activity);
5132            filter.dump(new PrintStreamPrinter(System.out), "    ");
5133        }
5134        intent.setComponent(null);
5135        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5136                userId);
5137        // Find any earlier preferred or last chosen entries and nuke them
5138        findPreferredActivity(intent, resolvedType,
5139                flags, query, 0, false, true, false, userId);
5140        // Add the new activity as the last chosen for this filter
5141        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5142                "Setting last chosen");
5143    }
5144
5145    @Override
5146    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5147        final int userId = UserHandle.getCallingUserId();
5148        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5149        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5150                userId);
5151        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5152                false, false, false, userId);
5153    }
5154
5155    private boolean isEphemeralDisabled() {
5156        // ephemeral apps have been disabled across the board
5157        if (DISABLE_EPHEMERAL_APPS) {
5158            return true;
5159        }
5160        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5161        if (!mSystemReady) {
5162            return true;
5163        }
5164        // we can't get a content resolver until the system is ready; these checks must happen last
5165        final ContentResolver resolver = mContext.getContentResolver();
5166        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5167            return true;
5168        }
5169        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5170    }
5171
5172    private boolean isEphemeralAllowed(
5173            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5174            boolean skipPackageCheck) {
5175        // Short circuit and return early if possible.
5176        if (isEphemeralDisabled()) {
5177            return false;
5178        }
5179        final int callingUser = UserHandle.getCallingUserId();
5180        if (callingUser != UserHandle.USER_SYSTEM) {
5181            return false;
5182        }
5183        if (mEphemeralResolverConnection == null) {
5184            return false;
5185        }
5186        if (mEphemeralInstallerComponent == null) {
5187            return false;
5188        }
5189        if (intent.getComponent() != null) {
5190            return false;
5191        }
5192        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5193            return false;
5194        }
5195        if (!skipPackageCheck && intent.getPackage() != null) {
5196            return false;
5197        }
5198        final boolean isWebUri = hasWebURI(intent);
5199        if (!isWebUri || intent.getData().getHost() == null) {
5200            return false;
5201        }
5202        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5203        synchronized (mPackages) {
5204            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5205            for (int n = 0; n < count; n++) {
5206                ResolveInfo info = resolvedActivities.get(n);
5207                String packageName = info.activityInfo.packageName;
5208                PackageSetting ps = mSettings.mPackages.get(packageName);
5209                if (ps != null) {
5210                    // Try to get the status from User settings first
5211                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5212                    int status = (int) (packedStatus >> 32);
5213                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5214                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5215                        if (DEBUG_EPHEMERAL) {
5216                            Slog.v(TAG, "DENY ephemeral apps;"
5217                                + " pkg: " + packageName + ", status: " + status);
5218                        }
5219                        return false;
5220                    }
5221                }
5222            }
5223        }
5224        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5225        return true;
5226    }
5227
5228    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5229            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5230            int userId) {
5231        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5232                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5233                        callingPackage, userId));
5234        mHandler.sendMessage(msg);
5235    }
5236
5237    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5238            int flags, List<ResolveInfo> query, int userId) {
5239        if (query != null) {
5240            final int N = query.size();
5241            if (N == 1) {
5242                return query.get(0);
5243            } else if (N > 1) {
5244                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5245                // If there is more than one activity with the same priority,
5246                // then let the user decide between them.
5247                ResolveInfo r0 = query.get(0);
5248                ResolveInfo r1 = query.get(1);
5249                if (DEBUG_INTENT_MATCHING || debug) {
5250                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5251                            + r1.activityInfo.name + "=" + r1.priority);
5252                }
5253                // If the first activity has a higher priority, or a different
5254                // default, then it is always desirable to pick it.
5255                if (r0.priority != r1.priority
5256                        || r0.preferredOrder != r1.preferredOrder
5257                        || r0.isDefault != r1.isDefault) {
5258                    return query.get(0);
5259                }
5260                // If we have saved a preference for a preferred activity for
5261                // this Intent, use that.
5262                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5263                        flags, query, r0.priority, true, false, debug, userId);
5264                if (ri != null) {
5265                    return ri;
5266                }
5267                ri = new ResolveInfo(mResolveInfo);
5268                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5269                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5270                // If all of the options come from the same package, show the application's
5271                // label and icon instead of the generic resolver's.
5272                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5273                // and then throw away the ResolveInfo itself, meaning that the caller loses
5274                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5275                // a fallback for this case; we only set the target package's resources on
5276                // the ResolveInfo, not the ActivityInfo.
5277                final String intentPackage = intent.getPackage();
5278                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5279                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5280                    ri.resolvePackageName = intentPackage;
5281                    if (userNeedsBadging(userId)) {
5282                        ri.noResourceId = true;
5283                    } else {
5284                        ri.icon = appi.icon;
5285                    }
5286                    ri.iconResourceId = appi.icon;
5287                    ri.labelRes = appi.labelRes;
5288                }
5289                ri.activityInfo.applicationInfo = new ApplicationInfo(
5290                        ri.activityInfo.applicationInfo);
5291                if (userId != 0) {
5292                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5293                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5294                }
5295                // Make sure that the resolver is displayable in car mode
5296                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5297                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5298                return ri;
5299            }
5300        }
5301        return null;
5302    }
5303
5304    /**
5305     * Return true if the given list is not empty and all of its contents have
5306     * an activityInfo with the given package name.
5307     */
5308    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5309        if (ArrayUtils.isEmpty(list)) {
5310            return false;
5311        }
5312        for (int i = 0, N = list.size(); i < N; i++) {
5313            final ResolveInfo ri = list.get(i);
5314            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5315            if (ai == null || !packageName.equals(ai.packageName)) {
5316                return false;
5317            }
5318        }
5319        return true;
5320    }
5321
5322    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5323            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5324        final int N = query.size();
5325        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5326                .get(userId);
5327        // Get the list of persistent preferred activities that handle the intent
5328        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5329        List<PersistentPreferredActivity> pprefs = ppir != null
5330                ? ppir.queryIntent(intent, resolvedType,
5331                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5332                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5333                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5334                : null;
5335        if (pprefs != null && pprefs.size() > 0) {
5336            final int M = pprefs.size();
5337            for (int i=0; i<M; i++) {
5338                final PersistentPreferredActivity ppa = pprefs.get(i);
5339                if (DEBUG_PREFERRED || debug) {
5340                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5341                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5342                            + "\n  component=" + ppa.mComponent);
5343                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5344                }
5345                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5346                        flags | MATCH_DISABLED_COMPONENTS, userId);
5347                if (DEBUG_PREFERRED || debug) {
5348                    Slog.v(TAG, "Found persistent preferred activity:");
5349                    if (ai != null) {
5350                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5351                    } else {
5352                        Slog.v(TAG, "  null");
5353                    }
5354                }
5355                if (ai == null) {
5356                    // This previously registered persistent preferred activity
5357                    // component is no longer known. Ignore it and do NOT remove it.
5358                    continue;
5359                }
5360                for (int j=0; j<N; j++) {
5361                    final ResolveInfo ri = query.get(j);
5362                    if (!ri.activityInfo.applicationInfo.packageName
5363                            .equals(ai.applicationInfo.packageName)) {
5364                        continue;
5365                    }
5366                    if (!ri.activityInfo.name.equals(ai.name)) {
5367                        continue;
5368                    }
5369                    //  Found a persistent preference that can handle the intent.
5370                    if (DEBUG_PREFERRED || debug) {
5371                        Slog.v(TAG, "Returning persistent preferred activity: " +
5372                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5373                    }
5374                    return ri;
5375                }
5376            }
5377        }
5378        return null;
5379    }
5380
5381    // TODO: handle preferred activities missing while user has amnesia
5382    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5383            List<ResolveInfo> query, int priority, boolean always,
5384            boolean removeMatches, boolean debug, int userId) {
5385        if (!sUserManager.exists(userId)) return null;
5386        flags = updateFlagsForResolve(flags, userId, intent);
5387        // writer
5388        synchronized (mPackages) {
5389            if (intent.getSelector() != null) {
5390                intent = intent.getSelector();
5391            }
5392            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5393
5394            // Try to find a matching persistent preferred activity.
5395            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5396                    debug, userId);
5397
5398            // If a persistent preferred activity matched, use it.
5399            if (pri != null) {
5400                return pri;
5401            }
5402
5403            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5404            // Get the list of preferred activities that handle the intent
5405            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5406            List<PreferredActivity> prefs = pir != null
5407                    ? pir.queryIntent(intent, resolvedType,
5408                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5409                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5410                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5411                    : null;
5412            if (prefs != null && prefs.size() > 0) {
5413                boolean changed = false;
5414                try {
5415                    // First figure out how good the original match set is.
5416                    // We will only allow preferred activities that came
5417                    // from the same match quality.
5418                    int match = 0;
5419
5420                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5421
5422                    final int N = query.size();
5423                    for (int j=0; j<N; j++) {
5424                        final ResolveInfo ri = query.get(j);
5425                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5426                                + ": 0x" + Integer.toHexString(match));
5427                        if (ri.match > match) {
5428                            match = ri.match;
5429                        }
5430                    }
5431
5432                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5433                            + Integer.toHexString(match));
5434
5435                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5436                    final int M = prefs.size();
5437                    for (int i=0; i<M; i++) {
5438                        final PreferredActivity pa = prefs.get(i);
5439                        if (DEBUG_PREFERRED || debug) {
5440                            Slog.v(TAG, "Checking PreferredActivity ds="
5441                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5442                                    + "\n  component=" + pa.mPref.mComponent);
5443                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5444                        }
5445                        if (pa.mPref.mMatch != match) {
5446                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5447                                    + Integer.toHexString(pa.mPref.mMatch));
5448                            continue;
5449                        }
5450                        // If it's not an "always" type preferred activity and that's what we're
5451                        // looking for, skip it.
5452                        if (always && !pa.mPref.mAlways) {
5453                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5454                            continue;
5455                        }
5456                        final ActivityInfo ai = getActivityInfo(
5457                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5458                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5459                                userId);
5460                        if (DEBUG_PREFERRED || debug) {
5461                            Slog.v(TAG, "Found preferred activity:");
5462                            if (ai != null) {
5463                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5464                            } else {
5465                                Slog.v(TAG, "  null");
5466                            }
5467                        }
5468                        if (ai == null) {
5469                            // This previously registered preferred activity
5470                            // component is no longer known.  Most likely an update
5471                            // to the app was installed and in the new version this
5472                            // component no longer exists.  Clean it up by removing
5473                            // it from the preferred activities list, and skip it.
5474                            Slog.w(TAG, "Removing dangling preferred activity: "
5475                                    + pa.mPref.mComponent);
5476                            pir.removeFilter(pa);
5477                            changed = true;
5478                            continue;
5479                        }
5480                        for (int j=0; j<N; j++) {
5481                            final ResolveInfo ri = query.get(j);
5482                            if (!ri.activityInfo.applicationInfo.packageName
5483                                    .equals(ai.applicationInfo.packageName)) {
5484                                continue;
5485                            }
5486                            if (!ri.activityInfo.name.equals(ai.name)) {
5487                                continue;
5488                            }
5489
5490                            if (removeMatches) {
5491                                pir.removeFilter(pa);
5492                                changed = true;
5493                                if (DEBUG_PREFERRED) {
5494                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5495                                }
5496                                break;
5497                            }
5498
5499                            // Okay we found a previously set preferred or last chosen app.
5500                            // If the result set is different from when this
5501                            // was created, we need to clear it and re-ask the
5502                            // user their preference, if we're looking for an "always" type entry.
5503                            if (always && !pa.mPref.sameSet(query)) {
5504                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5505                                        + intent + " type " + resolvedType);
5506                                if (DEBUG_PREFERRED) {
5507                                    Slog.v(TAG, "Removing preferred activity since set changed "
5508                                            + pa.mPref.mComponent);
5509                                }
5510                                pir.removeFilter(pa);
5511                                // Re-add the filter as a "last chosen" entry (!always)
5512                                PreferredActivity lastChosen = new PreferredActivity(
5513                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5514                                pir.addFilter(lastChosen);
5515                                changed = true;
5516                                return null;
5517                            }
5518
5519                            // Yay! Either the set matched or we're looking for the last chosen
5520                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5521                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5522                            return ri;
5523                        }
5524                    }
5525                } finally {
5526                    if (changed) {
5527                        if (DEBUG_PREFERRED) {
5528                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5529                        }
5530                        scheduleWritePackageRestrictionsLocked(userId);
5531                    }
5532                }
5533            }
5534        }
5535        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5536        return null;
5537    }
5538
5539    /*
5540     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5541     */
5542    @Override
5543    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5544            int targetUserId) {
5545        mContext.enforceCallingOrSelfPermission(
5546                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5547        List<CrossProfileIntentFilter> matches =
5548                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5549        if (matches != null) {
5550            int size = matches.size();
5551            for (int i = 0; i < size; i++) {
5552                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5553            }
5554        }
5555        if (hasWebURI(intent)) {
5556            // cross-profile app linking works only towards the parent.
5557            final UserInfo parent = getProfileParent(sourceUserId);
5558            synchronized(mPackages) {
5559                int flags = updateFlagsForResolve(0, parent.id, intent);
5560                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5561                        intent, resolvedType, flags, sourceUserId, parent.id);
5562                return xpDomainInfo != null;
5563            }
5564        }
5565        return false;
5566    }
5567
5568    private UserInfo getProfileParent(int userId) {
5569        final long identity = Binder.clearCallingIdentity();
5570        try {
5571            return sUserManager.getProfileParent(userId);
5572        } finally {
5573            Binder.restoreCallingIdentity(identity);
5574        }
5575    }
5576
5577    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5578            String resolvedType, int userId) {
5579        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5580        if (resolver != null) {
5581            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5582                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5583        }
5584        return null;
5585    }
5586
5587    @Override
5588    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5589            String resolvedType, int flags, int userId) {
5590        try {
5591            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5592
5593            return new ParceledListSlice<>(
5594                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5595        } finally {
5596            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5597        }
5598    }
5599
5600    /**
5601     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5602     * ephemeral, returns {@code null}.
5603     */
5604    private String getEphemeralPackageName(int callingUid) {
5605        final int appId = UserHandle.getAppId(callingUid);
5606        synchronized (mPackages) {
5607            final Object obj = mSettings.getUserIdLPr(appId);
5608            if (obj instanceof PackageSetting) {
5609                final PackageSetting ps = (PackageSetting) obj;
5610                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5611            }
5612        }
5613        return null;
5614    }
5615
5616    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5617            String resolvedType, int flags, int userId) {
5618        if (!sUserManager.exists(userId)) return Collections.emptyList();
5619        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5620        flags = updateFlagsForResolve(flags, userId, intent);
5621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5622                false /* requireFullPermission */, false /* checkShell */,
5623                "query intent activities");
5624        ComponentName comp = intent.getComponent();
5625        if (comp == null) {
5626            if (intent.getSelector() != null) {
5627                intent = intent.getSelector();
5628                comp = intent.getComponent();
5629            }
5630        }
5631
5632        if (comp != null) {
5633            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5634            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5635            if (ai != null) {
5636                // When specifying an explicit component, we prevent the activity from being
5637                // used when either 1) the calling package is normal and the activity is within
5638                // an ephemeral application or 2) the calling package is ephemeral and the
5639                // activity is not visible to ephemeral applications.
5640                boolean matchEphemeral =
5641                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5642                boolean ephemeralVisibleOnly =
5643                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5644                boolean blockResolution =
5645                        (!matchEphemeral && ephemeralPkgName == null
5646                                && (ai.applicationInfo.privateFlags
5647                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5648                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5649                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5650                if (!blockResolution) {
5651                    final ResolveInfo ri = new ResolveInfo();
5652                    ri.activityInfo = ai;
5653                    list.add(ri);
5654                }
5655            }
5656            return list;
5657        }
5658
5659        // reader
5660        boolean sortResult = false;
5661        boolean addEphemeral = false;
5662        List<ResolveInfo> result;
5663        final String pkgName = intent.getPackage();
5664        synchronized (mPackages) {
5665            if (pkgName == null) {
5666                List<CrossProfileIntentFilter> matchingFilters =
5667                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5668                // Check for results that need to skip the current profile.
5669                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5670                        resolvedType, flags, userId);
5671                if (xpResolveInfo != null) {
5672                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5673                    xpResult.add(xpResolveInfo);
5674                    return filterForEphemeral(
5675                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5676                }
5677
5678                // Check for results in the current profile.
5679                result = filterIfNotSystemUser(mActivities.queryIntent(
5680                        intent, resolvedType, flags, userId), userId);
5681                addEphemeral =
5682                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5683
5684                // Check for cross profile results.
5685                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5686                xpResolveInfo = queryCrossProfileIntents(
5687                        matchingFilters, intent, resolvedType, flags, userId,
5688                        hasNonNegativePriorityResult);
5689                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5690                    boolean isVisibleToUser = filterIfNotSystemUser(
5691                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5692                    if (isVisibleToUser) {
5693                        result.add(xpResolveInfo);
5694                        sortResult = true;
5695                    }
5696                }
5697                if (hasWebURI(intent)) {
5698                    CrossProfileDomainInfo xpDomainInfo = null;
5699                    final UserInfo parent = getProfileParent(userId);
5700                    if (parent != null) {
5701                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5702                                flags, userId, parent.id);
5703                    }
5704                    if (xpDomainInfo != null) {
5705                        if (xpResolveInfo != null) {
5706                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5707                            // in the result.
5708                            result.remove(xpResolveInfo);
5709                        }
5710                        if (result.size() == 0 && !addEphemeral) {
5711                            // No result in current profile, but found candidate in parent user.
5712                            // And we are not going to add emphemeral app, so we can return the
5713                            // result straight away.
5714                            result.add(xpDomainInfo.resolveInfo);
5715                            return filterForEphemeral(result, ephemeralPkgName);
5716                        }
5717                    } else if (result.size() <= 1 && !addEphemeral) {
5718                        // No result in parent user and <= 1 result in current profile, and we
5719                        // are not going to add emphemeral app, so we can return the result without
5720                        // further processing.
5721                        return filterForEphemeral(result, ephemeralPkgName);
5722                    }
5723                    // We have more than one candidate (combining results from current and parent
5724                    // profile), so we need filtering and sorting.
5725                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5726                            intent, flags, result, xpDomainInfo, userId);
5727                    sortResult = true;
5728                }
5729            } else {
5730                final PackageParser.Package pkg = mPackages.get(pkgName);
5731                if (pkg != null) {
5732                    result = filterForEphemeral(filterIfNotSystemUser(
5733                            mActivities.queryIntentForPackage(
5734                                    intent, resolvedType, flags, pkg.activities, userId),
5735                            userId), ephemeralPkgName);
5736                } else {
5737                    // the caller wants to resolve for a particular package; however, there
5738                    // were no installed results, so, try to find an ephemeral result
5739                    addEphemeral = isEphemeralAllowed(
5740                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5741                    result = new ArrayList<ResolveInfo>();
5742                }
5743            }
5744        }
5745        if (addEphemeral) {
5746            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5747            final EphemeralRequest requestObject = new EphemeralRequest(
5748                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5749                    null /*launchIntent*/, null /*callingPackage*/, userId);
5750            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5751                    mContext, mEphemeralResolverConnection, requestObject);
5752            if (intentInfo != null) {
5753                if (DEBUG_EPHEMERAL) {
5754                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5755                }
5756                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5757                ephemeralInstaller.ephemeralResponse = intentInfo;
5758                // make sure this resolver is the default
5759                ephemeralInstaller.isDefault = true;
5760                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5761                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5762                // add a non-generic filter
5763                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5764                ephemeralInstaller.filter.addDataPath(
5765                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5766                result.add(ephemeralInstaller);
5767            }
5768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5769        }
5770        if (sortResult) {
5771            Collections.sort(result, mResolvePrioritySorter);
5772        }
5773        return filterForEphemeral(result, ephemeralPkgName);
5774    }
5775
5776    private static class CrossProfileDomainInfo {
5777        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5778        ResolveInfo resolveInfo;
5779        /* Best domain verification status of the activities found in the other profile */
5780        int bestDomainVerificationStatus;
5781    }
5782
5783    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5784            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5785        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5786                sourceUserId)) {
5787            return null;
5788        }
5789        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5790                resolvedType, flags, parentUserId);
5791
5792        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5793            return null;
5794        }
5795        CrossProfileDomainInfo result = null;
5796        int size = resultTargetUser.size();
5797        for (int i = 0; i < size; i++) {
5798            ResolveInfo riTargetUser = resultTargetUser.get(i);
5799            // Intent filter verification is only for filters that specify a host. So don't return
5800            // those that handle all web uris.
5801            if (riTargetUser.handleAllWebDataURI) {
5802                continue;
5803            }
5804            String packageName = riTargetUser.activityInfo.packageName;
5805            PackageSetting ps = mSettings.mPackages.get(packageName);
5806            if (ps == null) {
5807                continue;
5808            }
5809            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5810            int status = (int)(verificationState >> 32);
5811            if (result == null) {
5812                result = new CrossProfileDomainInfo();
5813                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5814                        sourceUserId, parentUserId);
5815                result.bestDomainVerificationStatus = status;
5816            } else {
5817                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5818                        result.bestDomainVerificationStatus);
5819            }
5820        }
5821        // Don't consider matches with status NEVER across profiles.
5822        if (result != null && result.bestDomainVerificationStatus
5823                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5824            return null;
5825        }
5826        return result;
5827    }
5828
5829    /**
5830     * Verification statuses are ordered from the worse to the best, except for
5831     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5832     */
5833    private int bestDomainVerificationStatus(int status1, int status2) {
5834        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5835            return status2;
5836        }
5837        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5838            return status1;
5839        }
5840        return (int) MathUtils.max(status1, status2);
5841    }
5842
5843    private boolean isUserEnabled(int userId) {
5844        long callingId = Binder.clearCallingIdentity();
5845        try {
5846            UserInfo userInfo = sUserManager.getUserInfo(userId);
5847            return userInfo != null && userInfo.isEnabled();
5848        } finally {
5849            Binder.restoreCallingIdentity(callingId);
5850        }
5851    }
5852
5853    /**
5854     * Filter out activities with systemUserOnly flag set, when current user is not System.
5855     *
5856     * @return filtered list
5857     */
5858    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5859        if (userId == UserHandle.USER_SYSTEM) {
5860            return resolveInfos;
5861        }
5862        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5863            ResolveInfo info = resolveInfos.get(i);
5864            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5865                resolveInfos.remove(i);
5866            }
5867        }
5868        return resolveInfos;
5869    }
5870
5871    /**
5872     * Filters out ephemeral activities.
5873     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5874     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5875     *
5876     * @param resolveInfos The pre-filtered list of resolved activities
5877     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5878     *          is performed.
5879     * @return A filtered list of resolved activities.
5880     */
5881    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5882            String ephemeralPkgName) {
5883        if (ephemeralPkgName == null) {
5884            return resolveInfos;
5885        }
5886        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5887            ResolveInfo info = resolveInfos.get(i);
5888            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5889            // allow activities that are defined in the provided package
5890            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5891                continue;
5892            }
5893            // allow activities that have been explicitly exposed to ephemeral apps
5894            if (!isEphemeralApp
5895                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5896                continue;
5897            }
5898            resolveInfos.remove(i);
5899        }
5900        return resolveInfos;
5901    }
5902
5903    /**
5904     * @param resolveInfos list of resolve infos in descending priority order
5905     * @return if the list contains a resolve info with non-negative priority
5906     */
5907    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5908        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5909    }
5910
5911    private static boolean hasWebURI(Intent intent) {
5912        if (intent.getData() == null) {
5913            return false;
5914        }
5915        final String scheme = intent.getScheme();
5916        if (TextUtils.isEmpty(scheme)) {
5917            return false;
5918        }
5919        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5920    }
5921
5922    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5923            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5924            int userId) {
5925        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5926
5927        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5928            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5929                    candidates.size());
5930        }
5931
5932        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5933        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5934        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5935        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5936        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5937        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5938
5939        synchronized (mPackages) {
5940            final int count = candidates.size();
5941            // First, try to use linked apps. Partition the candidates into four lists:
5942            // one for the final results, one for the "do not use ever", one for "undefined status"
5943            // and finally one for "browser app type".
5944            for (int n=0; n<count; n++) {
5945                ResolveInfo info = candidates.get(n);
5946                String packageName = info.activityInfo.packageName;
5947                PackageSetting ps = mSettings.mPackages.get(packageName);
5948                if (ps != null) {
5949                    // Add to the special match all list (Browser use case)
5950                    if (info.handleAllWebDataURI) {
5951                        matchAllList.add(info);
5952                        continue;
5953                    }
5954                    // Try to get the status from User settings first
5955                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5956                    int status = (int)(packedStatus >> 32);
5957                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5958                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5959                        if (DEBUG_DOMAIN_VERIFICATION) {
5960                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5961                                    + " : linkgen=" + linkGeneration);
5962                        }
5963                        // Use link-enabled generation as preferredOrder, i.e.
5964                        // prefer newly-enabled over earlier-enabled.
5965                        info.preferredOrder = linkGeneration;
5966                        alwaysList.add(info);
5967                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5968                        if (DEBUG_DOMAIN_VERIFICATION) {
5969                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5970                        }
5971                        neverList.add(info);
5972                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5973                        if (DEBUG_DOMAIN_VERIFICATION) {
5974                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5975                        }
5976                        alwaysAskList.add(info);
5977                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5978                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5979                        if (DEBUG_DOMAIN_VERIFICATION) {
5980                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5981                        }
5982                        undefinedList.add(info);
5983                    }
5984                }
5985            }
5986
5987            // We'll want to include browser possibilities in a few cases
5988            boolean includeBrowser = false;
5989
5990            // First try to add the "always" resolution(s) for the current user, if any
5991            if (alwaysList.size() > 0) {
5992                result.addAll(alwaysList);
5993            } else {
5994                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5995                result.addAll(undefinedList);
5996                // Maybe add one for the other profile.
5997                if (xpDomainInfo != null && (
5998                        xpDomainInfo.bestDomainVerificationStatus
5999                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6000                    result.add(xpDomainInfo.resolveInfo);
6001                }
6002                includeBrowser = true;
6003            }
6004
6005            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6006            // If there were 'always' entries their preferred order has been set, so we also
6007            // back that off to make the alternatives equivalent
6008            if (alwaysAskList.size() > 0) {
6009                for (ResolveInfo i : result) {
6010                    i.preferredOrder = 0;
6011                }
6012                result.addAll(alwaysAskList);
6013                includeBrowser = true;
6014            }
6015
6016            if (includeBrowser) {
6017                // Also add browsers (all of them or only the default one)
6018                if (DEBUG_DOMAIN_VERIFICATION) {
6019                    Slog.v(TAG, "   ...including browsers in candidate set");
6020                }
6021                if ((matchFlags & MATCH_ALL) != 0) {
6022                    result.addAll(matchAllList);
6023                } else {
6024                    // Browser/generic handling case.  If there's a default browser, go straight
6025                    // to that (but only if there is no other higher-priority match).
6026                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6027                    int maxMatchPrio = 0;
6028                    ResolveInfo defaultBrowserMatch = null;
6029                    final int numCandidates = matchAllList.size();
6030                    for (int n = 0; n < numCandidates; n++) {
6031                        ResolveInfo info = matchAllList.get(n);
6032                        // track the highest overall match priority...
6033                        if (info.priority > maxMatchPrio) {
6034                            maxMatchPrio = info.priority;
6035                        }
6036                        // ...and the highest-priority default browser match
6037                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6038                            if (defaultBrowserMatch == null
6039                                    || (defaultBrowserMatch.priority < info.priority)) {
6040                                if (debug) {
6041                                    Slog.v(TAG, "Considering default browser match " + info);
6042                                }
6043                                defaultBrowserMatch = info;
6044                            }
6045                        }
6046                    }
6047                    if (defaultBrowserMatch != null
6048                            && defaultBrowserMatch.priority >= maxMatchPrio
6049                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6050                    {
6051                        if (debug) {
6052                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6053                        }
6054                        result.add(defaultBrowserMatch);
6055                    } else {
6056                        result.addAll(matchAllList);
6057                    }
6058                }
6059
6060                // If there is nothing selected, add all candidates and remove the ones that the user
6061                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6062                if (result.size() == 0) {
6063                    result.addAll(candidates);
6064                    result.removeAll(neverList);
6065                }
6066            }
6067        }
6068        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6069            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6070                    result.size());
6071            for (ResolveInfo info : result) {
6072                Slog.v(TAG, "  + " + info.activityInfo);
6073            }
6074        }
6075        return result;
6076    }
6077
6078    // Returns a packed value as a long:
6079    //
6080    // high 'int'-sized word: link status: undefined/ask/never/always.
6081    // low 'int'-sized word: relative priority among 'always' results.
6082    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6083        long result = ps.getDomainVerificationStatusForUser(userId);
6084        // if none available, get the master status
6085        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6086            if (ps.getIntentFilterVerificationInfo() != null) {
6087                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6088            }
6089        }
6090        return result;
6091    }
6092
6093    private ResolveInfo querySkipCurrentProfileIntents(
6094            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6095            int flags, int sourceUserId) {
6096        if (matchingFilters != null) {
6097            int size = matchingFilters.size();
6098            for (int i = 0; i < size; i ++) {
6099                CrossProfileIntentFilter filter = matchingFilters.get(i);
6100                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6101                    // Checking if there are activities in the target user that can handle the
6102                    // intent.
6103                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6104                            resolvedType, flags, sourceUserId);
6105                    if (resolveInfo != null) {
6106                        return resolveInfo;
6107                    }
6108                }
6109            }
6110        }
6111        return null;
6112    }
6113
6114    // Return matching ResolveInfo in target user if any.
6115    private ResolveInfo queryCrossProfileIntents(
6116            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6117            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6118        if (matchingFilters != null) {
6119            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6120            // match the same intent. For performance reasons, it is better not to
6121            // run queryIntent twice for the same userId
6122            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6123            int size = matchingFilters.size();
6124            for (int i = 0; i < size; i++) {
6125                CrossProfileIntentFilter filter = matchingFilters.get(i);
6126                int targetUserId = filter.getTargetUserId();
6127                boolean skipCurrentProfile =
6128                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6129                boolean skipCurrentProfileIfNoMatchFound =
6130                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6131                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6132                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6133                    // Checking if there are activities in the target user that can handle the
6134                    // intent.
6135                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6136                            resolvedType, flags, sourceUserId);
6137                    if (resolveInfo != null) return resolveInfo;
6138                    alreadyTriedUserIds.put(targetUserId, true);
6139                }
6140            }
6141        }
6142        return null;
6143    }
6144
6145    /**
6146     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6147     * will forward the intent to the filter's target user.
6148     * Otherwise, returns null.
6149     */
6150    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6151            String resolvedType, int flags, int sourceUserId) {
6152        int targetUserId = filter.getTargetUserId();
6153        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6154                resolvedType, flags, targetUserId);
6155        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6156            // If all the matches in the target profile are suspended, return null.
6157            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6158                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6159                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6160                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6161                            targetUserId);
6162                }
6163            }
6164        }
6165        return null;
6166    }
6167
6168    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6169            int sourceUserId, int targetUserId) {
6170        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6171        long ident = Binder.clearCallingIdentity();
6172        boolean targetIsProfile;
6173        try {
6174            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6175        } finally {
6176            Binder.restoreCallingIdentity(ident);
6177        }
6178        String className;
6179        if (targetIsProfile) {
6180            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6181        } else {
6182            className = FORWARD_INTENT_TO_PARENT;
6183        }
6184        ComponentName forwardingActivityComponentName = new ComponentName(
6185                mAndroidApplication.packageName, className);
6186        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6187                sourceUserId);
6188        if (!targetIsProfile) {
6189            forwardingActivityInfo.showUserIcon = targetUserId;
6190            forwardingResolveInfo.noResourceId = true;
6191        }
6192        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6193        forwardingResolveInfo.priority = 0;
6194        forwardingResolveInfo.preferredOrder = 0;
6195        forwardingResolveInfo.match = 0;
6196        forwardingResolveInfo.isDefault = true;
6197        forwardingResolveInfo.filter = filter;
6198        forwardingResolveInfo.targetUserId = targetUserId;
6199        return forwardingResolveInfo;
6200    }
6201
6202    @Override
6203    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6204            Intent[] specifics, String[] specificTypes, Intent intent,
6205            String resolvedType, int flags, int userId) {
6206        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6207                specificTypes, intent, resolvedType, flags, userId));
6208    }
6209
6210    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6211            Intent[] specifics, String[] specificTypes, Intent intent,
6212            String resolvedType, int flags, int userId) {
6213        if (!sUserManager.exists(userId)) return Collections.emptyList();
6214        flags = updateFlagsForResolve(flags, userId, intent);
6215        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6216                false /* requireFullPermission */, false /* checkShell */,
6217                "query intent activity options");
6218        final String resultsAction = intent.getAction();
6219
6220        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6221                | PackageManager.GET_RESOLVED_FILTER, userId);
6222
6223        if (DEBUG_INTENT_MATCHING) {
6224            Log.v(TAG, "Query " + intent + ": " + results);
6225        }
6226
6227        int specificsPos = 0;
6228        int N;
6229
6230        // todo: note that the algorithm used here is O(N^2).  This
6231        // isn't a problem in our current environment, but if we start running
6232        // into situations where we have more than 5 or 10 matches then this
6233        // should probably be changed to something smarter...
6234
6235        // First we go through and resolve each of the specific items
6236        // that were supplied, taking care of removing any corresponding
6237        // duplicate items in the generic resolve list.
6238        if (specifics != null) {
6239            for (int i=0; i<specifics.length; i++) {
6240                final Intent sintent = specifics[i];
6241                if (sintent == null) {
6242                    continue;
6243                }
6244
6245                if (DEBUG_INTENT_MATCHING) {
6246                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6247                }
6248
6249                String action = sintent.getAction();
6250                if (resultsAction != null && resultsAction.equals(action)) {
6251                    // If this action was explicitly requested, then don't
6252                    // remove things that have it.
6253                    action = null;
6254                }
6255
6256                ResolveInfo ri = null;
6257                ActivityInfo ai = null;
6258
6259                ComponentName comp = sintent.getComponent();
6260                if (comp == null) {
6261                    ri = resolveIntent(
6262                        sintent,
6263                        specificTypes != null ? specificTypes[i] : null,
6264                            flags, userId);
6265                    if (ri == null) {
6266                        continue;
6267                    }
6268                    if (ri == mResolveInfo) {
6269                        // ACK!  Must do something better with this.
6270                    }
6271                    ai = ri.activityInfo;
6272                    comp = new ComponentName(ai.applicationInfo.packageName,
6273                            ai.name);
6274                } else {
6275                    ai = getActivityInfo(comp, flags, userId);
6276                    if (ai == null) {
6277                        continue;
6278                    }
6279                }
6280
6281                // Look for any generic query activities that are duplicates
6282                // of this specific one, and remove them from the results.
6283                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6284                N = results.size();
6285                int j;
6286                for (j=specificsPos; j<N; j++) {
6287                    ResolveInfo sri = results.get(j);
6288                    if ((sri.activityInfo.name.equals(comp.getClassName())
6289                            && sri.activityInfo.applicationInfo.packageName.equals(
6290                                    comp.getPackageName()))
6291                        || (action != null && sri.filter.matchAction(action))) {
6292                        results.remove(j);
6293                        if (DEBUG_INTENT_MATCHING) Log.v(
6294                            TAG, "Removing duplicate item from " + j
6295                            + " due to specific " + specificsPos);
6296                        if (ri == null) {
6297                            ri = sri;
6298                        }
6299                        j--;
6300                        N--;
6301                    }
6302                }
6303
6304                // Add this specific item to its proper place.
6305                if (ri == null) {
6306                    ri = new ResolveInfo();
6307                    ri.activityInfo = ai;
6308                }
6309                results.add(specificsPos, ri);
6310                ri.specificIndex = i;
6311                specificsPos++;
6312            }
6313        }
6314
6315        // Now we go through the remaining generic results and remove any
6316        // duplicate actions that are found here.
6317        N = results.size();
6318        for (int i=specificsPos; i<N-1; i++) {
6319            final ResolveInfo rii = results.get(i);
6320            if (rii.filter == null) {
6321                continue;
6322            }
6323
6324            // Iterate over all of the actions of this result's intent
6325            // filter...  typically this should be just one.
6326            final Iterator<String> it = rii.filter.actionsIterator();
6327            if (it == null) {
6328                continue;
6329            }
6330            while (it.hasNext()) {
6331                final String action = it.next();
6332                if (resultsAction != null && resultsAction.equals(action)) {
6333                    // If this action was explicitly requested, then don't
6334                    // remove things that have it.
6335                    continue;
6336                }
6337                for (int j=i+1; j<N; j++) {
6338                    final ResolveInfo rij = results.get(j);
6339                    if (rij.filter != null && rij.filter.hasAction(action)) {
6340                        results.remove(j);
6341                        if (DEBUG_INTENT_MATCHING) Log.v(
6342                            TAG, "Removing duplicate item from " + j
6343                            + " due to action " + action + " at " + i);
6344                        j--;
6345                        N--;
6346                    }
6347                }
6348            }
6349
6350            // If the caller didn't request filter information, drop it now
6351            // so we don't have to marshall/unmarshall it.
6352            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6353                rii.filter = null;
6354            }
6355        }
6356
6357        // Filter out the caller activity if so requested.
6358        if (caller != null) {
6359            N = results.size();
6360            for (int i=0; i<N; i++) {
6361                ActivityInfo ainfo = results.get(i).activityInfo;
6362                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6363                        && caller.getClassName().equals(ainfo.name)) {
6364                    results.remove(i);
6365                    break;
6366                }
6367            }
6368        }
6369
6370        // If the caller didn't request filter information,
6371        // drop them now so we don't have to
6372        // marshall/unmarshall it.
6373        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6374            N = results.size();
6375            for (int i=0; i<N; i++) {
6376                results.get(i).filter = null;
6377            }
6378        }
6379
6380        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6381        return results;
6382    }
6383
6384    @Override
6385    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6386            String resolvedType, int flags, int userId) {
6387        return new ParceledListSlice<>(
6388                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6389    }
6390
6391    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6392            String resolvedType, int flags, int userId) {
6393        if (!sUserManager.exists(userId)) return Collections.emptyList();
6394        flags = updateFlagsForResolve(flags, userId, intent);
6395        ComponentName comp = intent.getComponent();
6396        if (comp == null) {
6397            if (intent.getSelector() != null) {
6398                intent = intent.getSelector();
6399                comp = intent.getComponent();
6400            }
6401        }
6402        if (comp != null) {
6403            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6404            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6405            if (ai != null) {
6406                ResolveInfo ri = new ResolveInfo();
6407                ri.activityInfo = ai;
6408                list.add(ri);
6409            }
6410            return list;
6411        }
6412
6413        // reader
6414        synchronized (mPackages) {
6415            String pkgName = intent.getPackage();
6416            if (pkgName == null) {
6417                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6418            }
6419            final PackageParser.Package pkg = mPackages.get(pkgName);
6420            if (pkg != null) {
6421                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6422                        userId);
6423            }
6424            return Collections.emptyList();
6425        }
6426    }
6427
6428    @Override
6429    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6430        if (!sUserManager.exists(userId)) return null;
6431        flags = updateFlagsForResolve(flags, userId, intent);
6432        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6433        if (query != null) {
6434            if (query.size() >= 1) {
6435                // If there is more than one service with the same priority,
6436                // just arbitrarily pick the first one.
6437                return query.get(0);
6438            }
6439        }
6440        return null;
6441    }
6442
6443    @Override
6444    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6445            String resolvedType, int flags, int userId) {
6446        return new ParceledListSlice<>(
6447                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6448    }
6449
6450    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6451            String resolvedType, int flags, int userId) {
6452        if (!sUserManager.exists(userId)) return Collections.emptyList();
6453        flags = updateFlagsForResolve(flags, userId, intent);
6454        ComponentName comp = intent.getComponent();
6455        if (comp == null) {
6456            if (intent.getSelector() != null) {
6457                intent = intent.getSelector();
6458                comp = intent.getComponent();
6459            }
6460        }
6461        if (comp != null) {
6462            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6463            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6464            if (si != null) {
6465                final ResolveInfo ri = new ResolveInfo();
6466                ri.serviceInfo = si;
6467                list.add(ri);
6468            }
6469            return list;
6470        }
6471
6472        // reader
6473        synchronized (mPackages) {
6474            String pkgName = intent.getPackage();
6475            if (pkgName == null) {
6476                return mServices.queryIntent(intent, resolvedType, flags, userId);
6477            }
6478            final PackageParser.Package pkg = mPackages.get(pkgName);
6479            if (pkg != null) {
6480                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6481                        userId);
6482            }
6483            return Collections.emptyList();
6484        }
6485    }
6486
6487    @Override
6488    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6489            String resolvedType, int flags, int userId) {
6490        return new ParceledListSlice<>(
6491                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6492    }
6493
6494    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6495            Intent intent, String resolvedType, int flags, int userId) {
6496        if (!sUserManager.exists(userId)) return Collections.emptyList();
6497        flags = updateFlagsForResolve(flags, userId, intent);
6498        ComponentName comp = intent.getComponent();
6499        if (comp == null) {
6500            if (intent.getSelector() != null) {
6501                intent = intent.getSelector();
6502                comp = intent.getComponent();
6503            }
6504        }
6505        if (comp != null) {
6506            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6507            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6508            if (pi != null) {
6509                final ResolveInfo ri = new ResolveInfo();
6510                ri.providerInfo = pi;
6511                list.add(ri);
6512            }
6513            return list;
6514        }
6515
6516        // reader
6517        synchronized (mPackages) {
6518            String pkgName = intent.getPackage();
6519            if (pkgName == null) {
6520                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6521            }
6522            final PackageParser.Package pkg = mPackages.get(pkgName);
6523            if (pkg != null) {
6524                return mProviders.queryIntentForPackage(
6525                        intent, resolvedType, flags, pkg.providers, userId);
6526            }
6527            return Collections.emptyList();
6528        }
6529    }
6530
6531    @Override
6532    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6533        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6534        flags = updateFlagsForPackage(flags, userId, null);
6535        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6536        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6537                true /* requireFullPermission */, false /* checkShell */,
6538                "get installed packages");
6539
6540        // writer
6541        synchronized (mPackages) {
6542            ArrayList<PackageInfo> list;
6543            if (listUninstalled) {
6544                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6545                for (PackageSetting ps : mSettings.mPackages.values()) {
6546                    final PackageInfo pi;
6547                    if (ps.pkg != null) {
6548                        pi = generatePackageInfo(ps, flags, userId);
6549                    } else {
6550                        pi = generatePackageInfo(ps, flags, userId);
6551                    }
6552                    if (pi != null) {
6553                        list.add(pi);
6554                    }
6555                }
6556            } else {
6557                list = new ArrayList<PackageInfo>(mPackages.size());
6558                for (PackageParser.Package p : mPackages.values()) {
6559                    final PackageInfo pi =
6560                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6561                    if (pi != null) {
6562                        list.add(pi);
6563                    }
6564                }
6565            }
6566
6567            return new ParceledListSlice<PackageInfo>(list);
6568        }
6569    }
6570
6571    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6572            String[] permissions, boolean[] tmp, int flags, int userId) {
6573        int numMatch = 0;
6574        final PermissionsState permissionsState = ps.getPermissionsState();
6575        for (int i=0; i<permissions.length; i++) {
6576            final String permission = permissions[i];
6577            if (permissionsState.hasPermission(permission, userId)) {
6578                tmp[i] = true;
6579                numMatch++;
6580            } else {
6581                tmp[i] = false;
6582            }
6583        }
6584        if (numMatch == 0) {
6585            return;
6586        }
6587        final PackageInfo pi;
6588        if (ps.pkg != null) {
6589            pi = generatePackageInfo(ps, flags, userId);
6590        } else {
6591            pi = generatePackageInfo(ps, flags, userId);
6592        }
6593        // The above might return null in cases of uninstalled apps or install-state
6594        // skew across users/profiles.
6595        if (pi != null) {
6596            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6597                if (numMatch == permissions.length) {
6598                    pi.requestedPermissions = permissions;
6599                } else {
6600                    pi.requestedPermissions = new String[numMatch];
6601                    numMatch = 0;
6602                    for (int i=0; i<permissions.length; i++) {
6603                        if (tmp[i]) {
6604                            pi.requestedPermissions[numMatch] = permissions[i];
6605                            numMatch++;
6606                        }
6607                    }
6608                }
6609            }
6610            list.add(pi);
6611        }
6612    }
6613
6614    @Override
6615    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6616            String[] permissions, int flags, int userId) {
6617        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6618        flags = updateFlagsForPackage(flags, userId, permissions);
6619        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6620                true /* requireFullPermission */, false /* checkShell */,
6621                "get packages holding permissions");
6622        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6623
6624        // writer
6625        synchronized (mPackages) {
6626            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6627            boolean[] tmpBools = new boolean[permissions.length];
6628            if (listUninstalled) {
6629                for (PackageSetting ps : mSettings.mPackages.values()) {
6630                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6631                            userId);
6632                }
6633            } else {
6634                for (PackageParser.Package pkg : mPackages.values()) {
6635                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6636                    if (ps != null) {
6637                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6638                                userId);
6639                    }
6640                }
6641            }
6642
6643            return new ParceledListSlice<PackageInfo>(list);
6644        }
6645    }
6646
6647    @Override
6648    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6649        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6650        flags = updateFlagsForApplication(flags, userId, null);
6651        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6652
6653        // writer
6654        synchronized (mPackages) {
6655            ArrayList<ApplicationInfo> list;
6656            if (listUninstalled) {
6657                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6658                for (PackageSetting ps : mSettings.mPackages.values()) {
6659                    ApplicationInfo ai;
6660                    int effectiveFlags = flags;
6661                    if (ps.isSystem()) {
6662                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6663                    }
6664                    if (ps.pkg != null) {
6665                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6666                                ps.readUserState(userId), userId);
6667                    } else {
6668                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6669                                userId);
6670                    }
6671                    if (ai != null) {
6672                        list.add(ai);
6673                    }
6674                }
6675            } else {
6676                list = new ArrayList<ApplicationInfo>(mPackages.size());
6677                for (PackageParser.Package p : mPackages.values()) {
6678                    if (p.mExtras != null) {
6679                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6680                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6681                        if (ai != null) {
6682                            list.add(ai);
6683                        }
6684                    }
6685                }
6686            }
6687
6688            return new ParceledListSlice<ApplicationInfo>(list);
6689        }
6690    }
6691
6692    @Override
6693    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6694        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6695            return null;
6696        }
6697
6698        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6699                "getEphemeralApplications");
6700        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6701                true /* requireFullPermission */, false /* checkShell */,
6702                "getEphemeralApplications");
6703        synchronized (mPackages) {
6704            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6705                    .getEphemeralApplicationsLPw(userId);
6706            if (ephemeralApps != null) {
6707                return new ParceledListSlice<>(ephemeralApps);
6708            }
6709        }
6710        return null;
6711    }
6712
6713    @Override
6714    public boolean isEphemeralApplication(String packageName, int userId) {
6715        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6716                true /* requireFullPermission */, false /* checkShell */,
6717                "isEphemeral");
6718        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6719            return false;
6720        }
6721
6722        if (!isCallerSameApp(packageName)) {
6723            return false;
6724        }
6725        synchronized (mPackages) {
6726            PackageParser.Package pkg = mPackages.get(packageName);
6727            if (pkg != null) {
6728                return pkg.applicationInfo.isEphemeralApp();
6729            }
6730        }
6731        return false;
6732    }
6733
6734    @Override
6735    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6736        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6737            return null;
6738        }
6739
6740        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6741                true /* requireFullPermission */, false /* checkShell */,
6742                "getCookie");
6743        if (!isCallerSameApp(packageName)) {
6744            return null;
6745        }
6746        synchronized (mPackages) {
6747            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6748                    packageName, userId);
6749        }
6750    }
6751
6752    @Override
6753    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6754        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6755            return true;
6756        }
6757
6758        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6759                true /* requireFullPermission */, true /* checkShell */,
6760                "setCookie");
6761        if (!isCallerSameApp(packageName)) {
6762            return false;
6763        }
6764        synchronized (mPackages) {
6765            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6766                    packageName, cookie, userId);
6767        }
6768    }
6769
6770    @Override
6771    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6772        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6773            return null;
6774        }
6775
6776        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6777                "getEphemeralApplicationIcon");
6778        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6779                true /* requireFullPermission */, false /* checkShell */,
6780                "getEphemeralApplicationIcon");
6781        synchronized (mPackages) {
6782            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6783                    packageName, userId);
6784        }
6785    }
6786
6787    private boolean isCallerSameApp(String packageName) {
6788        PackageParser.Package pkg = mPackages.get(packageName);
6789        return pkg != null
6790                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6791    }
6792
6793    @Override
6794    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6795        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6796    }
6797
6798    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6799        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6800
6801        // reader
6802        synchronized (mPackages) {
6803            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6804            final int userId = UserHandle.getCallingUserId();
6805            while (i.hasNext()) {
6806                final PackageParser.Package p = i.next();
6807                if (p.applicationInfo == null) continue;
6808
6809                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6810                        && !p.applicationInfo.isDirectBootAware();
6811                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6812                        && p.applicationInfo.isDirectBootAware();
6813
6814                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6815                        && (!mSafeMode || isSystemApp(p))
6816                        && (matchesUnaware || matchesAware)) {
6817                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6818                    if (ps != null) {
6819                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6820                                ps.readUserState(userId), userId);
6821                        if (ai != null) {
6822                            finalList.add(ai);
6823                        }
6824                    }
6825                }
6826            }
6827        }
6828
6829        return finalList;
6830    }
6831
6832    @Override
6833    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6834        if (!sUserManager.exists(userId)) return null;
6835        flags = updateFlagsForComponent(flags, userId, name);
6836        // reader
6837        synchronized (mPackages) {
6838            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6839            PackageSetting ps = provider != null
6840                    ? mSettings.mPackages.get(provider.owner.packageName)
6841                    : null;
6842            return ps != null
6843                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6844                    ? PackageParser.generateProviderInfo(provider, flags,
6845                            ps.readUserState(userId), userId)
6846                    : null;
6847        }
6848    }
6849
6850    /**
6851     * @deprecated
6852     */
6853    @Deprecated
6854    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6855        // reader
6856        synchronized (mPackages) {
6857            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6858                    .entrySet().iterator();
6859            final int userId = UserHandle.getCallingUserId();
6860            while (i.hasNext()) {
6861                Map.Entry<String, PackageParser.Provider> entry = i.next();
6862                PackageParser.Provider p = entry.getValue();
6863                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6864
6865                if (ps != null && p.syncable
6866                        && (!mSafeMode || (p.info.applicationInfo.flags
6867                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6868                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6869                            ps.readUserState(userId), userId);
6870                    if (info != null) {
6871                        outNames.add(entry.getKey());
6872                        outInfo.add(info);
6873                    }
6874                }
6875            }
6876        }
6877    }
6878
6879    @Override
6880    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6881            int uid, int flags) {
6882        final int userId = processName != null ? UserHandle.getUserId(uid)
6883                : UserHandle.getCallingUserId();
6884        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6885        flags = updateFlagsForComponent(flags, userId, processName);
6886
6887        ArrayList<ProviderInfo> finalList = null;
6888        // reader
6889        synchronized (mPackages) {
6890            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6891            while (i.hasNext()) {
6892                final PackageParser.Provider p = i.next();
6893                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6894                if (ps != null && p.info.authority != null
6895                        && (processName == null
6896                                || (p.info.processName.equals(processName)
6897                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6898                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6899                    if (finalList == null) {
6900                        finalList = new ArrayList<ProviderInfo>(3);
6901                    }
6902                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6903                            ps.readUserState(userId), userId);
6904                    if (info != null) {
6905                        finalList.add(info);
6906                    }
6907                }
6908            }
6909        }
6910
6911        if (finalList != null) {
6912            Collections.sort(finalList, mProviderInitOrderSorter);
6913            return new ParceledListSlice<ProviderInfo>(finalList);
6914        }
6915
6916        return ParceledListSlice.emptyList();
6917    }
6918
6919    @Override
6920    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6921        // reader
6922        synchronized (mPackages) {
6923            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6924            return PackageParser.generateInstrumentationInfo(i, flags);
6925        }
6926    }
6927
6928    @Override
6929    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6930            String targetPackage, int flags) {
6931        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6932    }
6933
6934    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6935            int flags) {
6936        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6937
6938        // reader
6939        synchronized (mPackages) {
6940            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6941            while (i.hasNext()) {
6942                final PackageParser.Instrumentation p = i.next();
6943                if (targetPackage == null
6944                        || targetPackage.equals(p.info.targetPackage)) {
6945                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6946                            flags);
6947                    if (ii != null) {
6948                        finalList.add(ii);
6949                    }
6950                }
6951            }
6952        }
6953
6954        return finalList;
6955    }
6956
6957    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6958        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6959        if (overlays == null) {
6960            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6961            return;
6962        }
6963        for (PackageParser.Package opkg : overlays.values()) {
6964            // Not much to do if idmap fails: we already logged the error
6965            // and we certainly don't want to abort installation of pkg simply
6966            // because an overlay didn't fit properly. For these reasons,
6967            // ignore the return value of createIdmapForPackagePairLI.
6968            createIdmapForPackagePairLI(pkg, opkg);
6969        }
6970    }
6971
6972    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6973            PackageParser.Package opkg) {
6974        if (!opkg.mTrustedOverlay) {
6975            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6976                    opkg.baseCodePath + ": overlay not trusted");
6977            return false;
6978        }
6979        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6980        if (overlaySet == null) {
6981            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6982                    opkg.baseCodePath + " but target package has no known overlays");
6983            return false;
6984        }
6985        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6986        // TODO: generate idmap for split APKs
6987        try {
6988            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6989        } catch (InstallerException e) {
6990            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6991                    + opkg.baseCodePath);
6992            return false;
6993        }
6994        PackageParser.Package[] overlayArray =
6995            overlaySet.values().toArray(new PackageParser.Package[0]);
6996        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6997            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6998                return p1.mOverlayPriority - p2.mOverlayPriority;
6999            }
7000        };
7001        Arrays.sort(overlayArray, cmp);
7002
7003        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7004        int i = 0;
7005        for (PackageParser.Package p : overlayArray) {
7006            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7007        }
7008        return true;
7009    }
7010
7011    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7012        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7013        try {
7014            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7015        } finally {
7016            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7017        }
7018    }
7019
7020    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7021        final File[] files = dir.listFiles();
7022        if (ArrayUtils.isEmpty(files)) {
7023            Log.d(TAG, "No files in app dir " + dir);
7024            return;
7025        }
7026
7027        if (DEBUG_PACKAGE_SCANNING) {
7028            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7029                    + " flags=0x" + Integer.toHexString(parseFlags));
7030        }
7031        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7032                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7033
7034        // Submit files for parsing in parallel
7035        int fileCount = 0;
7036        for (File file : files) {
7037            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7038                    && !PackageInstallerService.isStageName(file.getName());
7039            if (!isPackage) {
7040                // Ignore entries which are not packages
7041                continue;
7042            }
7043            parallelPackageParser.submit(file, parseFlags);
7044            fileCount++;
7045        }
7046
7047        // Process results one by one
7048        for (; fileCount > 0; fileCount--) {
7049            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7050            Throwable throwable = parseResult.throwable;
7051            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7052
7053            if (throwable == null) {
7054                try {
7055                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7056                            currentTime, null);
7057                } catch (PackageManagerException e) {
7058                    errorCode = e.error;
7059                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7060                }
7061            } else if (throwable instanceof PackageParser.PackageParserException) {
7062                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7063                        throwable;
7064                errorCode = e.error;
7065                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7066            } else {
7067                throw new IllegalStateException("Unexpected exception occurred while parsing "
7068                        + parseResult.scanFile, throwable);
7069            }
7070
7071            // Delete invalid userdata apps
7072            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7073                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7074                logCriticalInfo(Log.WARN,
7075                        "Deleting invalid package at " + parseResult.scanFile);
7076                removeCodePathLI(parseResult.scanFile);
7077            }
7078        }
7079        parallelPackageParser.close();
7080    }
7081
7082    private static File getSettingsProblemFile() {
7083        File dataDir = Environment.getDataDirectory();
7084        File systemDir = new File(dataDir, "system");
7085        File fname = new File(systemDir, "uiderrors.txt");
7086        return fname;
7087    }
7088
7089    static void reportSettingsProblem(int priority, String msg) {
7090        logCriticalInfo(priority, msg);
7091    }
7092
7093    static void logCriticalInfo(int priority, String msg) {
7094        Slog.println(priority, TAG, msg);
7095        EventLogTags.writePmCriticalInfo(msg);
7096        try {
7097            File fname = getSettingsProblemFile();
7098            FileOutputStream out = new FileOutputStream(fname, true);
7099            PrintWriter pw = new FastPrintWriter(out);
7100            SimpleDateFormat formatter = new SimpleDateFormat();
7101            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7102            pw.println(dateString + ": " + msg);
7103            pw.close();
7104            FileUtils.setPermissions(
7105                    fname.toString(),
7106                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7107                    -1, -1);
7108        } catch (java.io.IOException e) {
7109        }
7110    }
7111
7112    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7113        if (srcFile.isDirectory()) {
7114            final File baseFile = new File(pkg.baseCodePath);
7115            long maxModifiedTime = baseFile.lastModified();
7116            if (pkg.splitCodePaths != null) {
7117                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7118                    final File splitFile = new File(pkg.splitCodePaths[i]);
7119                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7120                }
7121            }
7122            return maxModifiedTime;
7123        }
7124        return srcFile.lastModified();
7125    }
7126
7127    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7128            final int policyFlags) throws PackageManagerException {
7129        // When upgrading from pre-N MR1, verify the package time stamp using the package
7130        // directory and not the APK file.
7131        final long lastModifiedTime = mIsPreNMR1Upgrade
7132                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7133        if (ps != null
7134                && ps.codePath.equals(srcFile)
7135                && ps.timeStamp == lastModifiedTime
7136                && !isCompatSignatureUpdateNeeded(pkg)
7137                && !isRecoverSignatureUpdateNeeded(pkg)) {
7138            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7139            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7140            ArraySet<PublicKey> signingKs;
7141            synchronized (mPackages) {
7142                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7143            }
7144            if (ps.signatures.mSignatures != null
7145                    && ps.signatures.mSignatures.length != 0
7146                    && signingKs != null) {
7147                // Optimization: reuse the existing cached certificates
7148                // if the package appears to be unchanged.
7149                pkg.mSignatures = ps.signatures.mSignatures;
7150                pkg.mSigningKeys = signingKs;
7151                return;
7152            }
7153
7154            Slog.w(TAG, "PackageSetting for " + ps.name
7155                    + " is missing signatures.  Collecting certs again to recover them.");
7156        } else {
7157            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7158        }
7159
7160        try {
7161            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7162            PackageParser.collectCertificates(pkg, policyFlags);
7163        } catch (PackageParserException e) {
7164            throw PackageManagerException.from(e);
7165        } finally {
7166            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7167        }
7168    }
7169
7170    /**
7171     *  Traces a package scan.
7172     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7173     */
7174    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7175            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7176        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7177        try {
7178            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7179        } finally {
7180            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7181        }
7182    }
7183
7184    /**
7185     *  Scans a package and returns the newly parsed package.
7186     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7187     */
7188    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7189            long currentTime, UserHandle user) throws PackageManagerException {
7190        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7191        PackageParser pp = new PackageParser();
7192        pp.setSeparateProcesses(mSeparateProcesses);
7193        pp.setOnlyCoreApps(mOnlyCore);
7194        pp.setDisplayMetrics(mMetrics);
7195
7196        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7197            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7198        }
7199
7200        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7201        final PackageParser.Package pkg;
7202        try {
7203            pkg = pp.parsePackage(scanFile, parseFlags);
7204        } catch (PackageParserException e) {
7205            throw PackageManagerException.from(e);
7206        } finally {
7207            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7208        }
7209
7210        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7211    }
7212
7213    /**
7214     *  Scans a package and returns the newly parsed package.
7215     *  @throws PackageManagerException on a parse error.
7216     */
7217    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7218            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7219            throws PackageManagerException {
7220        // If the package has children and this is the first dive in the function
7221        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7222        // packages (parent and children) would be successfully scanned before the
7223        // actual scan since scanning mutates internal state and we want to atomically
7224        // install the package and its children.
7225        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7226            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7227                scanFlags |= SCAN_CHECK_ONLY;
7228            }
7229        } else {
7230            scanFlags &= ~SCAN_CHECK_ONLY;
7231        }
7232
7233        // Scan the parent
7234        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7235                scanFlags, currentTime, user);
7236
7237        // Scan the children
7238        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7239        for (int i = 0; i < childCount; i++) {
7240            PackageParser.Package childPackage = pkg.childPackages.get(i);
7241            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7242                    currentTime, user);
7243        }
7244
7245
7246        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7247            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7248        }
7249
7250        return scannedPkg;
7251    }
7252
7253    /**
7254     *  Scans a package and returns the newly parsed package.
7255     *  @throws PackageManagerException on a parse error.
7256     */
7257    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7258            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7259            throws PackageManagerException {
7260        PackageSetting ps = null;
7261        PackageSetting updatedPkg;
7262        // reader
7263        synchronized (mPackages) {
7264            // Look to see if we already know about this package.
7265            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7266            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7267                // This package has been renamed to its original name.  Let's
7268                // use that.
7269                ps = mSettings.getPackageLPr(oldName);
7270            }
7271            // If there was no original package, see one for the real package name.
7272            if (ps == null) {
7273                ps = mSettings.getPackageLPr(pkg.packageName);
7274            }
7275            // Check to see if this package could be hiding/updating a system
7276            // package.  Must look for it either under the original or real
7277            // package name depending on our state.
7278            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7279            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7280
7281            // If this is a package we don't know about on the system partition, we
7282            // may need to remove disabled child packages on the system partition
7283            // or may need to not add child packages if the parent apk is updated
7284            // on the data partition and no longer defines this child package.
7285            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7286                // If this is a parent package for an updated system app and this system
7287                // app got an OTA update which no longer defines some of the child packages
7288                // we have to prune them from the disabled system packages.
7289                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7290                if (disabledPs != null) {
7291                    final int scannedChildCount = (pkg.childPackages != null)
7292                            ? pkg.childPackages.size() : 0;
7293                    final int disabledChildCount = disabledPs.childPackageNames != null
7294                            ? disabledPs.childPackageNames.size() : 0;
7295                    for (int i = 0; i < disabledChildCount; i++) {
7296                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7297                        boolean disabledPackageAvailable = false;
7298                        for (int j = 0; j < scannedChildCount; j++) {
7299                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7300                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7301                                disabledPackageAvailable = true;
7302                                break;
7303                            }
7304                         }
7305                         if (!disabledPackageAvailable) {
7306                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7307                         }
7308                    }
7309                }
7310            }
7311        }
7312
7313        boolean updatedPkgBetter = false;
7314        // First check if this is a system package that may involve an update
7315        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7316            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7317            // it needs to drop FLAG_PRIVILEGED.
7318            if (locationIsPrivileged(scanFile)) {
7319                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7320            } else {
7321                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7322            }
7323
7324            if (ps != null && !ps.codePath.equals(scanFile)) {
7325                // The path has changed from what was last scanned...  check the
7326                // version of the new path against what we have stored to determine
7327                // what to do.
7328                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7329                if (pkg.mVersionCode <= ps.versionCode) {
7330                    // The system package has been updated and the code path does not match
7331                    // Ignore entry. Skip it.
7332                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7333                            + " ignored: updated version " + ps.versionCode
7334                            + " better than this " + pkg.mVersionCode);
7335                    if (!updatedPkg.codePath.equals(scanFile)) {
7336                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7337                                + ps.name + " changing from " + updatedPkg.codePathString
7338                                + " to " + scanFile);
7339                        updatedPkg.codePath = scanFile;
7340                        updatedPkg.codePathString = scanFile.toString();
7341                        updatedPkg.resourcePath = scanFile;
7342                        updatedPkg.resourcePathString = scanFile.toString();
7343                    }
7344                    updatedPkg.pkg = pkg;
7345                    updatedPkg.versionCode = pkg.mVersionCode;
7346
7347                    // Update the disabled system child packages to point to the package too.
7348                    final int childCount = updatedPkg.childPackageNames != null
7349                            ? updatedPkg.childPackageNames.size() : 0;
7350                    for (int i = 0; i < childCount; i++) {
7351                        String childPackageName = updatedPkg.childPackageNames.get(i);
7352                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7353                                childPackageName);
7354                        if (updatedChildPkg != null) {
7355                            updatedChildPkg.pkg = pkg;
7356                            updatedChildPkg.versionCode = pkg.mVersionCode;
7357                        }
7358                    }
7359
7360                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7361                            + scanFile + " ignored: updated version " + ps.versionCode
7362                            + " better than this " + pkg.mVersionCode);
7363                } else {
7364                    // The current app on the system partition is better than
7365                    // what we have updated to on the data partition; switch
7366                    // back to the system partition version.
7367                    // At this point, its safely assumed that package installation for
7368                    // apps in system partition will go through. If not there won't be a working
7369                    // version of the app
7370                    // writer
7371                    synchronized (mPackages) {
7372                        // Just remove the loaded entries from package lists.
7373                        mPackages.remove(ps.name);
7374                    }
7375
7376                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7377                            + " reverting from " + ps.codePathString
7378                            + ": new version " + pkg.mVersionCode
7379                            + " better than installed " + ps.versionCode);
7380
7381                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7382                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7383                    synchronized (mInstallLock) {
7384                        args.cleanUpResourcesLI();
7385                    }
7386                    synchronized (mPackages) {
7387                        mSettings.enableSystemPackageLPw(ps.name);
7388                    }
7389                    updatedPkgBetter = true;
7390                }
7391            }
7392        }
7393
7394        if (updatedPkg != null) {
7395            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7396            // initially
7397            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7398
7399            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7400            // flag set initially
7401            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7402                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7403            }
7404        }
7405
7406        // Verify certificates against what was last scanned
7407        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7408
7409        /*
7410         * A new system app appeared, but we already had a non-system one of the
7411         * same name installed earlier.
7412         */
7413        boolean shouldHideSystemApp = false;
7414        if (updatedPkg == null && ps != null
7415                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7416            /*
7417             * Check to make sure the signatures match first. If they don't,
7418             * wipe the installed application and its data.
7419             */
7420            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7421                    != PackageManager.SIGNATURE_MATCH) {
7422                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7423                        + " signatures don't match existing userdata copy; removing");
7424                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7425                        "scanPackageInternalLI")) {
7426                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7427                }
7428                ps = null;
7429            } else {
7430                /*
7431                 * If the newly-added system app is an older version than the
7432                 * already installed version, hide it. It will be scanned later
7433                 * and re-added like an update.
7434                 */
7435                if (pkg.mVersionCode <= ps.versionCode) {
7436                    shouldHideSystemApp = true;
7437                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7438                            + " but new version " + pkg.mVersionCode + " better than installed "
7439                            + ps.versionCode + "; hiding system");
7440                } else {
7441                    /*
7442                     * The newly found system app is a newer version that the
7443                     * one previously installed. Simply remove the
7444                     * already-installed application and replace it with our own
7445                     * while keeping the application data.
7446                     */
7447                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7448                            + " reverting from " + ps.codePathString + ": new version "
7449                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7450                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7451                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7452                    synchronized (mInstallLock) {
7453                        args.cleanUpResourcesLI();
7454                    }
7455                }
7456            }
7457        }
7458
7459        // The apk is forward locked (not public) if its code and resources
7460        // are kept in different files. (except for app in either system or
7461        // vendor path).
7462        // TODO grab this value from PackageSettings
7463        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7464            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7465                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7466            }
7467        }
7468
7469        // TODO: extend to support forward-locked splits
7470        String resourcePath = null;
7471        String baseResourcePath = null;
7472        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7473            if (ps != null && ps.resourcePathString != null) {
7474                resourcePath = ps.resourcePathString;
7475                baseResourcePath = ps.resourcePathString;
7476            } else {
7477                // Should not happen at all. Just log an error.
7478                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7479            }
7480        } else {
7481            resourcePath = pkg.codePath;
7482            baseResourcePath = pkg.baseCodePath;
7483        }
7484
7485        // Set application objects path explicitly.
7486        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7487        pkg.setApplicationInfoCodePath(pkg.codePath);
7488        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7489        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7490        pkg.setApplicationInfoResourcePath(resourcePath);
7491        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7492        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7493
7494        // Note that we invoke the following method only if we are about to unpack an application
7495        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7496                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7497
7498        /*
7499         * If the system app should be overridden by a previously installed
7500         * data, hide the system app now and let the /data/app scan pick it up
7501         * again.
7502         */
7503        if (shouldHideSystemApp) {
7504            synchronized (mPackages) {
7505                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7506            }
7507        }
7508
7509        return scannedPkg;
7510    }
7511
7512    private static String fixProcessName(String defProcessName,
7513            String processName) {
7514        if (processName == null) {
7515            return defProcessName;
7516        }
7517        return processName;
7518    }
7519
7520    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7521            throws PackageManagerException {
7522        if (pkgSetting.signatures.mSignatures != null) {
7523            // Already existing package. Make sure signatures match
7524            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7525                    == PackageManager.SIGNATURE_MATCH;
7526            if (!match) {
7527                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7528                        == PackageManager.SIGNATURE_MATCH;
7529            }
7530            if (!match) {
7531                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7532                        == PackageManager.SIGNATURE_MATCH;
7533            }
7534            if (!match) {
7535                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7536                        + pkg.packageName + " signatures do not match the "
7537                        + "previously installed version; ignoring!");
7538            }
7539        }
7540
7541        // Check for shared user signatures
7542        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7543            // Already existing package. Make sure signatures match
7544            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7545                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7546            if (!match) {
7547                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7548                        == PackageManager.SIGNATURE_MATCH;
7549            }
7550            if (!match) {
7551                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7552                        == PackageManager.SIGNATURE_MATCH;
7553            }
7554            if (!match) {
7555                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7556                        "Package " + pkg.packageName
7557                        + " has no signatures that match those in shared user "
7558                        + pkgSetting.sharedUser.name + "; ignoring!");
7559            }
7560        }
7561    }
7562
7563    /**
7564     * Enforces that only the system UID or root's UID can call a method exposed
7565     * via Binder.
7566     *
7567     * @param message used as message if SecurityException is thrown
7568     * @throws SecurityException if the caller is not system or root
7569     */
7570    private static final void enforceSystemOrRoot(String message) {
7571        final int uid = Binder.getCallingUid();
7572        if (uid != Process.SYSTEM_UID && uid != 0) {
7573            throw new SecurityException(message);
7574        }
7575    }
7576
7577    @Override
7578    public void performFstrimIfNeeded() {
7579        enforceSystemOrRoot("Only the system can request fstrim");
7580
7581        // Before everything else, see whether we need to fstrim.
7582        try {
7583            IStorageManager sm = PackageHelper.getStorageManager();
7584            if (sm != null) {
7585                boolean doTrim = false;
7586                final long interval = android.provider.Settings.Global.getLong(
7587                        mContext.getContentResolver(),
7588                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7589                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7590                if (interval > 0) {
7591                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7592                    if (timeSinceLast > interval) {
7593                        doTrim = true;
7594                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7595                                + "; running immediately");
7596                    }
7597                }
7598                if (doTrim) {
7599                    final boolean dexOptDialogShown;
7600                    synchronized (mPackages) {
7601                        dexOptDialogShown = mDexOptDialogShown;
7602                    }
7603                    if (!isFirstBoot() && dexOptDialogShown) {
7604                        try {
7605                            ActivityManager.getService().showBootMessage(
7606                                    mContext.getResources().getString(
7607                                            R.string.android_upgrading_fstrim), true);
7608                        } catch (RemoteException e) {
7609                        }
7610                    }
7611                    sm.runMaintenance();
7612                }
7613            } else {
7614                Slog.e(TAG, "storageManager service unavailable!");
7615            }
7616        } catch (RemoteException e) {
7617            // Can't happen; StorageManagerService is local
7618        }
7619    }
7620
7621    @Override
7622    public void updatePackagesIfNeeded() {
7623        enforceSystemOrRoot("Only the system can request package update");
7624
7625        // We need to re-extract after an OTA.
7626        boolean causeUpgrade = isUpgrade();
7627
7628        // First boot or factory reset.
7629        // Note: we also handle devices that are upgrading to N right now as if it is their
7630        //       first boot, as they do not have profile data.
7631        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7632
7633        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7634        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7635
7636        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7637            return;
7638        }
7639
7640        List<PackageParser.Package> pkgs;
7641        synchronized (mPackages) {
7642            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7643        }
7644
7645        final long startTime = System.nanoTime();
7646        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7647                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7648
7649        final int elapsedTimeSeconds =
7650                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7651
7652        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7653        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7654        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7655        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7656        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7657    }
7658
7659    /**
7660     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7661     * containing statistics about the invocation. The array consists of three elements,
7662     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7663     * and {@code numberOfPackagesFailed}.
7664     */
7665    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7666            String compilerFilter) {
7667
7668        int numberOfPackagesVisited = 0;
7669        int numberOfPackagesOptimized = 0;
7670        int numberOfPackagesSkipped = 0;
7671        int numberOfPackagesFailed = 0;
7672        final int numberOfPackagesToDexopt = pkgs.size();
7673
7674        for (PackageParser.Package pkg : pkgs) {
7675            numberOfPackagesVisited++;
7676
7677            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7678                if (DEBUG_DEXOPT) {
7679                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7680                }
7681                numberOfPackagesSkipped++;
7682                continue;
7683            }
7684
7685            if (DEBUG_DEXOPT) {
7686                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7687                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7688            }
7689
7690            if (showDialog) {
7691                try {
7692                    ActivityManager.getService().showBootMessage(
7693                            mContext.getResources().getString(R.string.android_upgrading_apk,
7694                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7695                } catch (RemoteException e) {
7696                }
7697                synchronized (mPackages) {
7698                    mDexOptDialogShown = true;
7699                }
7700            }
7701
7702            // If the OTA updates a system app which was previously preopted to a non-preopted state
7703            // the app might end up being verified at runtime. That's because by default the apps
7704            // are verify-profile but for preopted apps there's no profile.
7705            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7706            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7707            // filter (by default interpret-only).
7708            // Note that at this stage unused apps are already filtered.
7709            if (isSystemApp(pkg) &&
7710                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7711                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7712                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7713            }
7714
7715            // checkProfiles is false to avoid merging profiles during boot which
7716            // might interfere with background compilation (b/28612421).
7717            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7718            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7719            // trade-off worth doing to save boot time work.
7720            int dexOptStatus = performDexOptTraced(pkg.packageName,
7721                    false /* checkProfiles */,
7722                    compilerFilter,
7723                    false /* force */);
7724            switch (dexOptStatus) {
7725                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7726                    numberOfPackagesOptimized++;
7727                    break;
7728                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7729                    numberOfPackagesSkipped++;
7730                    break;
7731                case PackageDexOptimizer.DEX_OPT_FAILED:
7732                    numberOfPackagesFailed++;
7733                    break;
7734                default:
7735                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7736                    break;
7737            }
7738        }
7739
7740        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7741                numberOfPackagesFailed };
7742    }
7743
7744    @Override
7745    public void notifyPackageUse(String packageName, int reason) {
7746        synchronized (mPackages) {
7747            PackageParser.Package p = mPackages.get(packageName);
7748            if (p == null) {
7749                return;
7750            }
7751            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7752        }
7753    }
7754
7755    @Override
7756    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7757        int userId = UserHandle.getCallingUserId();
7758        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
7759        if (ai == null) {
7760            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
7761                + loadingPackageName + ", user=" + userId);
7762            return;
7763        }
7764        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
7765    }
7766
7767    // TODO: this is not used nor needed. Delete it.
7768    @Override
7769    public boolean performDexOptIfNeeded(String packageName) {
7770        int dexOptStatus = performDexOptTraced(packageName,
7771                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7772        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7773    }
7774
7775    @Override
7776    public boolean performDexOpt(String packageName,
7777            boolean checkProfiles, int compileReason, boolean force) {
7778        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7779                getCompilerFilterForReason(compileReason), force);
7780        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7781    }
7782
7783    @Override
7784    public boolean performDexOptMode(String packageName,
7785            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7786        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7787                targetCompilerFilter, force);
7788        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7789    }
7790
7791    private int performDexOptTraced(String packageName,
7792                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7793        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7794        try {
7795            return performDexOptInternal(packageName, checkProfiles,
7796                    targetCompilerFilter, force);
7797        } finally {
7798            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7799        }
7800    }
7801
7802    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7803    // if the package can now be considered up to date for the given filter.
7804    private int performDexOptInternal(String packageName,
7805                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7806        PackageParser.Package p;
7807        synchronized (mPackages) {
7808            p = mPackages.get(packageName);
7809            if (p == null) {
7810                // Package could not be found. Report failure.
7811                return PackageDexOptimizer.DEX_OPT_FAILED;
7812            }
7813            mPackageUsage.maybeWriteAsync(mPackages);
7814            mCompilerStats.maybeWriteAsync();
7815        }
7816        long callingId = Binder.clearCallingIdentity();
7817        try {
7818            synchronized (mInstallLock) {
7819                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7820                        targetCompilerFilter, force);
7821            }
7822        } finally {
7823            Binder.restoreCallingIdentity(callingId);
7824        }
7825    }
7826
7827    public ArraySet<String> getOptimizablePackages() {
7828        ArraySet<String> pkgs = new ArraySet<String>();
7829        synchronized (mPackages) {
7830            for (PackageParser.Package p : mPackages.values()) {
7831                if (PackageDexOptimizer.canOptimizePackage(p)) {
7832                    pkgs.add(p.packageName);
7833                }
7834            }
7835        }
7836        return pkgs;
7837    }
7838
7839    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7840            boolean checkProfiles, String targetCompilerFilter,
7841            boolean force) {
7842        // Select the dex optimizer based on the force parameter.
7843        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7844        //       allocate an object here.
7845        PackageDexOptimizer pdo = force
7846                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7847                : mPackageDexOptimizer;
7848
7849        // Optimize all dependencies first. Note: we ignore the return value and march on
7850        // on errors.
7851        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7852        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7853        if (!deps.isEmpty()) {
7854            for (PackageParser.Package depPackage : deps) {
7855                // TODO: Analyze and investigate if we (should) profile libraries.
7856                // Currently this will do a full compilation of the library by default.
7857                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7858                        false /* checkProfiles */,
7859                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7860                        getOrCreateCompilerPackageStats(depPackage));
7861            }
7862        }
7863        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7864                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7865    }
7866
7867    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7868        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7869            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7870            Set<String> collectedNames = new HashSet<>();
7871            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7872
7873            retValue.remove(p);
7874
7875            return retValue;
7876        } else {
7877            return Collections.emptyList();
7878        }
7879    }
7880
7881    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7882            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7883        if (!collectedNames.contains(p.packageName)) {
7884            collectedNames.add(p.packageName);
7885            collected.add(p);
7886
7887            if (p.usesLibraries != null) {
7888                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7889            }
7890            if (p.usesOptionalLibraries != null) {
7891                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7892                        collectedNames);
7893            }
7894        }
7895    }
7896
7897    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7898            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7899        for (String libName : libs) {
7900            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7901            if (libPkg != null) {
7902                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7903            }
7904        }
7905    }
7906
7907    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7908        synchronized (mPackages) {
7909            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7910            if (lib != null && lib.apk != null) {
7911                return mPackages.get(lib.apk);
7912            }
7913        }
7914        return null;
7915    }
7916
7917    public void shutdown() {
7918        mPackageUsage.writeNow(mPackages);
7919        mCompilerStats.writeNow();
7920    }
7921
7922    @Override
7923    public void dumpProfiles(String packageName) {
7924        PackageParser.Package pkg;
7925        synchronized (mPackages) {
7926            pkg = mPackages.get(packageName);
7927            if (pkg == null) {
7928                throw new IllegalArgumentException("Unknown package: " + packageName);
7929            }
7930        }
7931        /* Only the shell, root, or the app user should be able to dump profiles. */
7932        int callingUid = Binder.getCallingUid();
7933        if (callingUid != Process.SHELL_UID &&
7934            callingUid != Process.ROOT_UID &&
7935            callingUid != pkg.applicationInfo.uid) {
7936            throw new SecurityException("dumpProfiles");
7937        }
7938
7939        synchronized (mInstallLock) {
7940            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7941            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7942            try {
7943                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7944                String codePaths = TextUtils.join(";", allCodePaths);
7945                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7946            } catch (InstallerException e) {
7947                Slog.w(TAG, "Failed to dump profiles", e);
7948            }
7949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7950        }
7951    }
7952
7953    @Override
7954    public void forceDexOpt(String packageName) {
7955        enforceSystemOrRoot("forceDexOpt");
7956
7957        PackageParser.Package pkg;
7958        synchronized (mPackages) {
7959            pkg = mPackages.get(packageName);
7960            if (pkg == null) {
7961                throw new IllegalArgumentException("Unknown package: " + packageName);
7962            }
7963        }
7964
7965        synchronized (mInstallLock) {
7966            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7967
7968            // Whoever is calling forceDexOpt wants a fully compiled package.
7969            // Don't use profiles since that may cause compilation to be skipped.
7970            final int res = performDexOptInternalWithDependenciesLI(pkg,
7971                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7972                    true /* force */);
7973
7974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7975            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7976                throw new IllegalStateException("Failed to dexopt: " + res);
7977            }
7978        }
7979    }
7980
7981    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7982        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7983            Slog.w(TAG, "Unable to update from " + oldPkg.name
7984                    + " to " + newPkg.packageName
7985                    + ": old package not in system partition");
7986            return false;
7987        } else if (mPackages.get(oldPkg.name) != null) {
7988            Slog.w(TAG, "Unable to update from " + oldPkg.name
7989                    + " to " + newPkg.packageName
7990                    + ": old package still exists");
7991            return false;
7992        }
7993        return true;
7994    }
7995
7996    void removeCodePathLI(File codePath) {
7997        if (codePath.isDirectory()) {
7998            try {
7999                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8000            } catch (InstallerException e) {
8001                Slog.w(TAG, "Failed to remove code path", e);
8002            }
8003        } else {
8004            codePath.delete();
8005        }
8006    }
8007
8008    private int[] resolveUserIds(int userId) {
8009        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8010    }
8011
8012    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8013        if (pkg == null) {
8014            Slog.wtf(TAG, "Package was null!", new Throwable());
8015            return;
8016        }
8017        clearAppDataLeafLIF(pkg, userId, flags);
8018        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8019        for (int i = 0; i < childCount; i++) {
8020            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8021        }
8022    }
8023
8024    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8025        final PackageSetting ps;
8026        synchronized (mPackages) {
8027            ps = mSettings.mPackages.get(pkg.packageName);
8028        }
8029        for (int realUserId : resolveUserIds(userId)) {
8030            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8031            try {
8032                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8033                        ceDataInode);
8034            } catch (InstallerException e) {
8035                Slog.w(TAG, String.valueOf(e));
8036            }
8037        }
8038    }
8039
8040    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8041        if (pkg == null) {
8042            Slog.wtf(TAG, "Package was null!", new Throwable());
8043            return;
8044        }
8045        destroyAppDataLeafLIF(pkg, userId, flags);
8046        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8047        for (int i = 0; i < childCount; i++) {
8048            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8049        }
8050    }
8051
8052    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8053        final PackageSetting ps;
8054        synchronized (mPackages) {
8055            ps = mSettings.mPackages.get(pkg.packageName);
8056        }
8057        for (int realUserId : resolveUserIds(userId)) {
8058            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8059            try {
8060                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8061                        ceDataInode);
8062            } catch (InstallerException e) {
8063                Slog.w(TAG, String.valueOf(e));
8064            }
8065        }
8066    }
8067
8068    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8069        if (pkg == null) {
8070            Slog.wtf(TAG, "Package was null!", new Throwable());
8071            return;
8072        }
8073        destroyAppProfilesLeafLIF(pkg);
8074        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8075        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8076        for (int i = 0; i < childCount; i++) {
8077            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8078            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8079                    true /* removeBaseMarker */);
8080        }
8081    }
8082
8083    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8084            boolean removeBaseMarker) {
8085        if (pkg.isForwardLocked()) {
8086            return;
8087        }
8088
8089        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8090            try {
8091                path = PackageManagerServiceUtils.realpath(new File(path));
8092            } catch (IOException e) {
8093                // TODO: Should we return early here ?
8094                Slog.w(TAG, "Failed to get canonical path", e);
8095                continue;
8096            }
8097
8098            final String useMarker = path.replace('/', '@');
8099            for (int realUserId : resolveUserIds(userId)) {
8100                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8101                if (removeBaseMarker) {
8102                    File foreignUseMark = new File(profileDir, useMarker);
8103                    if (foreignUseMark.exists()) {
8104                        if (!foreignUseMark.delete()) {
8105                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8106                                    + pkg.packageName);
8107                        }
8108                    }
8109                }
8110
8111                File[] markers = profileDir.listFiles();
8112                if (markers != null) {
8113                    final String searchString = "@" + pkg.packageName + "@";
8114                    // We also delete all markers that contain the package name we're
8115                    // uninstalling. These are associated with secondary dex-files belonging
8116                    // to the package. Reconstructing the path of these dex files is messy
8117                    // in general.
8118                    for (File marker : markers) {
8119                        if (marker.getName().indexOf(searchString) > 0) {
8120                            if (!marker.delete()) {
8121                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8122                                    + pkg.packageName);
8123                            }
8124                        }
8125                    }
8126                }
8127            }
8128        }
8129    }
8130
8131    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8132        try {
8133            mInstaller.destroyAppProfiles(pkg.packageName);
8134        } catch (InstallerException e) {
8135            Slog.w(TAG, String.valueOf(e));
8136        }
8137    }
8138
8139    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8140        if (pkg == null) {
8141            Slog.wtf(TAG, "Package was null!", new Throwable());
8142            return;
8143        }
8144        clearAppProfilesLeafLIF(pkg);
8145        // We don't remove the base foreign use marker when clearing profiles because
8146        // we will rename it when the app is updated. Unlike the actual profile contents,
8147        // the foreign use marker is good across installs.
8148        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8149        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8150        for (int i = 0; i < childCount; i++) {
8151            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8152        }
8153    }
8154
8155    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8156        try {
8157            mInstaller.clearAppProfiles(pkg.packageName);
8158        } catch (InstallerException e) {
8159            Slog.w(TAG, String.valueOf(e));
8160        }
8161    }
8162
8163    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8164            long lastUpdateTime) {
8165        // Set parent install/update time
8166        PackageSetting ps = (PackageSetting) pkg.mExtras;
8167        if (ps != null) {
8168            ps.firstInstallTime = firstInstallTime;
8169            ps.lastUpdateTime = lastUpdateTime;
8170        }
8171        // Set children install/update time
8172        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8173        for (int i = 0; i < childCount; i++) {
8174            PackageParser.Package childPkg = pkg.childPackages.get(i);
8175            ps = (PackageSetting) childPkg.mExtras;
8176            if (ps != null) {
8177                ps.firstInstallTime = firstInstallTime;
8178                ps.lastUpdateTime = lastUpdateTime;
8179            }
8180        }
8181    }
8182
8183    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8184            PackageParser.Package changingLib) {
8185        if (file.path != null) {
8186            usesLibraryFiles.add(file.path);
8187            return;
8188        }
8189        PackageParser.Package p = mPackages.get(file.apk);
8190        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8191            // If we are doing this while in the middle of updating a library apk,
8192            // then we need to make sure to use that new apk for determining the
8193            // dependencies here.  (We haven't yet finished committing the new apk
8194            // to the package manager state.)
8195            if (p == null || p.packageName.equals(changingLib.packageName)) {
8196                p = changingLib;
8197            }
8198        }
8199        if (p != null) {
8200            usesLibraryFiles.addAll(p.getAllCodePaths());
8201        }
8202    }
8203
8204    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8205            PackageParser.Package changingLib) throws PackageManagerException {
8206        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8207            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8208            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8209            for (int i=0; i<N; i++) {
8210                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8211                if (file == null) {
8212                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8213                            "Package " + pkg.packageName + " requires unavailable shared library "
8214                            + pkg.usesLibraries.get(i) + "; failing!");
8215                }
8216                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8217            }
8218            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8219            for (int i=0; i<N; i++) {
8220                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8221                if (file == null) {
8222                    Slog.w(TAG, "Package " + pkg.packageName
8223                            + " desires unavailable shared library "
8224                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8225                } else {
8226                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8227                }
8228            }
8229            N = usesLibraryFiles.size();
8230            if (N > 0) {
8231                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8232            } else {
8233                pkg.usesLibraryFiles = null;
8234            }
8235        }
8236    }
8237
8238    private static boolean hasString(List<String> list, List<String> which) {
8239        if (list == null) {
8240            return false;
8241        }
8242        for (int i=list.size()-1; i>=0; i--) {
8243            for (int j=which.size()-1; j>=0; j--) {
8244                if (which.get(j).equals(list.get(i))) {
8245                    return true;
8246                }
8247            }
8248        }
8249        return false;
8250    }
8251
8252    private void updateAllSharedLibrariesLPw() {
8253        for (PackageParser.Package pkg : mPackages.values()) {
8254            try {
8255                updateSharedLibrariesLPr(pkg, null);
8256            } catch (PackageManagerException e) {
8257                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8258            }
8259        }
8260    }
8261
8262    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8263            PackageParser.Package changingPkg) {
8264        ArrayList<PackageParser.Package> res = null;
8265        for (PackageParser.Package pkg : mPackages.values()) {
8266            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8267                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8268                if (res == null) {
8269                    res = new ArrayList<PackageParser.Package>();
8270                }
8271                res.add(pkg);
8272                try {
8273                    updateSharedLibrariesLPr(pkg, changingPkg);
8274                } catch (PackageManagerException e) {
8275                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8276                }
8277            }
8278        }
8279        return res;
8280    }
8281
8282    /**
8283     * Derive the value of the {@code cpuAbiOverride} based on the provided
8284     * value and an optional stored value from the package settings.
8285     */
8286    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8287        String cpuAbiOverride = null;
8288
8289        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8290            cpuAbiOverride = null;
8291        } else if (abiOverride != null) {
8292            cpuAbiOverride = abiOverride;
8293        } else if (settings != null) {
8294            cpuAbiOverride = settings.cpuAbiOverrideString;
8295        }
8296
8297        return cpuAbiOverride;
8298    }
8299
8300    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8301            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8302                    throws PackageManagerException {
8303        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8304        // If the package has children and this is the first dive in the function
8305        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8306        // whether all packages (parent and children) would be successfully scanned
8307        // before the actual scan since scanning mutates internal state and we want
8308        // to atomically install the package and its children.
8309        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8310            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8311                scanFlags |= SCAN_CHECK_ONLY;
8312            }
8313        } else {
8314            scanFlags &= ~SCAN_CHECK_ONLY;
8315        }
8316
8317        final PackageParser.Package scannedPkg;
8318        try {
8319            // Scan the parent
8320            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8321            // Scan the children
8322            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8323            for (int i = 0; i < childCount; i++) {
8324                PackageParser.Package childPkg = pkg.childPackages.get(i);
8325                scanPackageLI(childPkg, policyFlags,
8326                        scanFlags, currentTime, user);
8327            }
8328        } finally {
8329            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8330        }
8331
8332        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8333            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8334        }
8335
8336        return scannedPkg;
8337    }
8338
8339    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8340            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8341        boolean success = false;
8342        try {
8343            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8344                    currentTime, user);
8345            success = true;
8346            return res;
8347        } finally {
8348            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8349                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8350                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8351                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8352                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8353            }
8354        }
8355    }
8356
8357    /**
8358     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8359     */
8360    private static boolean apkHasCode(String fileName) {
8361        StrictJarFile jarFile = null;
8362        try {
8363            jarFile = new StrictJarFile(fileName,
8364                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8365            return jarFile.findEntry("classes.dex") != null;
8366        } catch (IOException ignore) {
8367        } finally {
8368            try {
8369                if (jarFile != null) {
8370                    jarFile.close();
8371                }
8372            } catch (IOException ignore) {}
8373        }
8374        return false;
8375    }
8376
8377    /**
8378     * Enforces code policy for the package. This ensures that if an APK has
8379     * declared hasCode="true" in its manifest that the APK actually contains
8380     * code.
8381     *
8382     * @throws PackageManagerException If bytecode could not be found when it should exist
8383     */
8384    private static void assertCodePolicy(PackageParser.Package pkg)
8385            throws PackageManagerException {
8386        final boolean shouldHaveCode =
8387                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8388        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8389            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8390                    "Package " + pkg.baseCodePath + " code is missing");
8391        }
8392
8393        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8394            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8395                final boolean splitShouldHaveCode =
8396                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8397                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8398                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8399                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8400                }
8401            }
8402        }
8403    }
8404
8405    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8406            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8407                    throws PackageManagerException {
8408        if (DEBUG_PACKAGE_SCANNING) {
8409            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8410                Log.d(TAG, "Scanning package " + pkg.packageName);
8411        }
8412
8413        applyPolicy(pkg, policyFlags);
8414
8415        assertPackageIsValid(pkg, policyFlags, scanFlags);
8416
8417        // Initialize package source and resource directories
8418        final File scanFile = new File(pkg.codePath);
8419        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8420        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8421
8422        SharedUserSetting suid = null;
8423        PackageSetting pkgSetting = null;
8424
8425        // Getting the package setting may have a side-effect, so if we
8426        // are only checking if scan would succeed, stash a copy of the
8427        // old setting to restore at the end.
8428        PackageSetting nonMutatedPs = null;
8429
8430        // We keep references to the derived CPU Abis from settings in oder to reuse
8431        // them in the case where we're not upgrading or booting for the first time.
8432        String primaryCpuAbiFromSettings = null;
8433        String secondaryCpuAbiFromSettings = null;
8434
8435        // writer
8436        synchronized (mPackages) {
8437            if (pkg.mSharedUserId != null) {
8438                // SIDE EFFECTS; may potentially allocate a new shared user
8439                suid = mSettings.getSharedUserLPw(
8440                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8441                if (DEBUG_PACKAGE_SCANNING) {
8442                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8443                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8444                                + "): packages=" + suid.packages);
8445                }
8446            }
8447
8448            // Check if we are renaming from an original package name.
8449            PackageSetting origPackage = null;
8450            String realName = null;
8451            if (pkg.mOriginalPackages != null) {
8452                // This package may need to be renamed to a previously
8453                // installed name.  Let's check on that...
8454                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8455                if (pkg.mOriginalPackages.contains(renamed)) {
8456                    // This package had originally been installed as the
8457                    // original name, and we have already taken care of
8458                    // transitioning to the new one.  Just update the new
8459                    // one to continue using the old name.
8460                    realName = pkg.mRealPackage;
8461                    if (!pkg.packageName.equals(renamed)) {
8462                        // Callers into this function may have already taken
8463                        // care of renaming the package; only do it here if
8464                        // it is not already done.
8465                        pkg.setPackageName(renamed);
8466                    }
8467                } else {
8468                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8469                        if ((origPackage = mSettings.getPackageLPr(
8470                                pkg.mOriginalPackages.get(i))) != null) {
8471                            // We do have the package already installed under its
8472                            // original name...  should we use it?
8473                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8474                                // New package is not compatible with original.
8475                                origPackage = null;
8476                                continue;
8477                            } else if (origPackage.sharedUser != null) {
8478                                // Make sure uid is compatible between packages.
8479                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8480                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8481                                            + " to " + pkg.packageName + ": old uid "
8482                                            + origPackage.sharedUser.name
8483                                            + " differs from " + pkg.mSharedUserId);
8484                                    origPackage = null;
8485                                    continue;
8486                                }
8487                                // TODO: Add case when shared user id is added [b/28144775]
8488                            } else {
8489                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8490                                        + pkg.packageName + " to old name " + origPackage.name);
8491                            }
8492                            break;
8493                        }
8494                    }
8495                }
8496            }
8497
8498            if (mTransferedPackages.contains(pkg.packageName)) {
8499                Slog.w(TAG, "Package " + pkg.packageName
8500                        + " was transferred to another, but its .apk remains");
8501            }
8502
8503            // See comments in nonMutatedPs declaration
8504            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8505                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8506                if (foundPs != null) {
8507                    nonMutatedPs = new PackageSetting(foundPs);
8508                }
8509            }
8510
8511            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8512                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8513                if (foundPs != null) {
8514                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8515                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8516                }
8517            }
8518
8519            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8520            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8521                PackageManagerService.reportSettingsProblem(Log.WARN,
8522                        "Package " + pkg.packageName + " shared user changed from "
8523                                + (pkgSetting.sharedUser != null
8524                                        ? pkgSetting.sharedUser.name : "<nothing>")
8525                                + " to "
8526                                + (suid != null ? suid.name : "<nothing>")
8527                                + "; replacing with new");
8528                pkgSetting = null;
8529            }
8530            final PackageSetting oldPkgSetting =
8531                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8532            final PackageSetting disabledPkgSetting =
8533                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8534            if (pkgSetting == null) {
8535                final String parentPackageName = (pkg.parentPackage != null)
8536                        ? pkg.parentPackage.packageName : null;
8537                // REMOVE SharedUserSetting from method; update in a separate call
8538                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8539                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8540                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8541                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8542                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8543                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8544                        UserManagerService.getInstance());
8545                // SIDE EFFECTS; updates system state; move elsewhere
8546                if (origPackage != null) {
8547                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8548                }
8549                mSettings.addUserToSettingLPw(pkgSetting);
8550            } else {
8551                // REMOVE SharedUserSetting from method; update in a separate call.
8552                //
8553                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8554                // secondaryCpuAbi are not known at this point so we always update them
8555                // to null here, only to reset them at a later point.
8556                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8557                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8558                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8559                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8560                        UserManagerService.getInstance());
8561            }
8562            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8563            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8564
8565            // SIDE EFFECTS; modifies system state; move elsewhere
8566            if (pkgSetting.origPackage != null) {
8567                // If we are first transitioning from an original package,
8568                // fix up the new package's name now.  We need to do this after
8569                // looking up the package under its new name, so getPackageLP
8570                // can take care of fiddling things correctly.
8571                pkg.setPackageName(origPackage.name);
8572
8573                // File a report about this.
8574                String msg = "New package " + pkgSetting.realName
8575                        + " renamed to replace old package " + pkgSetting.name;
8576                reportSettingsProblem(Log.WARN, msg);
8577
8578                // Make a note of it.
8579                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8580                    mTransferedPackages.add(origPackage.name);
8581                }
8582
8583                // No longer need to retain this.
8584                pkgSetting.origPackage = null;
8585            }
8586
8587            // SIDE EFFECTS; modifies system state; move elsewhere
8588            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8589                // Make a note of it.
8590                mTransferedPackages.add(pkg.packageName);
8591            }
8592
8593            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8594                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8595            }
8596
8597            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8598                // Check all shared libraries and map to their actual file path.
8599                // We only do this here for apps not on a system dir, because those
8600                // are the only ones that can fail an install due to this.  We
8601                // will take care of the system apps by updating all of their
8602                // library paths after the scan is done.
8603                updateSharedLibrariesLPr(pkg, null);
8604            }
8605
8606            if (mFoundPolicyFile) {
8607                SELinuxMMAC.assignSeinfoValue(pkg);
8608            }
8609
8610            pkg.applicationInfo.uid = pkgSetting.appId;
8611            pkg.mExtras = pkgSetting;
8612            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8613                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8614                    // We just determined the app is signed correctly, so bring
8615                    // over the latest parsed certs.
8616                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8617                } else {
8618                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8619                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8620                                "Package " + pkg.packageName + " upgrade keys do not match the "
8621                                + "previously installed version");
8622                    } else {
8623                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8624                        String msg = "System package " + pkg.packageName
8625                                + " signature changed; retaining data.";
8626                        reportSettingsProblem(Log.WARN, msg);
8627                    }
8628                }
8629            } else {
8630                try {
8631                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8632                    verifySignaturesLP(pkgSetting, pkg);
8633                    // We just determined the app is signed correctly, so bring
8634                    // over the latest parsed certs.
8635                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8636                } catch (PackageManagerException e) {
8637                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8638                        throw e;
8639                    }
8640                    // The signature has changed, but this package is in the system
8641                    // image...  let's recover!
8642                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8643                    // However...  if this package is part of a shared user, but it
8644                    // doesn't match the signature of the shared user, let's fail.
8645                    // What this means is that you can't change the signatures
8646                    // associated with an overall shared user, which doesn't seem all
8647                    // that unreasonable.
8648                    if (pkgSetting.sharedUser != null) {
8649                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8650                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8651                            throw new PackageManagerException(
8652                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8653                                    "Signature mismatch for shared user: "
8654                                            + pkgSetting.sharedUser);
8655                        }
8656                    }
8657                    // File a report about this.
8658                    String msg = "System package " + pkg.packageName
8659                            + " signature changed; retaining data.";
8660                    reportSettingsProblem(Log.WARN, msg);
8661                }
8662            }
8663
8664            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8665                // This package wants to adopt ownership of permissions from
8666                // another package.
8667                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8668                    final String origName = pkg.mAdoptPermissions.get(i);
8669                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8670                    if (orig != null) {
8671                        if (verifyPackageUpdateLPr(orig, pkg)) {
8672                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8673                                    + pkg.packageName);
8674                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8675                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8676                        }
8677                    }
8678                }
8679            }
8680        }
8681
8682        pkg.applicationInfo.processName = fixProcessName(
8683                pkg.applicationInfo.packageName,
8684                pkg.applicationInfo.processName);
8685
8686        if (pkg != mPlatformPackage) {
8687            // Get all of our default paths setup
8688            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8689        }
8690
8691        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8692
8693        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8694            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8695                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8696                derivePackageAbi(
8697                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8698                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8699
8700                // Some system apps still use directory structure for native libraries
8701                // in which case we might end up not detecting abi solely based on apk
8702                // structure. Try to detect abi based on directory structure.
8703                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8704                        pkg.applicationInfo.primaryCpuAbi == null) {
8705                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8706                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8707                }
8708            } else {
8709                // This is not a first boot or an upgrade, don't bother deriving the
8710                // ABI during the scan. Instead, trust the value that was stored in the
8711                // package setting.
8712                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8713                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8714
8715                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8716
8717                if (DEBUG_ABI_SELECTION) {
8718                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8719                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8720                        pkg.applicationInfo.secondaryCpuAbi);
8721                }
8722            }
8723        } else {
8724            if ((scanFlags & SCAN_MOVE) != 0) {
8725                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8726                // but we already have this packages package info in the PackageSetting. We just
8727                // use that and derive the native library path based on the new codepath.
8728                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8729                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8730            }
8731
8732            // Set native library paths again. For moves, the path will be updated based on the
8733            // ABIs we've determined above. For non-moves, the path will be updated based on the
8734            // ABIs we determined during compilation, but the path will depend on the final
8735            // package path (after the rename away from the stage path).
8736            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8737        }
8738
8739        // This is a special case for the "system" package, where the ABI is
8740        // dictated by the zygote configuration (and init.rc). We should keep track
8741        // of this ABI so that we can deal with "normal" applications that run under
8742        // the same UID correctly.
8743        if (mPlatformPackage == pkg) {
8744            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8745                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8746        }
8747
8748        // If there's a mismatch between the abi-override in the package setting
8749        // and the abiOverride specified for the install. Warn about this because we
8750        // would've already compiled the app without taking the package setting into
8751        // account.
8752        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8753            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8754                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8755                        " for package " + pkg.packageName);
8756            }
8757        }
8758
8759        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8760        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8761        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8762
8763        // Copy the derived override back to the parsed package, so that we can
8764        // update the package settings accordingly.
8765        pkg.cpuAbiOverride = cpuAbiOverride;
8766
8767        if (DEBUG_ABI_SELECTION) {
8768            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8769                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8770                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8771        }
8772
8773        // Push the derived path down into PackageSettings so we know what to
8774        // clean up at uninstall time.
8775        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8776
8777        if (DEBUG_ABI_SELECTION) {
8778            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8779                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8780                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8781        }
8782
8783        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8784        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8785            // We don't do this here during boot because we can do it all
8786            // at once after scanning all existing packages.
8787            //
8788            // We also do this *before* we perform dexopt on this package, so that
8789            // we can avoid redundant dexopts, and also to make sure we've got the
8790            // code and package path correct.
8791            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8792        }
8793
8794        if (mFactoryTest && pkg.requestedPermissions.contains(
8795                android.Manifest.permission.FACTORY_TEST)) {
8796            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8797        }
8798
8799        if (isSystemApp(pkg)) {
8800            pkgSetting.isOrphaned = true;
8801        }
8802
8803        // Take care of first install / last update times.
8804        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8805        if (currentTime != 0) {
8806            if (pkgSetting.firstInstallTime == 0) {
8807                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8808            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8809                pkgSetting.lastUpdateTime = currentTime;
8810            }
8811        } else if (pkgSetting.firstInstallTime == 0) {
8812            // We need *something*.  Take time time stamp of the file.
8813            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8814        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8815            if (scanFileTime != pkgSetting.timeStamp) {
8816                // A package on the system image has changed; consider this
8817                // to be an update.
8818                pkgSetting.lastUpdateTime = scanFileTime;
8819            }
8820        }
8821        pkgSetting.setTimeStamp(scanFileTime);
8822
8823        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8824            if (nonMutatedPs != null) {
8825                synchronized (mPackages) {
8826                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8827                }
8828            }
8829        } else {
8830            // Modify state for the given package setting
8831            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8832                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8833        }
8834        return pkg;
8835    }
8836
8837    /**
8838     * Applies policy to the parsed package based upon the given policy flags.
8839     * Ensures the package is in a good state.
8840     * <p>
8841     * Implementation detail: This method must NOT have any side effect. It would
8842     * ideally be static, but, it requires locks to read system state.
8843     */
8844    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8845        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8846            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8847            if (pkg.applicationInfo.isDirectBootAware()) {
8848                // we're direct boot aware; set for all components
8849                for (PackageParser.Service s : pkg.services) {
8850                    s.info.encryptionAware = s.info.directBootAware = true;
8851                }
8852                for (PackageParser.Provider p : pkg.providers) {
8853                    p.info.encryptionAware = p.info.directBootAware = true;
8854                }
8855                for (PackageParser.Activity a : pkg.activities) {
8856                    a.info.encryptionAware = a.info.directBootAware = true;
8857                }
8858                for (PackageParser.Activity r : pkg.receivers) {
8859                    r.info.encryptionAware = r.info.directBootAware = true;
8860                }
8861            }
8862        } else {
8863            // Only allow system apps to be flagged as core apps.
8864            pkg.coreApp = false;
8865            // clear flags not applicable to regular apps
8866            pkg.applicationInfo.privateFlags &=
8867                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8868            pkg.applicationInfo.privateFlags &=
8869                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8870        }
8871        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8872
8873        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8874            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8875        }
8876
8877        if (!isSystemApp(pkg)) {
8878            // Only system apps can use these features.
8879            pkg.mOriginalPackages = null;
8880            pkg.mRealPackage = null;
8881            pkg.mAdoptPermissions = null;
8882        }
8883    }
8884
8885    /**
8886     * Asserts the parsed package is valid according to teh given policy. If the
8887     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8888     * <p>
8889     * Implementation detail: This method must NOT have any side effects. It would
8890     * ideally be static, but, it requires locks to read system state.
8891     *
8892     * @throws PackageManagerException If the package fails any of the validation checks
8893     */
8894    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8895            throws PackageManagerException {
8896        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8897            assertCodePolicy(pkg);
8898        }
8899
8900        if (pkg.applicationInfo.getCodePath() == null ||
8901                pkg.applicationInfo.getResourcePath() == null) {
8902            // Bail out. The resource and code paths haven't been set.
8903            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8904                    "Code and resource paths haven't been set correctly");
8905        }
8906
8907        // Make sure we're not adding any bogus keyset info
8908        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8909        ksms.assertScannedPackageValid(pkg);
8910
8911        synchronized (mPackages) {
8912            // The special "android" package can only be defined once
8913            if (pkg.packageName.equals("android")) {
8914                if (mAndroidApplication != null) {
8915                    Slog.w(TAG, "*************************************************");
8916                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8917                    Slog.w(TAG, " codePath=" + pkg.codePath);
8918                    Slog.w(TAG, "*************************************************");
8919                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8920                            "Core android package being redefined.  Skipping.");
8921                }
8922            }
8923
8924            // A package name must be unique; don't allow duplicates
8925            if (mPackages.containsKey(pkg.packageName)
8926                    || mSharedLibraries.containsKey(pkg.packageName)) {
8927                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8928                        "Application package " + pkg.packageName
8929                        + " already installed.  Skipping duplicate.");
8930            }
8931
8932            // Only privileged apps and updated privileged apps can add child packages.
8933            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8934                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8935                    throw new PackageManagerException("Only privileged apps can add child "
8936                            + "packages. Ignoring package " + pkg.packageName);
8937                }
8938                final int childCount = pkg.childPackages.size();
8939                for (int i = 0; i < childCount; i++) {
8940                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8941                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8942                            childPkg.packageName)) {
8943                        throw new PackageManagerException("Can't override child of "
8944                                + "another disabled app. Ignoring package " + pkg.packageName);
8945                    }
8946                }
8947            }
8948
8949            // If we're only installing presumed-existing packages, require that the
8950            // scanned APK is both already known and at the path previously established
8951            // for it.  Previously unknown packages we pick up normally, but if we have an
8952            // a priori expectation about this package's install presence, enforce it.
8953            // With a singular exception for new system packages. When an OTA contains
8954            // a new system package, we allow the codepath to change from a system location
8955            // to the user-installed location. If we don't allow this change, any newer,
8956            // user-installed version of the application will be ignored.
8957            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8958                if (mExpectingBetter.containsKey(pkg.packageName)) {
8959                    logCriticalInfo(Log.WARN,
8960                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8961                } else {
8962                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8963                    if (known != null) {
8964                        if (DEBUG_PACKAGE_SCANNING) {
8965                            Log.d(TAG, "Examining " + pkg.codePath
8966                                    + " and requiring known paths " + known.codePathString
8967                                    + " & " + known.resourcePathString);
8968                        }
8969                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8970                                || !pkg.applicationInfo.getResourcePath().equals(
8971                                        known.resourcePathString)) {
8972                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8973                                    "Application package " + pkg.packageName
8974                                    + " found at " + pkg.applicationInfo.getCodePath()
8975                                    + " but expected at " + known.codePathString
8976                                    + "; ignoring.");
8977                        }
8978                    }
8979                }
8980            }
8981
8982            // Verify that this new package doesn't have any content providers
8983            // that conflict with existing packages.  Only do this if the
8984            // package isn't already installed, since we don't want to break
8985            // things that are installed.
8986            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8987                final int N = pkg.providers.size();
8988                int i;
8989                for (i=0; i<N; i++) {
8990                    PackageParser.Provider p = pkg.providers.get(i);
8991                    if (p.info.authority != null) {
8992                        String names[] = p.info.authority.split(";");
8993                        for (int j = 0; j < names.length; j++) {
8994                            if (mProvidersByAuthority.containsKey(names[j])) {
8995                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8996                                final String otherPackageName =
8997                                        ((other != null && other.getComponentName() != null) ?
8998                                                other.getComponentName().getPackageName() : "?");
8999                                throw new PackageManagerException(
9000                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9001                                        "Can't install because provider name " + names[j]
9002                                                + " (in package " + pkg.applicationInfo.packageName
9003                                                + ") is already used by " + otherPackageName);
9004                            }
9005                        }
9006                    }
9007                }
9008            }
9009        }
9010    }
9011
9012    /**
9013     * Adds a scanned package to the system. When this method is finished, the package will
9014     * be available for query, resolution, etc...
9015     */
9016    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9017            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9018        final String pkgName = pkg.packageName;
9019        if (mCustomResolverComponentName != null &&
9020                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9021            setUpCustomResolverActivity(pkg);
9022        }
9023
9024        if (pkg.packageName.equals("android")) {
9025            synchronized (mPackages) {
9026                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9027                    // Set up information for our fall-back user intent resolution activity.
9028                    mPlatformPackage = pkg;
9029                    pkg.mVersionCode = mSdkVersion;
9030                    mAndroidApplication = pkg.applicationInfo;
9031
9032                    if (!mResolverReplaced) {
9033                        mResolveActivity.applicationInfo = mAndroidApplication;
9034                        mResolveActivity.name = ResolverActivity.class.getName();
9035                        mResolveActivity.packageName = mAndroidApplication.packageName;
9036                        mResolveActivity.processName = "system:ui";
9037                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9038                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9039                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9040                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9041                        mResolveActivity.exported = true;
9042                        mResolveActivity.enabled = true;
9043                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9044                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9045                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9046                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9047                                | ActivityInfo.CONFIG_ORIENTATION
9048                                | ActivityInfo.CONFIG_KEYBOARD
9049                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9050                        mResolveInfo.activityInfo = mResolveActivity;
9051                        mResolveInfo.priority = 0;
9052                        mResolveInfo.preferredOrder = 0;
9053                        mResolveInfo.match = 0;
9054                        mResolveComponentName = new ComponentName(
9055                                mAndroidApplication.packageName, mResolveActivity.name);
9056                    }
9057                }
9058            }
9059        }
9060
9061        ArrayList<PackageParser.Package> clientLibPkgs = null;
9062        // writer
9063        synchronized (mPackages) {
9064            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9065                // Only system apps can add new shared libraries.
9066                if (pkg.libraryNames != null) {
9067                    for (int i=0; i<pkg.libraryNames.size(); i++) {
9068                        String name = pkg.libraryNames.get(i);
9069                        boolean allowed = false;
9070                        if (pkg.isUpdatedSystemApp()) {
9071                            // New library entries can only be added through the
9072                            // system image.  This is important to get rid of a lot
9073                            // of nasty edge cases: for example if we allowed a non-
9074                            // system update of the app to add a library, then uninstalling
9075                            // the update would make the library go away, and assumptions
9076                            // we made such as through app install filtering would now
9077                            // have allowed apps on the device which aren't compatible
9078                            // with it.  Better to just have the restriction here, be
9079                            // conservative, and create many fewer cases that can negatively
9080                            // impact the user experience.
9081                            final PackageSetting sysPs = mSettings
9082                                    .getDisabledSystemPkgLPr(pkg.packageName);
9083                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9084                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
9085                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9086                                        allowed = true;
9087                                        break;
9088                                    }
9089                                }
9090                            }
9091                        } else {
9092                            allowed = true;
9093                        }
9094                        if (allowed) {
9095                            if (!mSharedLibraries.containsKey(name)) {
9096                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
9097                            } else if (!name.equals(pkg.packageName)) {
9098                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9099                                        + name + " already exists; skipping");
9100                            }
9101                        } else {
9102                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9103                                    + name + " that is not declared on system image; skipping");
9104                        }
9105                    }
9106                    if ((scanFlags & SCAN_BOOTING) == 0) {
9107                        // If we are not booting, we need to update any applications
9108                        // that are clients of our shared library.  If we are booting,
9109                        // this will all be done once the scan is complete.
9110                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9111                    }
9112                }
9113            }
9114        }
9115
9116        if ((scanFlags & SCAN_BOOTING) != 0) {
9117            // No apps can run during boot scan, so they don't need to be frozen
9118        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9119            // Caller asked to not kill app, so it's probably not frozen
9120        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9121            // Caller asked us to ignore frozen check for some reason; they
9122            // probably didn't know the package name
9123        } else {
9124            // We're doing major surgery on this package, so it better be frozen
9125            // right now to keep it from launching
9126            checkPackageFrozen(pkgName);
9127        }
9128
9129        // Also need to kill any apps that are dependent on the library.
9130        if (clientLibPkgs != null) {
9131            for (int i=0; i<clientLibPkgs.size(); i++) {
9132                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9133                killApplication(clientPkg.applicationInfo.packageName,
9134                        clientPkg.applicationInfo.uid, "update lib");
9135            }
9136        }
9137
9138        // writer
9139        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9140
9141        boolean createIdmapFailed = false;
9142        synchronized (mPackages) {
9143            // We don't expect installation to fail beyond this point
9144
9145            if (pkgSetting.pkg != null) {
9146                // Note that |user| might be null during the initial boot scan. If a codePath
9147                // for an app has changed during a boot scan, it's due to an app update that's
9148                // part of the system partition and marker changes must be applied to all users.
9149                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9150                final int[] userIds = resolveUserIds(userId);
9151                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9152            }
9153
9154            // Add the new setting to mSettings
9155            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9156            // Add the new setting to mPackages
9157            mPackages.put(pkg.applicationInfo.packageName, pkg);
9158            // Make sure we don't accidentally delete its data.
9159            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9160            while (iter.hasNext()) {
9161                PackageCleanItem item = iter.next();
9162                if (pkgName.equals(item.packageName)) {
9163                    iter.remove();
9164                }
9165            }
9166
9167            // Add the package's KeySets to the global KeySetManagerService
9168            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9169            ksms.addScannedPackageLPw(pkg);
9170
9171            int N = pkg.providers.size();
9172            StringBuilder r = null;
9173            int i;
9174            for (i=0; i<N; i++) {
9175                PackageParser.Provider p = pkg.providers.get(i);
9176                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9177                        p.info.processName);
9178                mProviders.addProvider(p);
9179                p.syncable = p.info.isSyncable;
9180                if (p.info.authority != null) {
9181                    String names[] = p.info.authority.split(";");
9182                    p.info.authority = null;
9183                    for (int j = 0; j < names.length; j++) {
9184                        if (j == 1 && p.syncable) {
9185                            // We only want the first authority for a provider to possibly be
9186                            // syncable, so if we already added this provider using a different
9187                            // authority clear the syncable flag. We copy the provider before
9188                            // changing it because the mProviders object contains a reference
9189                            // to a provider that we don't want to change.
9190                            // Only do this for the second authority since the resulting provider
9191                            // object can be the same for all future authorities for this provider.
9192                            p = new PackageParser.Provider(p);
9193                            p.syncable = false;
9194                        }
9195                        if (!mProvidersByAuthority.containsKey(names[j])) {
9196                            mProvidersByAuthority.put(names[j], p);
9197                            if (p.info.authority == null) {
9198                                p.info.authority = names[j];
9199                            } else {
9200                                p.info.authority = p.info.authority + ";" + names[j];
9201                            }
9202                            if (DEBUG_PACKAGE_SCANNING) {
9203                                if (chatty)
9204                                    Log.d(TAG, "Registered content provider: " + names[j]
9205                                            + ", className = " + p.info.name + ", isSyncable = "
9206                                            + p.info.isSyncable);
9207                            }
9208                        } else {
9209                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9210                            Slog.w(TAG, "Skipping provider name " + names[j] +
9211                                    " (in package " + pkg.applicationInfo.packageName +
9212                                    "): name already used by "
9213                                    + ((other != null && other.getComponentName() != null)
9214                                            ? other.getComponentName().getPackageName() : "?"));
9215                        }
9216                    }
9217                }
9218                if (chatty) {
9219                    if (r == null) {
9220                        r = new StringBuilder(256);
9221                    } else {
9222                        r.append(' ');
9223                    }
9224                    r.append(p.info.name);
9225                }
9226            }
9227            if (r != null) {
9228                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9229            }
9230
9231            N = pkg.services.size();
9232            r = null;
9233            for (i=0; i<N; i++) {
9234                PackageParser.Service s = pkg.services.get(i);
9235                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9236                        s.info.processName);
9237                mServices.addService(s);
9238                if (chatty) {
9239                    if (r == null) {
9240                        r = new StringBuilder(256);
9241                    } else {
9242                        r.append(' ');
9243                    }
9244                    r.append(s.info.name);
9245                }
9246            }
9247            if (r != null) {
9248                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9249            }
9250
9251            N = pkg.receivers.size();
9252            r = null;
9253            for (i=0; i<N; i++) {
9254                PackageParser.Activity a = pkg.receivers.get(i);
9255                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9256                        a.info.processName);
9257                mReceivers.addActivity(a, "receiver");
9258                if (chatty) {
9259                    if (r == null) {
9260                        r = new StringBuilder(256);
9261                    } else {
9262                        r.append(' ');
9263                    }
9264                    r.append(a.info.name);
9265                }
9266            }
9267            if (r != null) {
9268                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9269            }
9270
9271            N = pkg.activities.size();
9272            r = null;
9273            for (i=0; i<N; i++) {
9274                PackageParser.Activity a = pkg.activities.get(i);
9275                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9276                        a.info.processName);
9277                mActivities.addActivity(a, "activity");
9278                if (chatty) {
9279                    if (r == null) {
9280                        r = new StringBuilder(256);
9281                    } else {
9282                        r.append(' ');
9283                    }
9284                    r.append(a.info.name);
9285                }
9286            }
9287            if (r != null) {
9288                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9289            }
9290
9291            N = pkg.permissionGroups.size();
9292            r = null;
9293            for (i=0; i<N; i++) {
9294                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9295                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9296                final String curPackageName = cur == null ? null : cur.info.packageName;
9297                // Dont allow ephemeral apps to define new permission groups.
9298                if (pkg.applicationInfo.isEphemeralApp()) {
9299                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9300                            + pg.info.packageName
9301                            + " ignored: ephemeral apps cannot define new permission groups.");
9302                    continue;
9303                }
9304                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9305                if (cur == null || isPackageUpdate) {
9306                    mPermissionGroups.put(pg.info.name, pg);
9307                    if (chatty) {
9308                        if (r == null) {
9309                            r = new StringBuilder(256);
9310                        } else {
9311                            r.append(' ');
9312                        }
9313                        if (isPackageUpdate) {
9314                            r.append("UPD:");
9315                        }
9316                        r.append(pg.info.name);
9317                    }
9318                } else {
9319                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9320                            + pg.info.packageName + " ignored: original from "
9321                            + cur.info.packageName);
9322                    if (chatty) {
9323                        if (r == null) {
9324                            r = new StringBuilder(256);
9325                        } else {
9326                            r.append(' ');
9327                        }
9328                        r.append("DUP:");
9329                        r.append(pg.info.name);
9330                    }
9331                }
9332            }
9333            if (r != null) {
9334                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9335            }
9336
9337            N = pkg.permissions.size();
9338            r = null;
9339            for (i=0; i<N; i++) {
9340                PackageParser.Permission p = pkg.permissions.get(i);
9341
9342                // Dont allow ephemeral apps to define new permissions.
9343                if (pkg.applicationInfo.isEphemeralApp()) {
9344                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9345                            + p.info.packageName
9346                            + " ignored: ephemeral apps cannot define new permissions.");
9347                    continue;
9348                }
9349
9350                // Assume by default that we did not install this permission into the system.
9351                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9352
9353                // Now that permission groups have a special meaning, we ignore permission
9354                // groups for legacy apps to prevent unexpected behavior. In particular,
9355                // permissions for one app being granted to someone just becase they happen
9356                // to be in a group defined by another app (before this had no implications).
9357                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9358                    p.group = mPermissionGroups.get(p.info.group);
9359                    // Warn for a permission in an unknown group.
9360                    if (p.info.group != null && p.group == null) {
9361                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9362                                + p.info.packageName + " in an unknown group " + p.info.group);
9363                    }
9364                }
9365
9366                ArrayMap<String, BasePermission> permissionMap =
9367                        p.tree ? mSettings.mPermissionTrees
9368                                : mSettings.mPermissions;
9369                BasePermission bp = permissionMap.get(p.info.name);
9370
9371                // Allow system apps to redefine non-system permissions
9372                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9373                    final boolean currentOwnerIsSystem = (bp.perm != null
9374                            && isSystemApp(bp.perm.owner));
9375                    if (isSystemApp(p.owner)) {
9376                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9377                            // It's a built-in permission and no owner, take ownership now
9378                            bp.packageSetting = pkgSetting;
9379                            bp.perm = p;
9380                            bp.uid = pkg.applicationInfo.uid;
9381                            bp.sourcePackage = p.info.packageName;
9382                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9383                        } else if (!currentOwnerIsSystem) {
9384                            String msg = "New decl " + p.owner + " of permission  "
9385                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9386                            reportSettingsProblem(Log.WARN, msg);
9387                            bp = null;
9388                        }
9389                    }
9390                }
9391
9392                if (bp == null) {
9393                    bp = new BasePermission(p.info.name, p.info.packageName,
9394                            BasePermission.TYPE_NORMAL);
9395                    permissionMap.put(p.info.name, bp);
9396                }
9397
9398                if (bp.perm == null) {
9399                    if (bp.sourcePackage == null
9400                            || bp.sourcePackage.equals(p.info.packageName)) {
9401                        BasePermission tree = findPermissionTreeLP(p.info.name);
9402                        if (tree == null
9403                                || tree.sourcePackage.equals(p.info.packageName)) {
9404                            bp.packageSetting = pkgSetting;
9405                            bp.perm = p;
9406                            bp.uid = pkg.applicationInfo.uid;
9407                            bp.sourcePackage = p.info.packageName;
9408                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9409                            if (chatty) {
9410                                if (r == null) {
9411                                    r = new StringBuilder(256);
9412                                } else {
9413                                    r.append(' ');
9414                                }
9415                                r.append(p.info.name);
9416                            }
9417                        } else {
9418                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9419                                    + p.info.packageName + " ignored: base tree "
9420                                    + tree.name + " is from package "
9421                                    + tree.sourcePackage);
9422                        }
9423                    } else {
9424                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9425                                + p.info.packageName + " ignored: original from "
9426                                + bp.sourcePackage);
9427                    }
9428                } else if (chatty) {
9429                    if (r == null) {
9430                        r = new StringBuilder(256);
9431                    } else {
9432                        r.append(' ');
9433                    }
9434                    r.append("DUP:");
9435                    r.append(p.info.name);
9436                }
9437                if (bp.perm == p) {
9438                    bp.protectionLevel = p.info.protectionLevel;
9439                }
9440            }
9441
9442            if (r != null) {
9443                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9444            }
9445
9446            N = pkg.instrumentation.size();
9447            r = null;
9448            for (i=0; i<N; i++) {
9449                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9450                a.info.packageName = pkg.applicationInfo.packageName;
9451                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9452                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9453                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9454                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9455                a.info.dataDir = pkg.applicationInfo.dataDir;
9456                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9457                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9458                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9459                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9460                mInstrumentation.put(a.getComponentName(), a);
9461                if (chatty) {
9462                    if (r == null) {
9463                        r = new StringBuilder(256);
9464                    } else {
9465                        r.append(' ');
9466                    }
9467                    r.append(a.info.name);
9468                }
9469            }
9470            if (r != null) {
9471                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9472            }
9473
9474            if (pkg.protectedBroadcasts != null) {
9475                N = pkg.protectedBroadcasts.size();
9476                for (i=0; i<N; i++) {
9477                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9478                }
9479            }
9480
9481            // Create idmap files for pairs of (packages, overlay packages).
9482            // Note: "android", ie framework-res.apk, is handled by native layers.
9483            if (pkg.mOverlayTarget != null) {
9484                // This is an overlay package.
9485                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9486                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9487                        mOverlays.put(pkg.mOverlayTarget,
9488                                new ArrayMap<String, PackageParser.Package>());
9489                    }
9490                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9491                    map.put(pkg.packageName, pkg);
9492                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9493                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9494                        createIdmapFailed = true;
9495                    }
9496                }
9497            } else if (mOverlays.containsKey(pkg.packageName) &&
9498                    !pkg.packageName.equals("android")) {
9499                // This is a regular package, with one or more known overlay packages.
9500                createIdmapsForPackageLI(pkg);
9501            }
9502        }
9503
9504        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9505
9506        if (createIdmapFailed) {
9507            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9508                    "scanPackageLI failed to createIdmap");
9509        }
9510    }
9511
9512    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9513            PackageParser.Package update, int[] userIds) {
9514        if (existing.applicationInfo == null || update.applicationInfo == null) {
9515            // This isn't due to an app installation.
9516            return;
9517        }
9518
9519        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9520        final File newCodePath = new File(update.applicationInfo.getCodePath());
9521
9522        // The codePath hasn't changed, so there's nothing for us to do.
9523        if (Objects.equals(oldCodePath, newCodePath)) {
9524            return;
9525        }
9526
9527        File canonicalNewCodePath;
9528        try {
9529            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9530        } catch (IOException e) {
9531            Slog.w(TAG, "Failed to get canonical path.", e);
9532            return;
9533        }
9534
9535        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9536        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9537        // that the last component of the path (i.e, the name) doesn't need canonicalization
9538        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9539        // but may change in the future. Hopefully this function won't exist at that point.
9540        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9541                oldCodePath.getName());
9542
9543        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9544        // with "@".
9545        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9546        if (!oldMarkerPrefix.endsWith("@")) {
9547            oldMarkerPrefix += "@";
9548        }
9549        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9550        if (!newMarkerPrefix.endsWith("@")) {
9551            newMarkerPrefix += "@";
9552        }
9553
9554        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9555        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9556        for (String updatedPath : updatedPaths) {
9557            String updatedPathName = new File(updatedPath).getName();
9558            markerSuffixes.add(updatedPathName.replace('/', '@'));
9559        }
9560
9561        for (int userId : userIds) {
9562            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9563
9564            for (String markerSuffix : markerSuffixes) {
9565                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9566                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9567                if (oldForeignUseMark.exists()) {
9568                    try {
9569                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9570                                newForeignUseMark.getAbsolutePath());
9571                    } catch (ErrnoException e) {
9572                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9573                        oldForeignUseMark.delete();
9574                    }
9575                }
9576            }
9577        }
9578    }
9579
9580    /**
9581     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9582     * is derived purely on the basis of the contents of {@code scanFile} and
9583     * {@code cpuAbiOverride}.
9584     *
9585     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9586     */
9587    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9588                                 String cpuAbiOverride, boolean extractLibs,
9589                                 File appLib32InstallDir)
9590            throws PackageManagerException {
9591        // Give ourselves some initial paths; we'll come back for another
9592        // pass once we've determined ABI below.
9593        setNativeLibraryPaths(pkg, appLib32InstallDir);
9594
9595        // We would never need to extract libs for forward-locked and external packages,
9596        // since the container service will do it for us. We shouldn't attempt to
9597        // extract libs from system app when it was not updated.
9598        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9599                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9600            extractLibs = false;
9601        }
9602
9603        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9604        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9605
9606        NativeLibraryHelper.Handle handle = null;
9607        try {
9608            handle = NativeLibraryHelper.Handle.create(pkg);
9609            // TODO(multiArch): This can be null for apps that didn't go through the
9610            // usual installation process. We can calculate it again, like we
9611            // do during install time.
9612            //
9613            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9614            // unnecessary.
9615            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9616
9617            // Null out the abis so that they can be recalculated.
9618            pkg.applicationInfo.primaryCpuAbi = null;
9619            pkg.applicationInfo.secondaryCpuAbi = null;
9620            if (isMultiArch(pkg.applicationInfo)) {
9621                // Warn if we've set an abiOverride for multi-lib packages..
9622                // By definition, we need to copy both 32 and 64 bit libraries for
9623                // such packages.
9624                if (pkg.cpuAbiOverride != null
9625                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9626                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9627                }
9628
9629                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9630                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9631                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9632                    if (extractLibs) {
9633                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9634                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9635                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9636                                useIsaSpecificSubdirs);
9637                    } else {
9638                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9639                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9640                    }
9641                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9642                }
9643
9644                maybeThrowExceptionForMultiArchCopy(
9645                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9646
9647                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9648                    if (extractLibs) {
9649                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9650                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9651                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9652                                useIsaSpecificSubdirs);
9653                    } else {
9654                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9655                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9656                    }
9657                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9658                }
9659
9660                maybeThrowExceptionForMultiArchCopy(
9661                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9662
9663                if (abi64 >= 0) {
9664                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9665                }
9666
9667                if (abi32 >= 0) {
9668                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9669                    if (abi64 >= 0) {
9670                        if (pkg.use32bitAbi) {
9671                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9672                            pkg.applicationInfo.primaryCpuAbi = abi;
9673                        } else {
9674                            pkg.applicationInfo.secondaryCpuAbi = abi;
9675                        }
9676                    } else {
9677                        pkg.applicationInfo.primaryCpuAbi = abi;
9678                    }
9679                }
9680
9681            } else {
9682                String[] abiList = (cpuAbiOverride != null) ?
9683                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9684
9685                // Enable gross and lame hacks for apps that are built with old
9686                // SDK tools. We must scan their APKs for renderscript bitcode and
9687                // not launch them if it's present. Don't bother checking on devices
9688                // that don't have 64 bit support.
9689                boolean needsRenderScriptOverride = false;
9690                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9691                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9692                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9693                    needsRenderScriptOverride = true;
9694                }
9695
9696                final int copyRet;
9697                if (extractLibs) {
9698                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9699                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9700                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9701                } else {
9702                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9703                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9704                }
9705                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9706
9707                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9708                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9709                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9710                }
9711
9712                if (copyRet >= 0) {
9713                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9714                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9715                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9716                } else if (needsRenderScriptOverride) {
9717                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9718                }
9719            }
9720        } catch (IOException ioe) {
9721            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9722        } finally {
9723            IoUtils.closeQuietly(handle);
9724        }
9725
9726        // Now that we've calculated the ABIs and determined if it's an internal app,
9727        // we will go ahead and populate the nativeLibraryPath.
9728        setNativeLibraryPaths(pkg, appLib32InstallDir);
9729    }
9730
9731    /**
9732     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9733     * i.e, so that all packages can be run inside a single process if required.
9734     *
9735     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9736     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9737     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9738     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9739     * updating a package that belongs to a shared user.
9740     *
9741     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9742     * adds unnecessary complexity.
9743     */
9744    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9745            PackageParser.Package scannedPackage) {
9746        String requiredInstructionSet = null;
9747        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9748            requiredInstructionSet = VMRuntime.getInstructionSet(
9749                     scannedPackage.applicationInfo.primaryCpuAbi);
9750        }
9751
9752        PackageSetting requirer = null;
9753        for (PackageSetting ps : packagesForUser) {
9754            // If packagesForUser contains scannedPackage, we skip it. This will happen
9755            // when scannedPackage is an update of an existing package. Without this check,
9756            // we will never be able to change the ABI of any package belonging to a shared
9757            // user, even if it's compatible with other packages.
9758            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9759                if (ps.primaryCpuAbiString == null) {
9760                    continue;
9761                }
9762
9763                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9764                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9765                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9766                    // this but there's not much we can do.
9767                    String errorMessage = "Instruction set mismatch, "
9768                            + ((requirer == null) ? "[caller]" : requirer)
9769                            + " requires " + requiredInstructionSet + " whereas " + ps
9770                            + " requires " + instructionSet;
9771                    Slog.w(TAG, errorMessage);
9772                }
9773
9774                if (requiredInstructionSet == null) {
9775                    requiredInstructionSet = instructionSet;
9776                    requirer = ps;
9777                }
9778            }
9779        }
9780
9781        if (requiredInstructionSet != null) {
9782            String adjustedAbi;
9783            if (requirer != null) {
9784                // requirer != null implies that either scannedPackage was null or that scannedPackage
9785                // did not require an ABI, in which case we have to adjust scannedPackage to match
9786                // the ABI of the set (which is the same as requirer's ABI)
9787                adjustedAbi = requirer.primaryCpuAbiString;
9788                if (scannedPackage != null) {
9789                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9790                }
9791            } else {
9792                // requirer == null implies that we're updating all ABIs in the set to
9793                // match scannedPackage.
9794                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9795            }
9796
9797            for (PackageSetting ps : packagesForUser) {
9798                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9799                    if (ps.primaryCpuAbiString != null) {
9800                        continue;
9801                    }
9802
9803                    ps.primaryCpuAbiString = adjustedAbi;
9804                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9805                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9806                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9807                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9808                                + " (requirer="
9809                                + (requirer == null ? "null" : requirer.pkg.packageName)
9810                                + ", scannedPackage="
9811                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9812                                + ")");
9813                        try {
9814                            mInstaller.rmdex(ps.codePathString,
9815                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9816                        } catch (InstallerException ignored) {
9817                        }
9818                    }
9819                }
9820            }
9821        }
9822    }
9823
9824    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9825        synchronized (mPackages) {
9826            mResolverReplaced = true;
9827            // Set up information for custom user intent resolution activity.
9828            mResolveActivity.applicationInfo = pkg.applicationInfo;
9829            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9830            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9831            mResolveActivity.processName = pkg.applicationInfo.packageName;
9832            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9833            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9834                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9835            mResolveActivity.theme = 0;
9836            mResolveActivity.exported = true;
9837            mResolveActivity.enabled = true;
9838            mResolveInfo.activityInfo = mResolveActivity;
9839            mResolveInfo.priority = 0;
9840            mResolveInfo.preferredOrder = 0;
9841            mResolveInfo.match = 0;
9842            mResolveComponentName = mCustomResolverComponentName;
9843            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9844                    mResolveComponentName);
9845        }
9846    }
9847
9848    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9849        if (installerComponent == null) {
9850            if (DEBUG_EPHEMERAL) {
9851                Slog.d(TAG, "Clear ephemeral installer activity");
9852            }
9853            mEphemeralInstallerActivity.applicationInfo = null;
9854            return;
9855        }
9856
9857        if (DEBUG_EPHEMERAL) {
9858            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9859        }
9860        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9861        // Set up information for ephemeral installer activity
9862        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9863        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9864        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9865        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9866        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9867        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9868                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9869        mEphemeralInstallerActivity.theme = 0;
9870        mEphemeralInstallerActivity.exported = true;
9871        mEphemeralInstallerActivity.enabled = true;
9872        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9873        mEphemeralInstallerInfo.priority = 0;
9874        mEphemeralInstallerInfo.preferredOrder = 1;
9875        mEphemeralInstallerInfo.isDefault = true;
9876        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9877                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9878    }
9879
9880    private static String calculateBundledApkRoot(final String codePathString) {
9881        final File codePath = new File(codePathString);
9882        final File codeRoot;
9883        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9884            codeRoot = Environment.getRootDirectory();
9885        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9886            codeRoot = Environment.getOemDirectory();
9887        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9888            codeRoot = Environment.getVendorDirectory();
9889        } else {
9890            // Unrecognized code path; take its top real segment as the apk root:
9891            // e.g. /something/app/blah.apk => /something
9892            try {
9893                File f = codePath.getCanonicalFile();
9894                File parent = f.getParentFile();    // non-null because codePath is a file
9895                File tmp;
9896                while ((tmp = parent.getParentFile()) != null) {
9897                    f = parent;
9898                    parent = tmp;
9899                }
9900                codeRoot = f;
9901                Slog.w(TAG, "Unrecognized code path "
9902                        + codePath + " - using " + codeRoot);
9903            } catch (IOException e) {
9904                // Can't canonicalize the code path -- shenanigans?
9905                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9906                return Environment.getRootDirectory().getPath();
9907            }
9908        }
9909        return codeRoot.getPath();
9910    }
9911
9912    /**
9913     * Derive and set the location of native libraries for the given package,
9914     * which varies depending on where and how the package was installed.
9915     */
9916    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9917        final ApplicationInfo info = pkg.applicationInfo;
9918        final String codePath = pkg.codePath;
9919        final File codeFile = new File(codePath);
9920        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9921        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9922
9923        info.nativeLibraryRootDir = null;
9924        info.nativeLibraryRootRequiresIsa = false;
9925        info.nativeLibraryDir = null;
9926        info.secondaryNativeLibraryDir = null;
9927
9928        if (isApkFile(codeFile)) {
9929            // Monolithic install
9930            if (bundledApp) {
9931                // If "/system/lib64/apkname" exists, assume that is the per-package
9932                // native library directory to use; otherwise use "/system/lib/apkname".
9933                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9934                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9935                        getPrimaryInstructionSet(info));
9936
9937                // This is a bundled system app so choose the path based on the ABI.
9938                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9939                // is just the default path.
9940                final String apkName = deriveCodePathName(codePath);
9941                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9942                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9943                        apkName).getAbsolutePath();
9944
9945                if (info.secondaryCpuAbi != null) {
9946                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9947                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9948                            secondaryLibDir, apkName).getAbsolutePath();
9949                }
9950            } else if (asecApp) {
9951                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9952                        .getAbsolutePath();
9953            } else {
9954                final String apkName = deriveCodePathName(codePath);
9955                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9956                        .getAbsolutePath();
9957            }
9958
9959            info.nativeLibraryRootRequiresIsa = false;
9960            info.nativeLibraryDir = info.nativeLibraryRootDir;
9961        } else {
9962            // Cluster install
9963            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9964            info.nativeLibraryRootRequiresIsa = true;
9965
9966            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9967                    getPrimaryInstructionSet(info)).getAbsolutePath();
9968
9969            if (info.secondaryCpuAbi != null) {
9970                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9971                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9972            }
9973        }
9974    }
9975
9976    /**
9977     * Calculate the abis and roots for a bundled app. These can uniquely
9978     * be determined from the contents of the system partition, i.e whether
9979     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9980     * of this information, and instead assume that the system was built
9981     * sensibly.
9982     */
9983    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9984                                           PackageSetting pkgSetting) {
9985        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9986
9987        // If "/system/lib64/apkname" exists, assume that is the per-package
9988        // native library directory to use; otherwise use "/system/lib/apkname".
9989        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9990        setBundledAppAbi(pkg, apkRoot, apkName);
9991        // pkgSetting might be null during rescan following uninstall of updates
9992        // to a bundled app, so accommodate that possibility.  The settings in
9993        // that case will be established later from the parsed package.
9994        //
9995        // If the settings aren't null, sync them up with what we've just derived.
9996        // note that apkRoot isn't stored in the package settings.
9997        if (pkgSetting != null) {
9998            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9999            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10000        }
10001    }
10002
10003    /**
10004     * Deduces the ABI of a bundled app and sets the relevant fields on the
10005     * parsed pkg object.
10006     *
10007     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10008     *        under which system libraries are installed.
10009     * @param apkName the name of the installed package.
10010     */
10011    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10012        final File codeFile = new File(pkg.codePath);
10013
10014        final boolean has64BitLibs;
10015        final boolean has32BitLibs;
10016        if (isApkFile(codeFile)) {
10017            // Monolithic install
10018            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10019            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10020        } else {
10021            // Cluster install
10022            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10023            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10024                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10025                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10026                has64BitLibs = (new File(rootDir, isa)).exists();
10027            } else {
10028                has64BitLibs = false;
10029            }
10030            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10031                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10032                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10033                has32BitLibs = (new File(rootDir, isa)).exists();
10034            } else {
10035                has32BitLibs = false;
10036            }
10037        }
10038
10039        if (has64BitLibs && !has32BitLibs) {
10040            // The package has 64 bit libs, but not 32 bit libs. Its primary
10041            // ABI should be 64 bit. We can safely assume here that the bundled
10042            // native libraries correspond to the most preferred ABI in the list.
10043
10044            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10045            pkg.applicationInfo.secondaryCpuAbi = null;
10046        } else if (has32BitLibs && !has64BitLibs) {
10047            // The package has 32 bit libs but not 64 bit libs. Its primary
10048            // ABI should be 32 bit.
10049
10050            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10051            pkg.applicationInfo.secondaryCpuAbi = null;
10052        } else if (has32BitLibs && has64BitLibs) {
10053            // The application has both 64 and 32 bit bundled libraries. We check
10054            // here that the app declares multiArch support, and warn if it doesn't.
10055            //
10056            // We will be lenient here and record both ABIs. The primary will be the
10057            // ABI that's higher on the list, i.e, a device that's configured to prefer
10058            // 64 bit apps will see a 64 bit primary ABI,
10059
10060            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10061                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10062            }
10063
10064            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10065                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10066                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10067            } else {
10068                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10069                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10070            }
10071        } else {
10072            pkg.applicationInfo.primaryCpuAbi = null;
10073            pkg.applicationInfo.secondaryCpuAbi = null;
10074        }
10075    }
10076
10077    private void killApplication(String pkgName, int appId, String reason) {
10078        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10079    }
10080
10081    private void killApplication(String pkgName, int appId, int userId, String reason) {
10082        // Request the ActivityManager to kill the process(only for existing packages)
10083        // so that we do not end up in a confused state while the user is still using the older
10084        // version of the application while the new one gets installed.
10085        final long token = Binder.clearCallingIdentity();
10086        try {
10087            IActivityManager am = ActivityManager.getService();
10088            if (am != null) {
10089                try {
10090                    am.killApplication(pkgName, appId, userId, reason);
10091                } catch (RemoteException e) {
10092                }
10093            }
10094        } finally {
10095            Binder.restoreCallingIdentity(token);
10096        }
10097    }
10098
10099    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10100        // Remove the parent package setting
10101        PackageSetting ps = (PackageSetting) pkg.mExtras;
10102        if (ps != null) {
10103            removePackageLI(ps, chatty);
10104        }
10105        // Remove the child package setting
10106        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10107        for (int i = 0; i < childCount; i++) {
10108            PackageParser.Package childPkg = pkg.childPackages.get(i);
10109            ps = (PackageSetting) childPkg.mExtras;
10110            if (ps != null) {
10111                removePackageLI(ps, chatty);
10112            }
10113        }
10114    }
10115
10116    void removePackageLI(PackageSetting ps, boolean chatty) {
10117        if (DEBUG_INSTALL) {
10118            if (chatty)
10119                Log.d(TAG, "Removing package " + ps.name);
10120        }
10121
10122        // writer
10123        synchronized (mPackages) {
10124            mPackages.remove(ps.name);
10125            final PackageParser.Package pkg = ps.pkg;
10126            if (pkg != null) {
10127                cleanPackageDataStructuresLILPw(pkg, chatty);
10128            }
10129        }
10130    }
10131
10132    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10133        if (DEBUG_INSTALL) {
10134            if (chatty)
10135                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10136        }
10137
10138        // writer
10139        synchronized (mPackages) {
10140            // Remove the parent package
10141            mPackages.remove(pkg.applicationInfo.packageName);
10142            cleanPackageDataStructuresLILPw(pkg, chatty);
10143
10144            // Remove the child packages
10145            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10146            for (int i = 0; i < childCount; i++) {
10147                PackageParser.Package childPkg = pkg.childPackages.get(i);
10148                mPackages.remove(childPkg.applicationInfo.packageName);
10149                cleanPackageDataStructuresLILPw(childPkg, chatty);
10150            }
10151        }
10152    }
10153
10154    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10155        int N = pkg.providers.size();
10156        StringBuilder r = null;
10157        int i;
10158        for (i=0; i<N; i++) {
10159            PackageParser.Provider p = pkg.providers.get(i);
10160            mProviders.removeProvider(p);
10161            if (p.info.authority == null) {
10162
10163                /* There was another ContentProvider with this authority when
10164                 * this app was installed so this authority is null,
10165                 * Ignore it as we don't have to unregister the provider.
10166                 */
10167                continue;
10168            }
10169            String names[] = p.info.authority.split(";");
10170            for (int j = 0; j < names.length; j++) {
10171                if (mProvidersByAuthority.get(names[j]) == p) {
10172                    mProvidersByAuthority.remove(names[j]);
10173                    if (DEBUG_REMOVE) {
10174                        if (chatty)
10175                            Log.d(TAG, "Unregistered content provider: " + names[j]
10176                                    + ", className = " + p.info.name + ", isSyncable = "
10177                                    + p.info.isSyncable);
10178                    }
10179                }
10180            }
10181            if (DEBUG_REMOVE && chatty) {
10182                if (r == null) {
10183                    r = new StringBuilder(256);
10184                } else {
10185                    r.append(' ');
10186                }
10187                r.append(p.info.name);
10188            }
10189        }
10190        if (r != null) {
10191            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10192        }
10193
10194        N = pkg.services.size();
10195        r = null;
10196        for (i=0; i<N; i++) {
10197            PackageParser.Service s = pkg.services.get(i);
10198            mServices.removeService(s);
10199            if (chatty) {
10200                if (r == null) {
10201                    r = new StringBuilder(256);
10202                } else {
10203                    r.append(' ');
10204                }
10205                r.append(s.info.name);
10206            }
10207        }
10208        if (r != null) {
10209            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10210        }
10211
10212        N = pkg.receivers.size();
10213        r = null;
10214        for (i=0; i<N; i++) {
10215            PackageParser.Activity a = pkg.receivers.get(i);
10216            mReceivers.removeActivity(a, "receiver");
10217            if (DEBUG_REMOVE && chatty) {
10218                if (r == null) {
10219                    r = new StringBuilder(256);
10220                } else {
10221                    r.append(' ');
10222                }
10223                r.append(a.info.name);
10224            }
10225        }
10226        if (r != null) {
10227            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10228        }
10229
10230        N = pkg.activities.size();
10231        r = null;
10232        for (i=0; i<N; i++) {
10233            PackageParser.Activity a = pkg.activities.get(i);
10234            mActivities.removeActivity(a, "activity");
10235            if (DEBUG_REMOVE && chatty) {
10236                if (r == null) {
10237                    r = new StringBuilder(256);
10238                } else {
10239                    r.append(' ');
10240                }
10241                r.append(a.info.name);
10242            }
10243        }
10244        if (r != null) {
10245            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10246        }
10247
10248        N = pkg.permissions.size();
10249        r = null;
10250        for (i=0; i<N; i++) {
10251            PackageParser.Permission p = pkg.permissions.get(i);
10252            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10253            if (bp == null) {
10254                bp = mSettings.mPermissionTrees.get(p.info.name);
10255            }
10256            if (bp != null && bp.perm == p) {
10257                bp.perm = null;
10258                if (DEBUG_REMOVE && chatty) {
10259                    if (r == null) {
10260                        r = new StringBuilder(256);
10261                    } else {
10262                        r.append(' ');
10263                    }
10264                    r.append(p.info.name);
10265                }
10266            }
10267            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10268                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10269                if (appOpPkgs != null) {
10270                    appOpPkgs.remove(pkg.packageName);
10271                }
10272            }
10273        }
10274        if (r != null) {
10275            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10276        }
10277
10278        N = pkg.requestedPermissions.size();
10279        r = null;
10280        for (i=0; i<N; i++) {
10281            String perm = pkg.requestedPermissions.get(i);
10282            BasePermission bp = mSettings.mPermissions.get(perm);
10283            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10284                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10285                if (appOpPkgs != null) {
10286                    appOpPkgs.remove(pkg.packageName);
10287                    if (appOpPkgs.isEmpty()) {
10288                        mAppOpPermissionPackages.remove(perm);
10289                    }
10290                }
10291            }
10292        }
10293        if (r != null) {
10294            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10295        }
10296
10297        N = pkg.instrumentation.size();
10298        r = null;
10299        for (i=0; i<N; i++) {
10300            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10301            mInstrumentation.remove(a.getComponentName());
10302            if (DEBUG_REMOVE && chatty) {
10303                if (r == null) {
10304                    r = new StringBuilder(256);
10305                } else {
10306                    r.append(' ');
10307                }
10308                r.append(a.info.name);
10309            }
10310        }
10311        if (r != null) {
10312            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10313        }
10314
10315        r = null;
10316        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10317            // Only system apps can hold shared libraries.
10318            if (pkg.libraryNames != null) {
10319                for (i=0; i<pkg.libraryNames.size(); i++) {
10320                    String name = pkg.libraryNames.get(i);
10321                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10322                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10323                        mSharedLibraries.remove(name);
10324                        if (DEBUG_REMOVE && chatty) {
10325                            if (r == null) {
10326                                r = new StringBuilder(256);
10327                            } else {
10328                                r.append(' ');
10329                            }
10330                            r.append(name);
10331                        }
10332                    }
10333                }
10334            }
10335        }
10336        if (r != null) {
10337            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10338        }
10339    }
10340
10341    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10342        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10343            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10344                return true;
10345            }
10346        }
10347        return false;
10348    }
10349
10350    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10351    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10352    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10353
10354    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10355        // Update the parent permissions
10356        updatePermissionsLPw(pkg.packageName, pkg, flags);
10357        // Update the child permissions
10358        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10359        for (int i = 0; i < childCount; i++) {
10360            PackageParser.Package childPkg = pkg.childPackages.get(i);
10361            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10362        }
10363    }
10364
10365    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10366            int flags) {
10367        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10368        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10369    }
10370
10371    private void updatePermissionsLPw(String changingPkg,
10372            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10373        // Make sure there are no dangling permission trees.
10374        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10375        while (it.hasNext()) {
10376            final BasePermission bp = it.next();
10377            if (bp.packageSetting == null) {
10378                // We may not yet have parsed the package, so just see if
10379                // we still know about its settings.
10380                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10381            }
10382            if (bp.packageSetting == null) {
10383                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10384                        + " from package " + bp.sourcePackage);
10385                it.remove();
10386            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10387                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10388                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10389                            + " from package " + bp.sourcePackage);
10390                    flags |= UPDATE_PERMISSIONS_ALL;
10391                    it.remove();
10392                }
10393            }
10394        }
10395
10396        // Make sure all dynamic permissions have been assigned to a package,
10397        // and make sure there are no dangling permissions.
10398        it = mSettings.mPermissions.values().iterator();
10399        while (it.hasNext()) {
10400            final BasePermission bp = it.next();
10401            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10402                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10403                        + bp.name + " pkg=" + bp.sourcePackage
10404                        + " info=" + bp.pendingInfo);
10405                if (bp.packageSetting == null && bp.pendingInfo != null) {
10406                    final BasePermission tree = findPermissionTreeLP(bp.name);
10407                    if (tree != null && tree.perm != null) {
10408                        bp.packageSetting = tree.packageSetting;
10409                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10410                                new PermissionInfo(bp.pendingInfo));
10411                        bp.perm.info.packageName = tree.perm.info.packageName;
10412                        bp.perm.info.name = bp.name;
10413                        bp.uid = tree.uid;
10414                    }
10415                }
10416            }
10417            if (bp.packageSetting == null) {
10418                // We may not yet have parsed the package, so just see if
10419                // we still know about its settings.
10420                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10421            }
10422            if (bp.packageSetting == null) {
10423                Slog.w(TAG, "Removing dangling permission: " + bp.name
10424                        + " from package " + bp.sourcePackage);
10425                it.remove();
10426            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10427                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10428                    Slog.i(TAG, "Removing old permission: " + bp.name
10429                            + " from package " + bp.sourcePackage);
10430                    flags |= UPDATE_PERMISSIONS_ALL;
10431                    it.remove();
10432                }
10433            }
10434        }
10435
10436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10437        // Now update the permissions for all packages, in particular
10438        // replace the granted permissions of the system packages.
10439        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10440            for (PackageParser.Package pkg : mPackages.values()) {
10441                if (pkg != pkgInfo) {
10442                    // Only replace for packages on requested volume
10443                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10444                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10445                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10446                    grantPermissionsLPw(pkg, replace, changingPkg);
10447                }
10448            }
10449        }
10450
10451        if (pkgInfo != null) {
10452            // Only replace for packages on requested volume
10453            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10454            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10455                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10456            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10457        }
10458        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10459    }
10460
10461    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10462            String packageOfInterest) {
10463        // IMPORTANT: There are two types of permissions: install and runtime.
10464        // Install time permissions are granted when the app is installed to
10465        // all device users and users added in the future. Runtime permissions
10466        // are granted at runtime explicitly to specific users. Normal and signature
10467        // protected permissions are install time permissions. Dangerous permissions
10468        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10469        // otherwise they are runtime permissions. This function does not manage
10470        // runtime permissions except for the case an app targeting Lollipop MR1
10471        // being upgraded to target a newer SDK, in which case dangerous permissions
10472        // are transformed from install time to runtime ones.
10473
10474        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10475        if (ps == null) {
10476            return;
10477        }
10478
10479        PermissionsState permissionsState = ps.getPermissionsState();
10480        PermissionsState origPermissions = permissionsState;
10481
10482        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10483
10484        boolean runtimePermissionsRevoked = false;
10485        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10486
10487        boolean changedInstallPermission = false;
10488
10489        if (replace) {
10490            ps.installPermissionsFixed = false;
10491            if (!ps.isSharedUser()) {
10492                origPermissions = new PermissionsState(permissionsState);
10493                permissionsState.reset();
10494            } else {
10495                // We need to know only about runtime permission changes since the
10496                // calling code always writes the install permissions state but
10497                // the runtime ones are written only if changed. The only cases of
10498                // changed runtime permissions here are promotion of an install to
10499                // runtime and revocation of a runtime from a shared user.
10500                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10501                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10502                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10503                    runtimePermissionsRevoked = true;
10504                }
10505            }
10506        }
10507
10508        permissionsState.setGlobalGids(mGlobalGids);
10509
10510        final int N = pkg.requestedPermissions.size();
10511        for (int i=0; i<N; i++) {
10512            final String name = pkg.requestedPermissions.get(i);
10513            final BasePermission bp = mSettings.mPermissions.get(name);
10514
10515            if (DEBUG_INSTALL) {
10516                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10517            }
10518
10519            if (bp == null || bp.packageSetting == null) {
10520                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10521                    Slog.w(TAG, "Unknown permission " + name
10522                            + " in package " + pkg.packageName);
10523                }
10524                continue;
10525            }
10526
10527
10528            // Limit ephemeral apps to ephemeral allowed permissions.
10529            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10530                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10531                        + pkg.packageName);
10532                continue;
10533            }
10534
10535            final String perm = bp.name;
10536            boolean allowedSig = false;
10537            int grant = GRANT_DENIED;
10538
10539            // Keep track of app op permissions.
10540            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10541                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10542                if (pkgs == null) {
10543                    pkgs = new ArraySet<>();
10544                    mAppOpPermissionPackages.put(bp.name, pkgs);
10545                }
10546                pkgs.add(pkg.packageName);
10547            }
10548
10549            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10550            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10551                    >= Build.VERSION_CODES.M;
10552            switch (level) {
10553                case PermissionInfo.PROTECTION_NORMAL: {
10554                    // For all apps normal permissions are install time ones.
10555                    grant = GRANT_INSTALL;
10556                } break;
10557
10558                case PermissionInfo.PROTECTION_DANGEROUS: {
10559                    // If a permission review is required for legacy apps we represent
10560                    // their permissions as always granted runtime ones since we need
10561                    // to keep the review required permission flag per user while an
10562                    // install permission's state is shared across all users.
10563                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10564                        // For legacy apps dangerous permissions are install time ones.
10565                        grant = GRANT_INSTALL;
10566                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10567                        // For legacy apps that became modern, install becomes runtime.
10568                        grant = GRANT_UPGRADE;
10569                    } else if (mPromoteSystemApps
10570                            && isSystemApp(ps)
10571                            && mExistingSystemPackages.contains(ps.name)) {
10572                        // For legacy system apps, install becomes runtime.
10573                        // We cannot check hasInstallPermission() for system apps since those
10574                        // permissions were granted implicitly and not persisted pre-M.
10575                        grant = GRANT_UPGRADE;
10576                    } else {
10577                        // For modern apps keep runtime permissions unchanged.
10578                        grant = GRANT_RUNTIME;
10579                    }
10580                } break;
10581
10582                case PermissionInfo.PROTECTION_SIGNATURE: {
10583                    // For all apps signature permissions are install time ones.
10584                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10585                    if (allowedSig) {
10586                        grant = GRANT_INSTALL;
10587                    }
10588                } break;
10589            }
10590
10591            if (DEBUG_INSTALL) {
10592                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10593            }
10594
10595            if (grant != GRANT_DENIED) {
10596                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10597                    // If this is an existing, non-system package, then
10598                    // we can't add any new permissions to it.
10599                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10600                        // Except...  if this is a permission that was added
10601                        // to the platform (note: need to only do this when
10602                        // updating the platform).
10603                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10604                            grant = GRANT_DENIED;
10605                        }
10606                    }
10607                }
10608
10609                switch (grant) {
10610                    case GRANT_INSTALL: {
10611                        // Revoke this as runtime permission to handle the case of
10612                        // a runtime permission being downgraded to an install one.
10613                        // Also in permission review mode we keep dangerous permissions
10614                        // for legacy apps
10615                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10616                            if (origPermissions.getRuntimePermissionState(
10617                                    bp.name, userId) != null) {
10618                                // Revoke the runtime permission and clear the flags.
10619                                origPermissions.revokeRuntimePermission(bp, userId);
10620                                origPermissions.updatePermissionFlags(bp, userId,
10621                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10622                                // If we revoked a permission permission, we have to write.
10623                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10624                                        changedRuntimePermissionUserIds, userId);
10625                            }
10626                        }
10627                        // Grant an install permission.
10628                        if (permissionsState.grantInstallPermission(bp) !=
10629                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10630                            changedInstallPermission = true;
10631                        }
10632                    } break;
10633
10634                    case GRANT_RUNTIME: {
10635                        // Grant previously granted runtime permissions.
10636                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10637                            PermissionState permissionState = origPermissions
10638                                    .getRuntimePermissionState(bp.name, userId);
10639                            int flags = permissionState != null
10640                                    ? permissionState.getFlags() : 0;
10641                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10642                                // Don't propagate the permission in a permission review mode if
10643                                // the former was revoked, i.e. marked to not propagate on upgrade.
10644                                // Note that in a permission review mode install permissions are
10645                                // represented as constantly granted runtime ones since we need to
10646                                // keep a per user state associated with the permission. Also the
10647                                // revoke on upgrade flag is no longer applicable and is reset.
10648                                final boolean revokeOnUpgrade = (flags & PackageManager
10649                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10650                                if (revokeOnUpgrade) {
10651                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10652                                    // Since we changed the flags, we have to write.
10653                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10654                                            changedRuntimePermissionUserIds, userId);
10655                                }
10656                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10657                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
10658                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
10659                                        // If we cannot put the permission as it was,
10660                                        // we have to write.
10661                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10662                                                changedRuntimePermissionUserIds, userId);
10663                                    }
10664                                }
10665
10666                                // If the app supports runtime permissions no need for a review.
10667                                if (mPermissionReviewRequired
10668                                        && appSupportsRuntimePermissions
10669                                        && (flags & PackageManager
10670                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10671                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10672                                    // Since we changed the flags, we have to write.
10673                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10674                                            changedRuntimePermissionUserIds, userId);
10675                                }
10676                            } else if (mPermissionReviewRequired
10677                                    && !appSupportsRuntimePermissions) {
10678                                // For legacy apps that need a permission review, every new
10679                                // runtime permission is granted but it is pending a review.
10680                                // We also need to review only platform defined runtime
10681                                // permissions as these are the only ones the platform knows
10682                                // how to disable the API to simulate revocation as legacy
10683                                // apps don't expect to run with revoked permissions.
10684                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10685                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10686                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10687                                        // We changed the flags, hence have to write.
10688                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10689                                                changedRuntimePermissionUserIds, userId);
10690                                    }
10691                                }
10692                                if (permissionsState.grantRuntimePermission(bp, userId)
10693                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10694                                    // We changed the permission, hence have to write.
10695                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10696                                            changedRuntimePermissionUserIds, userId);
10697                                }
10698                            }
10699                            // Propagate the permission flags.
10700                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10701                        }
10702                    } break;
10703
10704                    case GRANT_UPGRADE: {
10705                        // Grant runtime permissions for a previously held install permission.
10706                        PermissionState permissionState = origPermissions
10707                                .getInstallPermissionState(bp.name);
10708                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10709
10710                        if (origPermissions.revokeInstallPermission(bp)
10711                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10712                            // We will be transferring the permission flags, so clear them.
10713                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10714                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10715                            changedInstallPermission = true;
10716                        }
10717
10718                        // If the permission is not to be promoted to runtime we ignore it and
10719                        // also its other flags as they are not applicable to install permissions.
10720                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10721                            for (int userId : currentUserIds) {
10722                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10723                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10724                                    // Transfer the permission flags.
10725                                    permissionsState.updatePermissionFlags(bp, userId,
10726                                            flags, flags);
10727                                    // If we granted the permission, we have to write.
10728                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10729                                            changedRuntimePermissionUserIds, userId);
10730                                }
10731                            }
10732                        }
10733                    } break;
10734
10735                    default: {
10736                        if (packageOfInterest == null
10737                                || packageOfInterest.equals(pkg.packageName)) {
10738                            Slog.w(TAG, "Not granting permission " + perm
10739                                    + " to package " + pkg.packageName
10740                                    + " because it was previously installed without");
10741                        }
10742                    } break;
10743                }
10744            } else {
10745                if (permissionsState.revokeInstallPermission(bp) !=
10746                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10747                    // Also drop the permission flags.
10748                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10749                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10750                    changedInstallPermission = true;
10751                    Slog.i(TAG, "Un-granting permission " + perm
10752                            + " from package " + pkg.packageName
10753                            + " (protectionLevel=" + bp.protectionLevel
10754                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10755                            + ")");
10756                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10757                    // Don't print warning for app op permissions, since it is fine for them
10758                    // not to be granted, there is a UI for the user to decide.
10759                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10760                        Slog.w(TAG, "Not granting permission " + perm
10761                                + " to package " + pkg.packageName
10762                                + " (protectionLevel=" + bp.protectionLevel
10763                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10764                                + ")");
10765                    }
10766                }
10767            }
10768        }
10769
10770        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10771                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10772            // This is the first that we have heard about this package, so the
10773            // permissions we have now selected are fixed until explicitly
10774            // changed.
10775            ps.installPermissionsFixed = true;
10776        }
10777
10778        // Persist the runtime permissions state for users with changes. If permissions
10779        // were revoked because no app in the shared user declares them we have to
10780        // write synchronously to avoid losing runtime permissions state.
10781        for (int userId : changedRuntimePermissionUserIds) {
10782            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10783        }
10784    }
10785
10786    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10787        boolean allowed = false;
10788        final int NP = PackageParser.NEW_PERMISSIONS.length;
10789        for (int ip=0; ip<NP; ip++) {
10790            final PackageParser.NewPermissionInfo npi
10791                    = PackageParser.NEW_PERMISSIONS[ip];
10792            if (npi.name.equals(perm)
10793                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10794                allowed = true;
10795                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10796                        + pkg.packageName);
10797                break;
10798            }
10799        }
10800        return allowed;
10801    }
10802
10803    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10804            BasePermission bp, PermissionsState origPermissions) {
10805        boolean privilegedPermission = (bp.protectionLevel
10806                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10807        boolean privappPermissionsDisable =
10808                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10809        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10810        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10811        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10812                && !platformPackage && platformPermission) {
10813            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10814                    .getPrivAppPermissions(pkg.packageName);
10815            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10816            if (!whitelisted) {
10817                Slog.w(TAG, "Privileged permission " + perm + " for package "
10818                        + pkg.packageName + " - not in privapp-permissions whitelist");
10819                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10820                    return false;
10821                }
10822            }
10823        }
10824        boolean allowed = (compareSignatures(
10825                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10826                        == PackageManager.SIGNATURE_MATCH)
10827                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10828                        == PackageManager.SIGNATURE_MATCH);
10829        if (!allowed && privilegedPermission) {
10830            if (isSystemApp(pkg)) {
10831                // For updated system applications, a system permission
10832                // is granted only if it had been defined by the original application.
10833                if (pkg.isUpdatedSystemApp()) {
10834                    final PackageSetting sysPs = mSettings
10835                            .getDisabledSystemPkgLPr(pkg.packageName);
10836                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10837                        // If the original was granted this permission, we take
10838                        // that grant decision as read and propagate it to the
10839                        // update.
10840                        if (sysPs.isPrivileged()) {
10841                            allowed = true;
10842                        }
10843                    } else {
10844                        // The system apk may have been updated with an older
10845                        // version of the one on the data partition, but which
10846                        // granted a new system permission that it didn't have
10847                        // before.  In this case we do want to allow the app to
10848                        // now get the new permission if the ancestral apk is
10849                        // privileged to get it.
10850                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10851                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10852                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10853                                    allowed = true;
10854                                    break;
10855                                }
10856                            }
10857                        }
10858                        // Also if a privileged parent package on the system image or any of
10859                        // its children requested a privileged permission, the updated child
10860                        // packages can also get the permission.
10861                        if (pkg.parentPackage != null) {
10862                            final PackageSetting disabledSysParentPs = mSettings
10863                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10864                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10865                                    && disabledSysParentPs.isPrivileged()) {
10866                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10867                                    allowed = true;
10868                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10869                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10870                                    for (int i = 0; i < count; i++) {
10871                                        PackageParser.Package disabledSysChildPkg =
10872                                                disabledSysParentPs.pkg.childPackages.get(i);
10873                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10874                                                perm)) {
10875                                            allowed = true;
10876                                            break;
10877                                        }
10878                                    }
10879                                }
10880                            }
10881                        }
10882                    }
10883                } else {
10884                    allowed = isPrivilegedApp(pkg);
10885                }
10886            }
10887        }
10888        if (!allowed) {
10889            if (!allowed && (bp.protectionLevel
10890                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10891                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10892                // If this was a previously normal/dangerous permission that got moved
10893                // to a system permission as part of the runtime permission redesign, then
10894                // we still want to blindly grant it to old apps.
10895                allowed = true;
10896            }
10897            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10898                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10899                // If this permission is to be granted to the system installer and
10900                // this app is an installer, then it gets the permission.
10901                allowed = true;
10902            }
10903            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10904                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10905                // If this permission is to be granted to the system verifier and
10906                // this app is a verifier, then it gets the permission.
10907                allowed = true;
10908            }
10909            if (!allowed && (bp.protectionLevel
10910                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10911                    && isSystemApp(pkg)) {
10912                // Any pre-installed system app is allowed to get this permission.
10913                allowed = true;
10914            }
10915            if (!allowed && (bp.protectionLevel
10916                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10917                // For development permissions, a development permission
10918                // is granted only if it was already granted.
10919                allowed = origPermissions.hasInstallPermission(perm);
10920            }
10921            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10922                    && pkg.packageName.equals(mSetupWizardPackage)) {
10923                // If this permission is to be granted to the system setup wizard and
10924                // this app is a setup wizard, then it gets the permission.
10925                allowed = true;
10926            }
10927        }
10928        return allowed;
10929    }
10930
10931    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10932        final int permCount = pkg.requestedPermissions.size();
10933        for (int j = 0; j < permCount; j++) {
10934            String requestedPermission = pkg.requestedPermissions.get(j);
10935            if (permission.equals(requestedPermission)) {
10936                return true;
10937            }
10938        }
10939        return false;
10940    }
10941
10942    final class ActivityIntentResolver
10943            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10944        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10945                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10946            if (!sUserManager.exists(userId)) return null;
10947            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10948                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10949                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10950            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10951                    isEphemeral, userId);
10952        }
10953
10954        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10955                int userId) {
10956            if (!sUserManager.exists(userId)) return null;
10957            mFlags = flags;
10958            return super.queryIntent(intent, resolvedType,
10959                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10960                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10961                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10962        }
10963
10964        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10965                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10966            if (!sUserManager.exists(userId)) return null;
10967            if (packageActivities == null) {
10968                return null;
10969            }
10970            mFlags = flags;
10971            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10972            final boolean vislbleToEphemeral =
10973                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10974            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10975            final int N = packageActivities.size();
10976            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10977                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10978
10979            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10980            for (int i = 0; i < N; ++i) {
10981                intentFilters = packageActivities.get(i).intents;
10982                if (intentFilters != null && intentFilters.size() > 0) {
10983                    PackageParser.ActivityIntentInfo[] array =
10984                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10985                    intentFilters.toArray(array);
10986                    listCut.add(array);
10987                }
10988            }
10989            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10990                    vislbleToEphemeral, isEphemeral, listCut, userId);
10991        }
10992
10993        /**
10994         * Finds a privileged activity that matches the specified activity names.
10995         */
10996        private PackageParser.Activity findMatchingActivity(
10997                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10998            for (PackageParser.Activity sysActivity : activityList) {
10999                if (sysActivity.info.name.equals(activityInfo.name)) {
11000                    return sysActivity;
11001                }
11002                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11003                    return sysActivity;
11004                }
11005                if (sysActivity.info.targetActivity != null) {
11006                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11007                        return sysActivity;
11008                    }
11009                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11010                        return sysActivity;
11011                    }
11012                }
11013            }
11014            return null;
11015        }
11016
11017        public class IterGenerator<E> {
11018            public Iterator<E> generate(ActivityIntentInfo info) {
11019                return null;
11020            }
11021        }
11022
11023        public class ActionIterGenerator extends IterGenerator<String> {
11024            @Override
11025            public Iterator<String> generate(ActivityIntentInfo info) {
11026                return info.actionsIterator();
11027            }
11028        }
11029
11030        public class CategoriesIterGenerator extends IterGenerator<String> {
11031            @Override
11032            public Iterator<String> generate(ActivityIntentInfo info) {
11033                return info.categoriesIterator();
11034            }
11035        }
11036
11037        public class SchemesIterGenerator extends IterGenerator<String> {
11038            @Override
11039            public Iterator<String> generate(ActivityIntentInfo info) {
11040                return info.schemesIterator();
11041            }
11042        }
11043
11044        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11045            @Override
11046            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11047                return info.authoritiesIterator();
11048            }
11049        }
11050
11051        /**
11052         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11053         * MODIFIED. Do not pass in a list that should not be changed.
11054         */
11055        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11056                IterGenerator<T> generator, Iterator<T> searchIterator) {
11057            // loop through the set of actions; every one must be found in the intent filter
11058            while (searchIterator.hasNext()) {
11059                // we must have at least one filter in the list to consider a match
11060                if (intentList.size() == 0) {
11061                    break;
11062                }
11063
11064                final T searchAction = searchIterator.next();
11065
11066                // loop through the set of intent filters
11067                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11068                while (intentIter.hasNext()) {
11069                    final ActivityIntentInfo intentInfo = intentIter.next();
11070                    boolean selectionFound = false;
11071
11072                    // loop through the intent filter's selection criteria; at least one
11073                    // of them must match the searched criteria
11074                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11075                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11076                        final T intentSelection = intentSelectionIter.next();
11077                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11078                            selectionFound = true;
11079                            break;
11080                        }
11081                    }
11082
11083                    // the selection criteria wasn't found in this filter's set; this filter
11084                    // is not a potential match
11085                    if (!selectionFound) {
11086                        intentIter.remove();
11087                    }
11088                }
11089            }
11090        }
11091
11092        private boolean isProtectedAction(ActivityIntentInfo filter) {
11093            final Iterator<String> actionsIter = filter.actionsIterator();
11094            while (actionsIter != null && actionsIter.hasNext()) {
11095                final String filterAction = actionsIter.next();
11096                if (PROTECTED_ACTIONS.contains(filterAction)) {
11097                    return true;
11098                }
11099            }
11100            return false;
11101        }
11102
11103        /**
11104         * Adjusts the priority of the given intent filter according to policy.
11105         * <p>
11106         * <ul>
11107         * <li>The priority for non privileged applications is capped to '0'</li>
11108         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11109         * <li>The priority for unbundled updates to privileged applications is capped to the
11110         *      priority defined on the system partition</li>
11111         * </ul>
11112         * <p>
11113         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11114         * allowed to obtain any priority on any action.
11115         */
11116        private void adjustPriority(
11117                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11118            // nothing to do; priority is fine as-is
11119            if (intent.getPriority() <= 0) {
11120                return;
11121            }
11122
11123            final ActivityInfo activityInfo = intent.activity.info;
11124            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11125
11126            final boolean privilegedApp =
11127                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11128            if (!privilegedApp) {
11129                // non-privileged applications can never define a priority >0
11130                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11131                        + " package: " + applicationInfo.packageName
11132                        + " activity: " + intent.activity.className
11133                        + " origPrio: " + intent.getPriority());
11134                intent.setPriority(0);
11135                return;
11136            }
11137
11138            if (systemActivities == null) {
11139                // the system package is not disabled; we're parsing the system partition
11140                if (isProtectedAction(intent)) {
11141                    if (mDeferProtectedFilters) {
11142                        // We can't deal with these just yet. No component should ever obtain a
11143                        // >0 priority for a protected actions, with ONE exception -- the setup
11144                        // wizard. The setup wizard, however, cannot be known until we're able to
11145                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11146                        // until all intent filters have been processed. Chicken, meet egg.
11147                        // Let the filter temporarily have a high priority and rectify the
11148                        // priorities after all system packages have been scanned.
11149                        mProtectedFilters.add(intent);
11150                        if (DEBUG_FILTERS) {
11151                            Slog.i(TAG, "Protected action; save for later;"
11152                                    + " package: " + applicationInfo.packageName
11153                                    + " activity: " + intent.activity.className
11154                                    + " origPrio: " + intent.getPriority());
11155                        }
11156                        return;
11157                    } else {
11158                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11159                            Slog.i(TAG, "No setup wizard;"
11160                                + " All protected intents capped to priority 0");
11161                        }
11162                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11163                            if (DEBUG_FILTERS) {
11164                                Slog.i(TAG, "Found setup wizard;"
11165                                    + " allow priority " + intent.getPriority() + ";"
11166                                    + " package: " + intent.activity.info.packageName
11167                                    + " activity: " + intent.activity.className
11168                                    + " priority: " + intent.getPriority());
11169                            }
11170                            // setup wizard gets whatever it wants
11171                            return;
11172                        }
11173                        Slog.w(TAG, "Protected action; cap priority to 0;"
11174                                + " package: " + intent.activity.info.packageName
11175                                + " activity: " + intent.activity.className
11176                                + " origPrio: " + intent.getPriority());
11177                        intent.setPriority(0);
11178                        return;
11179                    }
11180                }
11181                // privileged apps on the system image get whatever priority they request
11182                return;
11183            }
11184
11185            // privileged app unbundled update ... try to find the same activity
11186            final PackageParser.Activity foundActivity =
11187                    findMatchingActivity(systemActivities, activityInfo);
11188            if (foundActivity == null) {
11189                // this is a new activity; it cannot obtain >0 priority
11190                if (DEBUG_FILTERS) {
11191                    Slog.i(TAG, "New activity; cap priority to 0;"
11192                            + " package: " + applicationInfo.packageName
11193                            + " activity: " + intent.activity.className
11194                            + " origPrio: " + intent.getPriority());
11195                }
11196                intent.setPriority(0);
11197                return;
11198            }
11199
11200            // found activity, now check for filter equivalence
11201
11202            // a shallow copy is enough; we modify the list, not its contents
11203            final List<ActivityIntentInfo> intentListCopy =
11204                    new ArrayList<>(foundActivity.intents);
11205            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11206
11207            // find matching action subsets
11208            final Iterator<String> actionsIterator = intent.actionsIterator();
11209            if (actionsIterator != null) {
11210                getIntentListSubset(
11211                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11212                if (intentListCopy.size() == 0) {
11213                    // no more intents to match; we're not equivalent
11214                    if (DEBUG_FILTERS) {
11215                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11216                                + " package: " + applicationInfo.packageName
11217                                + " activity: " + intent.activity.className
11218                                + " origPrio: " + intent.getPriority());
11219                    }
11220                    intent.setPriority(0);
11221                    return;
11222                }
11223            }
11224
11225            // find matching category subsets
11226            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11227            if (categoriesIterator != null) {
11228                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11229                        categoriesIterator);
11230                if (intentListCopy.size() == 0) {
11231                    // no more intents to match; we're not equivalent
11232                    if (DEBUG_FILTERS) {
11233                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11234                                + " package: " + applicationInfo.packageName
11235                                + " activity: " + intent.activity.className
11236                                + " origPrio: " + intent.getPriority());
11237                    }
11238                    intent.setPriority(0);
11239                    return;
11240                }
11241            }
11242
11243            // find matching schemes subsets
11244            final Iterator<String> schemesIterator = intent.schemesIterator();
11245            if (schemesIterator != null) {
11246                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11247                        schemesIterator);
11248                if (intentListCopy.size() == 0) {
11249                    // no more intents to match; we're not equivalent
11250                    if (DEBUG_FILTERS) {
11251                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11252                                + " package: " + applicationInfo.packageName
11253                                + " activity: " + intent.activity.className
11254                                + " origPrio: " + intent.getPriority());
11255                    }
11256                    intent.setPriority(0);
11257                    return;
11258                }
11259            }
11260
11261            // find matching authorities subsets
11262            final Iterator<IntentFilter.AuthorityEntry>
11263                    authoritiesIterator = intent.authoritiesIterator();
11264            if (authoritiesIterator != null) {
11265                getIntentListSubset(intentListCopy,
11266                        new AuthoritiesIterGenerator(),
11267                        authoritiesIterator);
11268                if (intentListCopy.size() == 0) {
11269                    // no more intents to match; we're not equivalent
11270                    if (DEBUG_FILTERS) {
11271                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11272                                + " package: " + applicationInfo.packageName
11273                                + " activity: " + intent.activity.className
11274                                + " origPrio: " + intent.getPriority());
11275                    }
11276                    intent.setPriority(0);
11277                    return;
11278                }
11279            }
11280
11281            // we found matching filter(s); app gets the max priority of all intents
11282            int cappedPriority = 0;
11283            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11284                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11285            }
11286            if (intent.getPriority() > cappedPriority) {
11287                if (DEBUG_FILTERS) {
11288                    Slog.i(TAG, "Found matching filter(s);"
11289                            + " cap priority to " + cappedPriority + ";"
11290                            + " package: " + applicationInfo.packageName
11291                            + " activity: " + intent.activity.className
11292                            + " origPrio: " + intent.getPriority());
11293                }
11294                intent.setPriority(cappedPriority);
11295                return;
11296            }
11297            // all this for nothing; the requested priority was <= what was on the system
11298        }
11299
11300        public final void addActivity(PackageParser.Activity a, String type) {
11301            mActivities.put(a.getComponentName(), a);
11302            if (DEBUG_SHOW_INFO)
11303                Log.v(
11304                TAG, "  " + type + " " +
11305                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11306            if (DEBUG_SHOW_INFO)
11307                Log.v(TAG, "    Class=" + a.info.name);
11308            final int NI = a.intents.size();
11309            for (int j=0; j<NI; j++) {
11310                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11311                if ("activity".equals(type)) {
11312                    final PackageSetting ps =
11313                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11314                    final List<PackageParser.Activity> systemActivities =
11315                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11316                    adjustPriority(systemActivities, intent);
11317                }
11318                if (DEBUG_SHOW_INFO) {
11319                    Log.v(TAG, "    IntentFilter:");
11320                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11321                }
11322                if (!intent.debugCheck()) {
11323                    Log.w(TAG, "==> For Activity " + a.info.name);
11324                }
11325                addFilter(intent);
11326            }
11327        }
11328
11329        public final void removeActivity(PackageParser.Activity a, String type) {
11330            mActivities.remove(a.getComponentName());
11331            if (DEBUG_SHOW_INFO) {
11332                Log.v(TAG, "  " + type + " "
11333                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11334                                : a.info.name) + ":");
11335                Log.v(TAG, "    Class=" + a.info.name);
11336            }
11337            final int NI = a.intents.size();
11338            for (int j=0; j<NI; j++) {
11339                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11340                if (DEBUG_SHOW_INFO) {
11341                    Log.v(TAG, "    IntentFilter:");
11342                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11343                }
11344                removeFilter(intent);
11345            }
11346        }
11347
11348        @Override
11349        protected boolean allowFilterResult(
11350                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11351            ActivityInfo filterAi = filter.activity.info;
11352            for (int i=dest.size()-1; i>=0; i--) {
11353                ActivityInfo destAi = dest.get(i).activityInfo;
11354                if (destAi.name == filterAi.name
11355                        && destAi.packageName == filterAi.packageName) {
11356                    return false;
11357                }
11358            }
11359            return true;
11360        }
11361
11362        @Override
11363        protected ActivityIntentInfo[] newArray(int size) {
11364            return new ActivityIntentInfo[size];
11365        }
11366
11367        @Override
11368        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11369            if (!sUserManager.exists(userId)) return true;
11370            PackageParser.Package p = filter.activity.owner;
11371            if (p != null) {
11372                PackageSetting ps = (PackageSetting)p.mExtras;
11373                if (ps != null) {
11374                    // System apps are never considered stopped for purposes of
11375                    // filtering, because there may be no way for the user to
11376                    // actually re-launch them.
11377                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11378                            && ps.getStopped(userId);
11379                }
11380            }
11381            return false;
11382        }
11383
11384        @Override
11385        protected boolean isPackageForFilter(String packageName,
11386                PackageParser.ActivityIntentInfo info) {
11387            return packageName.equals(info.activity.owner.packageName);
11388        }
11389
11390        @Override
11391        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11392                int match, int userId) {
11393            if (!sUserManager.exists(userId)) return null;
11394            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11395                return null;
11396            }
11397            final PackageParser.Activity activity = info.activity;
11398            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11399            if (ps == null) {
11400                return null;
11401            }
11402            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11403                    ps.readUserState(userId), userId);
11404            if (ai == null) {
11405                return null;
11406            }
11407            final ResolveInfo res = new ResolveInfo();
11408            res.activityInfo = ai;
11409            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11410                res.filter = info;
11411            }
11412            if (info != null) {
11413                res.handleAllWebDataURI = info.handleAllWebDataURI();
11414            }
11415            res.priority = info.getPriority();
11416            res.preferredOrder = activity.owner.mPreferredOrder;
11417            //System.out.println("Result: " + res.activityInfo.className +
11418            //                   " = " + res.priority);
11419            res.match = match;
11420            res.isDefault = info.hasDefault;
11421            res.labelRes = info.labelRes;
11422            res.nonLocalizedLabel = info.nonLocalizedLabel;
11423            if (userNeedsBadging(userId)) {
11424                res.noResourceId = true;
11425            } else {
11426                res.icon = info.icon;
11427            }
11428            res.iconResourceId = info.icon;
11429            res.system = res.activityInfo.applicationInfo.isSystemApp();
11430            return res;
11431        }
11432
11433        @Override
11434        protected void sortResults(List<ResolveInfo> results) {
11435            Collections.sort(results, mResolvePrioritySorter);
11436        }
11437
11438        @Override
11439        protected void dumpFilter(PrintWriter out, String prefix,
11440                PackageParser.ActivityIntentInfo filter) {
11441            out.print(prefix); out.print(
11442                    Integer.toHexString(System.identityHashCode(filter.activity)));
11443                    out.print(' ');
11444                    filter.activity.printComponentShortName(out);
11445                    out.print(" filter ");
11446                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11447        }
11448
11449        @Override
11450        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11451            return filter.activity;
11452        }
11453
11454        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11455            PackageParser.Activity activity = (PackageParser.Activity)label;
11456            out.print(prefix); out.print(
11457                    Integer.toHexString(System.identityHashCode(activity)));
11458                    out.print(' ');
11459                    activity.printComponentShortName(out);
11460            if (count > 1) {
11461                out.print(" ("); out.print(count); out.print(" filters)");
11462            }
11463            out.println();
11464        }
11465
11466        // Keys are String (activity class name), values are Activity.
11467        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11468                = new ArrayMap<ComponentName, PackageParser.Activity>();
11469        private int mFlags;
11470    }
11471
11472    private final class ServiceIntentResolver
11473            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11474        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11475                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11476            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11477            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11478                    isEphemeral, userId);
11479        }
11480
11481        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11482                int userId) {
11483            if (!sUserManager.exists(userId)) return null;
11484            mFlags = flags;
11485            return super.queryIntent(intent, resolvedType,
11486                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11487                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11488                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11489        }
11490
11491        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11492                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11493            if (!sUserManager.exists(userId)) return null;
11494            if (packageServices == null) {
11495                return null;
11496            }
11497            mFlags = flags;
11498            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11499            final boolean vislbleToEphemeral =
11500                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11501            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11502            final int N = packageServices.size();
11503            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11504                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11505
11506            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11507            for (int i = 0; i < N; ++i) {
11508                intentFilters = packageServices.get(i).intents;
11509                if (intentFilters != null && intentFilters.size() > 0) {
11510                    PackageParser.ServiceIntentInfo[] array =
11511                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11512                    intentFilters.toArray(array);
11513                    listCut.add(array);
11514                }
11515            }
11516            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11517                    vislbleToEphemeral, isEphemeral, listCut, userId);
11518        }
11519
11520        public final void addService(PackageParser.Service s) {
11521            mServices.put(s.getComponentName(), s);
11522            if (DEBUG_SHOW_INFO) {
11523                Log.v(TAG, "  "
11524                        + (s.info.nonLocalizedLabel != null
11525                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11526                Log.v(TAG, "    Class=" + s.info.name);
11527            }
11528            final int NI = s.intents.size();
11529            int j;
11530            for (j=0; j<NI; j++) {
11531                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11532                if (DEBUG_SHOW_INFO) {
11533                    Log.v(TAG, "    IntentFilter:");
11534                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11535                }
11536                if (!intent.debugCheck()) {
11537                    Log.w(TAG, "==> For Service " + s.info.name);
11538                }
11539                addFilter(intent);
11540            }
11541        }
11542
11543        public final void removeService(PackageParser.Service s) {
11544            mServices.remove(s.getComponentName());
11545            if (DEBUG_SHOW_INFO) {
11546                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11547                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11548                Log.v(TAG, "    Class=" + s.info.name);
11549            }
11550            final int NI = s.intents.size();
11551            int j;
11552            for (j=0; j<NI; j++) {
11553                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11554                if (DEBUG_SHOW_INFO) {
11555                    Log.v(TAG, "    IntentFilter:");
11556                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11557                }
11558                removeFilter(intent);
11559            }
11560        }
11561
11562        @Override
11563        protected boolean allowFilterResult(
11564                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11565            ServiceInfo filterSi = filter.service.info;
11566            for (int i=dest.size()-1; i>=0; i--) {
11567                ServiceInfo destAi = dest.get(i).serviceInfo;
11568                if (destAi.name == filterSi.name
11569                        && destAi.packageName == filterSi.packageName) {
11570                    return false;
11571                }
11572            }
11573            return true;
11574        }
11575
11576        @Override
11577        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11578            return new PackageParser.ServiceIntentInfo[size];
11579        }
11580
11581        @Override
11582        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11583            if (!sUserManager.exists(userId)) return true;
11584            PackageParser.Package p = filter.service.owner;
11585            if (p != null) {
11586                PackageSetting ps = (PackageSetting)p.mExtras;
11587                if (ps != null) {
11588                    // System apps are never considered stopped for purposes of
11589                    // filtering, because there may be no way for the user to
11590                    // actually re-launch them.
11591                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11592                            && ps.getStopped(userId);
11593                }
11594            }
11595            return false;
11596        }
11597
11598        @Override
11599        protected boolean isPackageForFilter(String packageName,
11600                PackageParser.ServiceIntentInfo info) {
11601            return packageName.equals(info.service.owner.packageName);
11602        }
11603
11604        @Override
11605        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11606                int match, int userId) {
11607            if (!sUserManager.exists(userId)) return null;
11608            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11609            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11610                return null;
11611            }
11612            final PackageParser.Service service = info.service;
11613            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11614            if (ps == null) {
11615                return null;
11616            }
11617            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11618                    ps.readUserState(userId), userId);
11619            if (si == null) {
11620                return null;
11621            }
11622            final ResolveInfo res = new ResolveInfo();
11623            res.serviceInfo = si;
11624            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11625                res.filter = filter;
11626            }
11627            res.priority = info.getPriority();
11628            res.preferredOrder = service.owner.mPreferredOrder;
11629            res.match = match;
11630            res.isDefault = info.hasDefault;
11631            res.labelRes = info.labelRes;
11632            res.nonLocalizedLabel = info.nonLocalizedLabel;
11633            res.icon = info.icon;
11634            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11635            return res;
11636        }
11637
11638        @Override
11639        protected void sortResults(List<ResolveInfo> results) {
11640            Collections.sort(results, mResolvePrioritySorter);
11641        }
11642
11643        @Override
11644        protected void dumpFilter(PrintWriter out, String prefix,
11645                PackageParser.ServiceIntentInfo filter) {
11646            out.print(prefix); out.print(
11647                    Integer.toHexString(System.identityHashCode(filter.service)));
11648                    out.print(' ');
11649                    filter.service.printComponentShortName(out);
11650                    out.print(" filter ");
11651                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11652        }
11653
11654        @Override
11655        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11656            return filter.service;
11657        }
11658
11659        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11660            PackageParser.Service service = (PackageParser.Service)label;
11661            out.print(prefix); out.print(
11662                    Integer.toHexString(System.identityHashCode(service)));
11663                    out.print(' ');
11664                    service.printComponentShortName(out);
11665            if (count > 1) {
11666                out.print(" ("); out.print(count); out.print(" filters)");
11667            }
11668            out.println();
11669        }
11670
11671//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11672//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11673//            final List<ResolveInfo> retList = Lists.newArrayList();
11674//            while (i.hasNext()) {
11675//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11676//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11677//                    retList.add(resolveInfo);
11678//                }
11679//            }
11680//            return retList;
11681//        }
11682
11683        // Keys are String (activity class name), values are Activity.
11684        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11685                = new ArrayMap<ComponentName, PackageParser.Service>();
11686        private int mFlags;
11687    }
11688
11689    private final class ProviderIntentResolver
11690            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11691        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11692                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11693            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11694            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11695                    isEphemeral, userId);
11696        }
11697
11698        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11699                int userId) {
11700            if (!sUserManager.exists(userId))
11701                return null;
11702            mFlags = flags;
11703            return super.queryIntent(intent, resolvedType,
11704                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11705                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11706                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11707        }
11708
11709        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11710                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11711            if (!sUserManager.exists(userId))
11712                return null;
11713            if (packageProviders == null) {
11714                return null;
11715            }
11716            mFlags = flags;
11717            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11718            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11719            final boolean vislbleToEphemeral =
11720                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11721            final int N = packageProviders.size();
11722            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11723                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11724
11725            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11726            for (int i = 0; i < N; ++i) {
11727                intentFilters = packageProviders.get(i).intents;
11728                if (intentFilters != null && intentFilters.size() > 0) {
11729                    PackageParser.ProviderIntentInfo[] array =
11730                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11731                    intentFilters.toArray(array);
11732                    listCut.add(array);
11733                }
11734            }
11735            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11736                    vislbleToEphemeral, isEphemeral, listCut, userId);
11737        }
11738
11739        public final void addProvider(PackageParser.Provider p) {
11740            if (mProviders.containsKey(p.getComponentName())) {
11741                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11742                return;
11743            }
11744
11745            mProviders.put(p.getComponentName(), p);
11746            if (DEBUG_SHOW_INFO) {
11747                Log.v(TAG, "  "
11748                        + (p.info.nonLocalizedLabel != null
11749                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11750                Log.v(TAG, "    Class=" + p.info.name);
11751            }
11752            final int NI = p.intents.size();
11753            int j;
11754            for (j = 0; j < NI; j++) {
11755                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11756                if (DEBUG_SHOW_INFO) {
11757                    Log.v(TAG, "    IntentFilter:");
11758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11759                }
11760                if (!intent.debugCheck()) {
11761                    Log.w(TAG, "==> For Provider " + p.info.name);
11762                }
11763                addFilter(intent);
11764            }
11765        }
11766
11767        public final void removeProvider(PackageParser.Provider p) {
11768            mProviders.remove(p.getComponentName());
11769            if (DEBUG_SHOW_INFO) {
11770                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11771                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11772                Log.v(TAG, "    Class=" + p.info.name);
11773            }
11774            final int NI = p.intents.size();
11775            int j;
11776            for (j = 0; j < NI; j++) {
11777                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11778                if (DEBUG_SHOW_INFO) {
11779                    Log.v(TAG, "    IntentFilter:");
11780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11781                }
11782                removeFilter(intent);
11783            }
11784        }
11785
11786        @Override
11787        protected boolean allowFilterResult(
11788                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11789            ProviderInfo filterPi = filter.provider.info;
11790            for (int i = dest.size() - 1; i >= 0; i--) {
11791                ProviderInfo destPi = dest.get(i).providerInfo;
11792                if (destPi.name == filterPi.name
11793                        && destPi.packageName == filterPi.packageName) {
11794                    return false;
11795                }
11796            }
11797            return true;
11798        }
11799
11800        @Override
11801        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11802            return new PackageParser.ProviderIntentInfo[size];
11803        }
11804
11805        @Override
11806        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11807            if (!sUserManager.exists(userId))
11808                return true;
11809            PackageParser.Package p = filter.provider.owner;
11810            if (p != null) {
11811                PackageSetting ps = (PackageSetting) p.mExtras;
11812                if (ps != null) {
11813                    // System apps are never considered stopped for purposes of
11814                    // filtering, because there may be no way for the user to
11815                    // actually re-launch them.
11816                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11817                            && ps.getStopped(userId);
11818                }
11819            }
11820            return false;
11821        }
11822
11823        @Override
11824        protected boolean isPackageForFilter(String packageName,
11825                PackageParser.ProviderIntentInfo info) {
11826            return packageName.equals(info.provider.owner.packageName);
11827        }
11828
11829        @Override
11830        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11831                int match, int userId) {
11832            if (!sUserManager.exists(userId))
11833                return null;
11834            final PackageParser.ProviderIntentInfo info = filter;
11835            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11836                return null;
11837            }
11838            final PackageParser.Provider provider = info.provider;
11839            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11840            if (ps == null) {
11841                return null;
11842            }
11843            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11844                    ps.readUserState(userId), userId);
11845            if (pi == null) {
11846                return null;
11847            }
11848            final ResolveInfo res = new ResolveInfo();
11849            res.providerInfo = pi;
11850            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11851                res.filter = filter;
11852            }
11853            res.priority = info.getPriority();
11854            res.preferredOrder = provider.owner.mPreferredOrder;
11855            res.match = match;
11856            res.isDefault = info.hasDefault;
11857            res.labelRes = info.labelRes;
11858            res.nonLocalizedLabel = info.nonLocalizedLabel;
11859            res.icon = info.icon;
11860            res.system = res.providerInfo.applicationInfo.isSystemApp();
11861            return res;
11862        }
11863
11864        @Override
11865        protected void sortResults(List<ResolveInfo> results) {
11866            Collections.sort(results, mResolvePrioritySorter);
11867        }
11868
11869        @Override
11870        protected void dumpFilter(PrintWriter out, String prefix,
11871                PackageParser.ProviderIntentInfo filter) {
11872            out.print(prefix);
11873            out.print(
11874                    Integer.toHexString(System.identityHashCode(filter.provider)));
11875            out.print(' ');
11876            filter.provider.printComponentShortName(out);
11877            out.print(" filter ");
11878            out.println(Integer.toHexString(System.identityHashCode(filter)));
11879        }
11880
11881        @Override
11882        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11883            return filter.provider;
11884        }
11885
11886        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11887            PackageParser.Provider provider = (PackageParser.Provider)label;
11888            out.print(prefix); out.print(
11889                    Integer.toHexString(System.identityHashCode(provider)));
11890                    out.print(' ');
11891                    provider.printComponentShortName(out);
11892            if (count > 1) {
11893                out.print(" ("); out.print(count); out.print(" filters)");
11894            }
11895            out.println();
11896        }
11897
11898        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11899                = new ArrayMap<ComponentName, PackageParser.Provider>();
11900        private int mFlags;
11901    }
11902
11903    static final class EphemeralIntentResolver
11904            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11905        /**
11906         * The result that has the highest defined order. Ordering applies on a
11907         * per-package basis. Mapping is from package name to Pair of order and
11908         * EphemeralResolveInfo.
11909         * <p>
11910         * NOTE: This is implemented as a field variable for convenience and efficiency.
11911         * By having a field variable, we're able to track filter ordering as soon as
11912         * a non-zero order is defined. Otherwise, multiple loops across the result set
11913         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11914         * this needs to be contained entirely within {@link #filterResults()}.
11915         */
11916        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11917
11918        @Override
11919        protected EphemeralResponse[] newArray(int size) {
11920            return new EphemeralResponse[size];
11921        }
11922
11923        @Override
11924        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11925            return true;
11926        }
11927
11928        @Override
11929        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11930                int userId) {
11931            if (!sUserManager.exists(userId)) {
11932                return null;
11933            }
11934            final String packageName = responseObj.resolveInfo.getPackageName();
11935            final Integer order = responseObj.getOrder();
11936            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11937                    mOrderResult.get(packageName);
11938            // ordering is enabled and this item's order isn't high enough
11939            if (lastOrderResult != null && lastOrderResult.first >= order) {
11940                return null;
11941            }
11942            final EphemeralResolveInfo res = responseObj.resolveInfo;
11943            if (order > 0) {
11944                // non-zero order, enable ordering
11945                mOrderResult.put(packageName, new Pair<>(order, res));
11946            }
11947            return responseObj;
11948        }
11949
11950        @Override
11951        protected void filterResults(List<EphemeralResponse> results) {
11952            // only do work if ordering is enabled [most of the time it won't be]
11953            if (mOrderResult.size() == 0) {
11954                return;
11955            }
11956            int resultSize = results.size();
11957            for (int i = 0; i < resultSize; i++) {
11958                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11959                final String packageName = info.getPackageName();
11960                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11961                if (savedInfo == null) {
11962                    // package doesn't having ordering
11963                    continue;
11964                }
11965                if (savedInfo.second == info) {
11966                    // circled back to the highest ordered item; remove from order list
11967                    mOrderResult.remove(savedInfo);
11968                    if (mOrderResult.size() == 0) {
11969                        // no more ordered items
11970                        break;
11971                    }
11972                    continue;
11973                }
11974                // item has a worse order, remove it from the result list
11975                results.remove(i);
11976                resultSize--;
11977                i--;
11978            }
11979        }
11980    }
11981
11982    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11983            new Comparator<ResolveInfo>() {
11984        public int compare(ResolveInfo r1, ResolveInfo r2) {
11985            int v1 = r1.priority;
11986            int v2 = r2.priority;
11987            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11988            if (v1 != v2) {
11989                return (v1 > v2) ? -1 : 1;
11990            }
11991            v1 = r1.preferredOrder;
11992            v2 = r2.preferredOrder;
11993            if (v1 != v2) {
11994                return (v1 > v2) ? -1 : 1;
11995            }
11996            if (r1.isDefault != r2.isDefault) {
11997                return r1.isDefault ? -1 : 1;
11998            }
11999            v1 = r1.match;
12000            v2 = r2.match;
12001            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12002            if (v1 != v2) {
12003                return (v1 > v2) ? -1 : 1;
12004            }
12005            if (r1.system != r2.system) {
12006                return r1.system ? -1 : 1;
12007            }
12008            if (r1.activityInfo != null) {
12009                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12010            }
12011            if (r1.serviceInfo != null) {
12012                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12013            }
12014            if (r1.providerInfo != null) {
12015                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12016            }
12017            return 0;
12018        }
12019    };
12020
12021    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12022            new Comparator<ProviderInfo>() {
12023        public int compare(ProviderInfo p1, ProviderInfo p2) {
12024            final int v1 = p1.initOrder;
12025            final int v2 = p2.initOrder;
12026            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12027        }
12028    };
12029
12030    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12031            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12032            final int[] userIds) {
12033        mHandler.post(new Runnable() {
12034            @Override
12035            public void run() {
12036                try {
12037                    final IActivityManager am = ActivityManager.getService();
12038                    if (am == null) return;
12039                    final int[] resolvedUserIds;
12040                    if (userIds == null) {
12041                        resolvedUserIds = am.getRunningUserIds();
12042                    } else {
12043                        resolvedUserIds = userIds;
12044                    }
12045                    for (int id : resolvedUserIds) {
12046                        final Intent intent = new Intent(action,
12047                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12048                        if (extras != null) {
12049                            intent.putExtras(extras);
12050                        }
12051                        if (targetPkg != null) {
12052                            intent.setPackage(targetPkg);
12053                        }
12054                        // Modify the UID when posting to other users
12055                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12056                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12057                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12058                            intent.putExtra(Intent.EXTRA_UID, uid);
12059                        }
12060                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12061                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12062                        if (DEBUG_BROADCASTS) {
12063                            RuntimeException here = new RuntimeException("here");
12064                            here.fillInStackTrace();
12065                            Slog.d(TAG, "Sending to user " + id + ": "
12066                                    + intent.toShortString(false, true, false, false)
12067                                    + " " + intent.getExtras(), here);
12068                        }
12069                        am.broadcastIntent(null, intent, null, finishedReceiver,
12070                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12071                                null, finishedReceiver != null, false, id);
12072                    }
12073                } catch (RemoteException ex) {
12074                }
12075            }
12076        });
12077    }
12078
12079    /**
12080     * Check if the external storage media is available. This is true if there
12081     * is a mounted external storage medium or if the external storage is
12082     * emulated.
12083     */
12084    private boolean isExternalMediaAvailable() {
12085        return mMediaMounted || Environment.isExternalStorageEmulated();
12086    }
12087
12088    @Override
12089    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12090        // writer
12091        synchronized (mPackages) {
12092            if (!isExternalMediaAvailable()) {
12093                // If the external storage is no longer mounted at this point,
12094                // the caller may not have been able to delete all of this
12095                // packages files and can not delete any more.  Bail.
12096                return null;
12097            }
12098            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12099            if (lastPackage != null) {
12100                pkgs.remove(lastPackage);
12101            }
12102            if (pkgs.size() > 0) {
12103                return pkgs.get(0);
12104            }
12105        }
12106        return null;
12107    }
12108
12109    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12110        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12111                userId, andCode ? 1 : 0, packageName);
12112        if (mSystemReady) {
12113            msg.sendToTarget();
12114        } else {
12115            if (mPostSystemReadyMessages == null) {
12116                mPostSystemReadyMessages = new ArrayList<>();
12117            }
12118            mPostSystemReadyMessages.add(msg);
12119        }
12120    }
12121
12122    void startCleaningPackages() {
12123        // reader
12124        if (!isExternalMediaAvailable()) {
12125            return;
12126        }
12127        synchronized (mPackages) {
12128            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12129                return;
12130            }
12131        }
12132        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12133        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12134        IActivityManager am = ActivityManager.getService();
12135        if (am != null) {
12136            try {
12137                am.startService(null, intent, null, mContext.getOpPackageName(),
12138                        UserHandle.USER_SYSTEM);
12139            } catch (RemoteException e) {
12140            }
12141        }
12142    }
12143
12144    @Override
12145    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12146            int installFlags, String installerPackageName, int userId) {
12147        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12148
12149        final int callingUid = Binder.getCallingUid();
12150        enforceCrossUserPermission(callingUid, userId,
12151                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12152
12153        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12154            try {
12155                if (observer != null) {
12156                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12157                }
12158            } catch (RemoteException re) {
12159            }
12160            return;
12161        }
12162
12163        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12164            installFlags |= PackageManager.INSTALL_FROM_ADB;
12165
12166        } else {
12167            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12168            // about installerPackageName.
12169
12170            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12171            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12172        }
12173
12174        UserHandle user;
12175        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12176            user = UserHandle.ALL;
12177        } else {
12178            user = new UserHandle(userId);
12179        }
12180
12181        // Only system components can circumvent runtime permissions when installing.
12182        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12183                && mContext.checkCallingOrSelfPermission(Manifest.permission
12184                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12185            throw new SecurityException("You need the "
12186                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12187                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12188        }
12189
12190        final File originFile = new File(originPath);
12191        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12192
12193        final Message msg = mHandler.obtainMessage(INIT_COPY);
12194        final VerificationInfo verificationInfo = new VerificationInfo(
12195                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12196        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12197                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12198                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12199                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12200        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12201        msg.obj = params;
12202
12203        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12204                System.identityHashCode(msg.obj));
12205        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12206                System.identityHashCode(msg.obj));
12207
12208        mHandler.sendMessage(msg);
12209    }
12210
12211    void installStage(String packageName, File stagedDir, String stagedCid,
12212            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12213            String installerPackageName, int installerUid, UserHandle user,
12214            Certificate[][] certificates) {
12215        if (DEBUG_EPHEMERAL) {
12216            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12217                Slog.d(TAG, "Ephemeral install of " + packageName);
12218            }
12219        }
12220        final VerificationInfo verificationInfo = new VerificationInfo(
12221                sessionParams.originatingUri, sessionParams.referrerUri,
12222                sessionParams.originatingUid, installerUid);
12223
12224        final OriginInfo origin;
12225        if (stagedDir != null) {
12226            origin = OriginInfo.fromStagedFile(stagedDir);
12227        } else {
12228            origin = OriginInfo.fromStagedContainer(stagedCid);
12229        }
12230
12231        final Message msg = mHandler.obtainMessage(INIT_COPY);
12232        final InstallParams params = new InstallParams(origin, null, observer,
12233                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12234                verificationInfo, user, sessionParams.abiOverride,
12235                sessionParams.grantedRuntimePermissions, certificates, sessionParams.installReason);
12236        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12237        msg.obj = params;
12238
12239        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12240                System.identityHashCode(msg.obj));
12241        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12242                System.identityHashCode(msg.obj));
12243
12244        mHandler.sendMessage(msg);
12245    }
12246
12247    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12248            int userId) {
12249        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12250        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12251    }
12252
12253    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12254            int appId, int... userIds) {
12255        if (ArrayUtils.isEmpty(userIds)) {
12256            return;
12257        }
12258        Bundle extras = new Bundle(1);
12259        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12260        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12261
12262        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12263                packageName, extras, 0, null, null, userIds);
12264        if (isSystem) {
12265            mHandler.post(() -> {
12266                        for (int userId : userIds) {
12267                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12268                        }
12269                    }
12270            );
12271        }
12272    }
12273
12274    /**
12275     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12276     * automatically without needing an explicit launch.
12277     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12278     */
12279    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12280        // If user is not running, the app didn't miss any broadcast
12281        if (!mUserManagerInternal.isUserRunning(userId)) {
12282            return;
12283        }
12284        final IActivityManager am = ActivityManager.getService();
12285        try {
12286            // Deliver LOCKED_BOOT_COMPLETED first
12287            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12288                    .setPackage(packageName);
12289            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12290            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12291                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12292
12293            // Deliver BOOT_COMPLETED only if user is unlocked
12294            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12295                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12296                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12297                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12298            }
12299        } catch (RemoteException e) {
12300            throw e.rethrowFromSystemServer();
12301        }
12302    }
12303
12304    @Override
12305    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12306            int userId) {
12307        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12308        PackageSetting pkgSetting;
12309        final int uid = Binder.getCallingUid();
12310        enforceCrossUserPermission(uid, userId,
12311                true /* requireFullPermission */, true /* checkShell */,
12312                "setApplicationHiddenSetting for user " + userId);
12313
12314        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12315            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12316            return false;
12317        }
12318
12319        long callingId = Binder.clearCallingIdentity();
12320        try {
12321            boolean sendAdded = false;
12322            boolean sendRemoved = false;
12323            // writer
12324            synchronized (mPackages) {
12325                pkgSetting = mSettings.mPackages.get(packageName);
12326                if (pkgSetting == null) {
12327                    return false;
12328                }
12329                // Do not allow "android" is being disabled
12330                if ("android".equals(packageName)) {
12331                    Slog.w(TAG, "Cannot hide package: android");
12332                    return false;
12333                }
12334                // Only allow protected packages to hide themselves.
12335                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12336                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12337                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12338                    return false;
12339                }
12340
12341                if (pkgSetting.getHidden(userId) != hidden) {
12342                    pkgSetting.setHidden(hidden, userId);
12343                    mSettings.writePackageRestrictionsLPr(userId);
12344                    if (hidden) {
12345                        sendRemoved = true;
12346                    } else {
12347                        sendAdded = true;
12348                    }
12349                }
12350            }
12351            if (sendAdded) {
12352                sendPackageAddedForUser(packageName, pkgSetting, userId);
12353                return true;
12354            }
12355            if (sendRemoved) {
12356                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12357                        "hiding pkg");
12358                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12359                return true;
12360            }
12361        } finally {
12362            Binder.restoreCallingIdentity(callingId);
12363        }
12364        return false;
12365    }
12366
12367    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12368            int userId) {
12369        final PackageRemovedInfo info = new PackageRemovedInfo();
12370        info.removedPackage = packageName;
12371        info.removedUsers = new int[] {userId};
12372        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12373        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12374    }
12375
12376    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12377        if (pkgList.length > 0) {
12378            Bundle extras = new Bundle(1);
12379            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12380
12381            sendPackageBroadcast(
12382                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12383                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12384                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12385                    new int[] {userId});
12386        }
12387    }
12388
12389    /**
12390     * Returns true if application is not found or there was an error. Otherwise it returns
12391     * the hidden state of the package for the given user.
12392     */
12393    @Override
12394    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12395        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12397                true /* requireFullPermission */, false /* checkShell */,
12398                "getApplicationHidden for user " + userId);
12399        PackageSetting pkgSetting;
12400        long callingId = Binder.clearCallingIdentity();
12401        try {
12402            // writer
12403            synchronized (mPackages) {
12404                pkgSetting = mSettings.mPackages.get(packageName);
12405                if (pkgSetting == null) {
12406                    return true;
12407                }
12408                return pkgSetting.getHidden(userId);
12409            }
12410        } finally {
12411            Binder.restoreCallingIdentity(callingId);
12412        }
12413    }
12414
12415    /**
12416     * @hide
12417     */
12418    @Override
12419    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
12420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12421                null);
12422        PackageSetting pkgSetting;
12423        final int uid = Binder.getCallingUid();
12424        enforceCrossUserPermission(uid, userId,
12425                true /* requireFullPermission */, true /* checkShell */,
12426                "installExistingPackage for user " + userId);
12427        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12428            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12429        }
12430
12431        long callingId = Binder.clearCallingIdentity();
12432        try {
12433            boolean installed = false;
12434
12435            // writer
12436            synchronized (mPackages) {
12437                pkgSetting = mSettings.mPackages.get(packageName);
12438                if (pkgSetting == null) {
12439                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12440                }
12441                if (!pkgSetting.getInstalled(userId)) {
12442                    pkgSetting.setInstalled(true, userId);
12443                    pkgSetting.setHidden(false, userId);
12444                    pkgSetting.setInstallReason(installReason, userId);
12445                    mSettings.writePackageRestrictionsLPr(userId);
12446                    installed = true;
12447                }
12448            }
12449
12450            if (installed) {
12451                if (pkgSetting.pkg != null) {
12452                    synchronized (mInstallLock) {
12453                        // We don't need to freeze for a brand new install
12454                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12455                    }
12456                }
12457                sendPackageAddedForUser(packageName, pkgSetting, userId);
12458            }
12459        } finally {
12460            Binder.restoreCallingIdentity(callingId);
12461        }
12462
12463        return PackageManager.INSTALL_SUCCEEDED;
12464    }
12465
12466    boolean isUserRestricted(int userId, String restrictionKey) {
12467        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12468        if (restrictions.getBoolean(restrictionKey, false)) {
12469            Log.w(TAG, "User is restricted: " + restrictionKey);
12470            return true;
12471        }
12472        return false;
12473    }
12474
12475    @Override
12476    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12477            int userId) {
12478        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12479        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12480                true /* requireFullPermission */, true /* checkShell */,
12481                "setPackagesSuspended for user " + userId);
12482
12483        if (ArrayUtils.isEmpty(packageNames)) {
12484            return packageNames;
12485        }
12486
12487        // List of package names for whom the suspended state has changed.
12488        List<String> changedPackages = new ArrayList<>(packageNames.length);
12489        // List of package names for whom the suspended state is not set as requested in this
12490        // method.
12491        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12492        long callingId = Binder.clearCallingIdentity();
12493        try {
12494            for (int i = 0; i < packageNames.length; i++) {
12495                String packageName = packageNames[i];
12496                boolean changed = false;
12497                final int appId;
12498                synchronized (mPackages) {
12499                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12500                    if (pkgSetting == null) {
12501                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12502                                + "\". Skipping suspending/un-suspending.");
12503                        unactionedPackages.add(packageName);
12504                        continue;
12505                    }
12506                    appId = pkgSetting.appId;
12507                    if (pkgSetting.getSuspended(userId) != suspended) {
12508                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12509                            unactionedPackages.add(packageName);
12510                            continue;
12511                        }
12512                        pkgSetting.setSuspended(suspended, userId);
12513                        mSettings.writePackageRestrictionsLPr(userId);
12514                        changed = true;
12515                        changedPackages.add(packageName);
12516                    }
12517                }
12518
12519                if (changed && suspended) {
12520                    killApplication(packageName, UserHandle.getUid(userId, appId),
12521                            "suspending package");
12522                }
12523            }
12524        } finally {
12525            Binder.restoreCallingIdentity(callingId);
12526        }
12527
12528        if (!changedPackages.isEmpty()) {
12529            sendPackagesSuspendedForUser(changedPackages.toArray(
12530                    new String[changedPackages.size()]), userId, suspended);
12531        }
12532
12533        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12534    }
12535
12536    @Override
12537    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12538        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12539                true /* requireFullPermission */, false /* checkShell */,
12540                "isPackageSuspendedForUser for user " + userId);
12541        synchronized (mPackages) {
12542            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12543            if (pkgSetting == null) {
12544                throw new IllegalArgumentException("Unknown target package: " + packageName);
12545            }
12546            return pkgSetting.getSuspended(userId);
12547        }
12548    }
12549
12550    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12551        if (isPackageDeviceAdmin(packageName, userId)) {
12552            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12553                    + "\": has an active device admin");
12554            return false;
12555        }
12556
12557        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12558        if (packageName.equals(activeLauncherPackageName)) {
12559            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12560                    + "\": contains the active launcher");
12561            return false;
12562        }
12563
12564        if (packageName.equals(mRequiredInstallerPackage)) {
12565            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12566                    + "\": required for package installation");
12567            return false;
12568        }
12569
12570        if (packageName.equals(mRequiredUninstallerPackage)) {
12571            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12572                    + "\": required for package uninstallation");
12573            return false;
12574        }
12575
12576        if (packageName.equals(mRequiredVerifierPackage)) {
12577            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12578                    + "\": required for package verification");
12579            return false;
12580        }
12581
12582        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12583            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12584                    + "\": is the default dialer");
12585            return false;
12586        }
12587
12588        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12589            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12590                    + "\": protected package");
12591            return false;
12592        }
12593
12594        return true;
12595    }
12596
12597    private String getActiveLauncherPackageName(int userId) {
12598        Intent intent = new Intent(Intent.ACTION_MAIN);
12599        intent.addCategory(Intent.CATEGORY_HOME);
12600        ResolveInfo resolveInfo = resolveIntent(
12601                intent,
12602                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12603                PackageManager.MATCH_DEFAULT_ONLY,
12604                userId);
12605
12606        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12607    }
12608
12609    private String getDefaultDialerPackageName(int userId) {
12610        synchronized (mPackages) {
12611            return mSettings.getDefaultDialerPackageNameLPw(userId);
12612        }
12613    }
12614
12615    @Override
12616    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12617        mContext.enforceCallingOrSelfPermission(
12618                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12619                "Only package verification agents can verify applications");
12620
12621        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12622        final PackageVerificationResponse response = new PackageVerificationResponse(
12623                verificationCode, Binder.getCallingUid());
12624        msg.arg1 = id;
12625        msg.obj = response;
12626        mHandler.sendMessage(msg);
12627    }
12628
12629    @Override
12630    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12631            long millisecondsToDelay) {
12632        mContext.enforceCallingOrSelfPermission(
12633                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12634                "Only package verification agents can extend verification timeouts");
12635
12636        final PackageVerificationState state = mPendingVerification.get(id);
12637        final PackageVerificationResponse response = new PackageVerificationResponse(
12638                verificationCodeAtTimeout, Binder.getCallingUid());
12639
12640        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12641            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12642        }
12643        if (millisecondsToDelay < 0) {
12644            millisecondsToDelay = 0;
12645        }
12646        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12647                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12648            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12649        }
12650
12651        if ((state != null) && !state.timeoutExtended()) {
12652            state.extendTimeout();
12653
12654            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12655            msg.arg1 = id;
12656            msg.obj = response;
12657            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12658        }
12659    }
12660
12661    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12662            int verificationCode, UserHandle user) {
12663        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12664        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12665        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12666        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12667        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12668
12669        mContext.sendBroadcastAsUser(intent, user,
12670                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12671    }
12672
12673    private ComponentName matchComponentForVerifier(String packageName,
12674            List<ResolveInfo> receivers) {
12675        ActivityInfo targetReceiver = null;
12676
12677        final int NR = receivers.size();
12678        for (int i = 0; i < NR; i++) {
12679            final ResolveInfo info = receivers.get(i);
12680            if (info.activityInfo == null) {
12681                continue;
12682            }
12683
12684            if (packageName.equals(info.activityInfo.packageName)) {
12685                targetReceiver = info.activityInfo;
12686                break;
12687            }
12688        }
12689
12690        if (targetReceiver == null) {
12691            return null;
12692        }
12693
12694        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12695    }
12696
12697    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12698            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12699        if (pkgInfo.verifiers.length == 0) {
12700            return null;
12701        }
12702
12703        final int N = pkgInfo.verifiers.length;
12704        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12705        for (int i = 0; i < N; i++) {
12706            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12707
12708            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12709                    receivers);
12710            if (comp == null) {
12711                continue;
12712            }
12713
12714            final int verifierUid = getUidForVerifier(verifierInfo);
12715            if (verifierUid == -1) {
12716                continue;
12717            }
12718
12719            if (DEBUG_VERIFY) {
12720                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12721                        + " with the correct signature");
12722            }
12723            sufficientVerifiers.add(comp);
12724            verificationState.addSufficientVerifier(verifierUid);
12725        }
12726
12727        return sufficientVerifiers;
12728    }
12729
12730    private int getUidForVerifier(VerifierInfo verifierInfo) {
12731        synchronized (mPackages) {
12732            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12733            if (pkg == null) {
12734                return -1;
12735            } else if (pkg.mSignatures.length != 1) {
12736                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12737                        + " has more than one signature; ignoring");
12738                return -1;
12739            }
12740
12741            /*
12742             * If the public key of the package's signature does not match
12743             * our expected public key, then this is a different package and
12744             * we should skip.
12745             */
12746
12747            final byte[] expectedPublicKey;
12748            try {
12749                final Signature verifierSig = pkg.mSignatures[0];
12750                final PublicKey publicKey = verifierSig.getPublicKey();
12751                expectedPublicKey = publicKey.getEncoded();
12752            } catch (CertificateException e) {
12753                return -1;
12754            }
12755
12756            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12757
12758            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12759                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12760                        + " does not have the expected public key; ignoring");
12761                return -1;
12762            }
12763
12764            return pkg.applicationInfo.uid;
12765        }
12766    }
12767
12768    @Override
12769    public void finishPackageInstall(int token, boolean didLaunch) {
12770        enforceSystemOrRoot("Only the system is allowed to finish installs");
12771
12772        if (DEBUG_INSTALL) {
12773            Slog.v(TAG, "BM finishing package install for " + token);
12774        }
12775        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12776
12777        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12778        mHandler.sendMessage(msg);
12779    }
12780
12781    /**
12782     * Get the verification agent timeout.
12783     *
12784     * @return verification timeout in milliseconds
12785     */
12786    private long getVerificationTimeout() {
12787        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12788                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12789                DEFAULT_VERIFICATION_TIMEOUT);
12790    }
12791
12792    /**
12793     * Get the default verification agent response code.
12794     *
12795     * @return default verification response code
12796     */
12797    private int getDefaultVerificationResponse() {
12798        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12799                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12800                DEFAULT_VERIFICATION_RESPONSE);
12801    }
12802
12803    /**
12804     * Check whether or not package verification has been enabled.
12805     *
12806     * @return true if verification should be performed
12807     */
12808    private boolean isVerificationEnabled(int userId, int installFlags) {
12809        if (!DEFAULT_VERIFY_ENABLE) {
12810            return false;
12811        }
12812        // Ephemeral apps don't get the full verification treatment
12813        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12814            if (DEBUG_EPHEMERAL) {
12815                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12816            }
12817            return false;
12818        }
12819
12820        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12821
12822        // Check if installing from ADB
12823        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12824            // Do not run verification in a test harness environment
12825            if (ActivityManager.isRunningInTestHarness()) {
12826                return false;
12827            }
12828            if (ensureVerifyAppsEnabled) {
12829                return true;
12830            }
12831            // Check if the developer does not want package verification for ADB installs
12832            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12833                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12834                return false;
12835            }
12836        }
12837
12838        if (ensureVerifyAppsEnabled) {
12839            return true;
12840        }
12841
12842        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12843                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12844    }
12845
12846    @Override
12847    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12848            throws RemoteException {
12849        mContext.enforceCallingOrSelfPermission(
12850                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12851                "Only intentfilter verification agents can verify applications");
12852
12853        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12854        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12855                Binder.getCallingUid(), verificationCode, failedDomains);
12856        msg.arg1 = id;
12857        msg.obj = response;
12858        mHandler.sendMessage(msg);
12859    }
12860
12861    @Override
12862    public int getIntentVerificationStatus(String packageName, int userId) {
12863        synchronized (mPackages) {
12864            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12865        }
12866    }
12867
12868    @Override
12869    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12870        mContext.enforceCallingOrSelfPermission(
12871                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12872
12873        boolean result = false;
12874        synchronized (mPackages) {
12875            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12876        }
12877        if (result) {
12878            scheduleWritePackageRestrictionsLocked(userId);
12879        }
12880        return result;
12881    }
12882
12883    @Override
12884    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12885            String packageName) {
12886        synchronized (mPackages) {
12887            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12888        }
12889    }
12890
12891    @Override
12892    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12893        if (TextUtils.isEmpty(packageName)) {
12894            return ParceledListSlice.emptyList();
12895        }
12896        synchronized (mPackages) {
12897            PackageParser.Package pkg = mPackages.get(packageName);
12898            if (pkg == null || pkg.activities == null) {
12899                return ParceledListSlice.emptyList();
12900            }
12901            final int count = pkg.activities.size();
12902            ArrayList<IntentFilter> result = new ArrayList<>();
12903            for (int n=0; n<count; n++) {
12904                PackageParser.Activity activity = pkg.activities.get(n);
12905                if (activity.intents != null && activity.intents.size() > 0) {
12906                    result.addAll(activity.intents);
12907                }
12908            }
12909            return new ParceledListSlice<>(result);
12910        }
12911    }
12912
12913    @Override
12914    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12915        mContext.enforceCallingOrSelfPermission(
12916                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12917
12918        synchronized (mPackages) {
12919            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12920            if (packageName != null) {
12921                result |= updateIntentVerificationStatus(packageName,
12922                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12923                        userId);
12924                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12925                        packageName, userId);
12926            }
12927            return result;
12928        }
12929    }
12930
12931    @Override
12932    public String getDefaultBrowserPackageName(int userId) {
12933        synchronized (mPackages) {
12934            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12935        }
12936    }
12937
12938    /**
12939     * Get the "allow unknown sources" setting.
12940     *
12941     * @return the current "allow unknown sources" setting
12942     */
12943    private int getUnknownSourcesSettings() {
12944        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12945                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12946                -1);
12947    }
12948
12949    @Override
12950    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12951        final int uid = Binder.getCallingUid();
12952        // writer
12953        synchronized (mPackages) {
12954            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12955            if (targetPackageSetting == null) {
12956                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12957            }
12958
12959            PackageSetting installerPackageSetting;
12960            if (installerPackageName != null) {
12961                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12962                if (installerPackageSetting == null) {
12963                    throw new IllegalArgumentException("Unknown installer package: "
12964                            + installerPackageName);
12965                }
12966            } else {
12967                installerPackageSetting = null;
12968            }
12969
12970            Signature[] callerSignature;
12971            Object obj = mSettings.getUserIdLPr(uid);
12972            if (obj != null) {
12973                if (obj instanceof SharedUserSetting) {
12974                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12975                } else if (obj instanceof PackageSetting) {
12976                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12977                } else {
12978                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12979                }
12980            } else {
12981                throw new SecurityException("Unknown calling UID: " + uid);
12982            }
12983
12984            // Verify: can't set installerPackageName to a package that is
12985            // not signed with the same cert as the caller.
12986            if (installerPackageSetting != null) {
12987                if (compareSignatures(callerSignature,
12988                        installerPackageSetting.signatures.mSignatures)
12989                        != PackageManager.SIGNATURE_MATCH) {
12990                    throw new SecurityException(
12991                            "Caller does not have same cert as new installer package "
12992                            + installerPackageName);
12993                }
12994            }
12995
12996            // Verify: if target already has an installer package, it must
12997            // be signed with the same cert as the caller.
12998            if (targetPackageSetting.installerPackageName != null) {
12999                PackageSetting setting = mSettings.mPackages.get(
13000                        targetPackageSetting.installerPackageName);
13001                // If the currently set package isn't valid, then it's always
13002                // okay to change it.
13003                if (setting != null) {
13004                    if (compareSignatures(callerSignature,
13005                            setting.signatures.mSignatures)
13006                            != PackageManager.SIGNATURE_MATCH) {
13007                        throw new SecurityException(
13008                                "Caller does not have same cert as old installer package "
13009                                + targetPackageSetting.installerPackageName);
13010                    }
13011                }
13012            }
13013
13014            // Okay!
13015            targetPackageSetting.installerPackageName = installerPackageName;
13016            if (installerPackageName != null) {
13017                mSettings.mInstallerPackages.add(installerPackageName);
13018            }
13019            scheduleWriteSettingsLocked();
13020        }
13021    }
13022
13023    @Override
13024    public void setApplicationCategoryHint(String packageName, int categoryHint,
13025            String callerPackageName) {
13026        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13027                callerPackageName);
13028        synchronized (mPackages) {
13029            PackageSetting ps = mSettings.mPackages.get(packageName);
13030            if (ps == null) {
13031                throw new IllegalArgumentException("Unknown target package " + packageName);
13032            }
13033
13034            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13035                throw new IllegalArgumentException("Calling package " + callerPackageName
13036                        + " is not installer for " + packageName);
13037            }
13038
13039            if (ps.categoryHint != categoryHint) {
13040                ps.categoryHint = categoryHint;
13041                scheduleWriteSettingsLocked();
13042            }
13043        }
13044    }
13045
13046    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13047        // Queue up an async operation since the package installation may take a little while.
13048        mHandler.post(new Runnable() {
13049            public void run() {
13050                mHandler.removeCallbacks(this);
13051                 // Result object to be returned
13052                PackageInstalledInfo res = new PackageInstalledInfo();
13053                res.setReturnCode(currentStatus);
13054                res.uid = -1;
13055                res.pkg = null;
13056                res.removedInfo = null;
13057                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13058                    args.doPreInstall(res.returnCode);
13059                    synchronized (mInstallLock) {
13060                        installPackageTracedLI(args, res);
13061                    }
13062                    args.doPostInstall(res.returnCode, res.uid);
13063                }
13064
13065                // A restore should be performed at this point if (a) the install
13066                // succeeded, (b) the operation is not an update, and (c) the new
13067                // package has not opted out of backup participation.
13068                final boolean update = res.removedInfo != null
13069                        && res.removedInfo.removedPackage != null;
13070                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13071                boolean doRestore = !update
13072                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13073
13074                // Set up the post-install work request bookkeeping.  This will be used
13075                // and cleaned up by the post-install event handling regardless of whether
13076                // there's a restore pass performed.  Token values are >= 1.
13077                int token;
13078                if (mNextInstallToken < 0) mNextInstallToken = 1;
13079                token = mNextInstallToken++;
13080
13081                PostInstallData data = new PostInstallData(args, res);
13082                mRunningInstalls.put(token, data);
13083                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13084
13085                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13086                    // Pass responsibility to the Backup Manager.  It will perform a
13087                    // restore if appropriate, then pass responsibility back to the
13088                    // Package Manager to run the post-install observer callbacks
13089                    // and broadcasts.
13090                    IBackupManager bm = IBackupManager.Stub.asInterface(
13091                            ServiceManager.getService(Context.BACKUP_SERVICE));
13092                    if (bm != null) {
13093                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13094                                + " to BM for possible restore");
13095                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13096                        try {
13097                            // TODO: http://b/22388012
13098                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13099                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13100                            } else {
13101                                doRestore = false;
13102                            }
13103                        } catch (RemoteException e) {
13104                            // can't happen; the backup manager is local
13105                        } catch (Exception e) {
13106                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13107                            doRestore = false;
13108                        }
13109                    } else {
13110                        Slog.e(TAG, "Backup Manager not found!");
13111                        doRestore = false;
13112                    }
13113                }
13114
13115                if (!doRestore) {
13116                    // No restore possible, or the Backup Manager was mysteriously not
13117                    // available -- just fire the post-install work request directly.
13118                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13119
13120                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13121
13122                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13123                    mHandler.sendMessage(msg);
13124                }
13125            }
13126        });
13127    }
13128
13129    /**
13130     * Callback from PackageSettings whenever an app is first transitioned out of the
13131     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13132     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13133     * here whether the app is the target of an ongoing install, and only send the
13134     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13135     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13136     * handling.
13137     */
13138    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13139        // Serialize this with the rest of the install-process message chain.  In the
13140        // restore-at-install case, this Runnable will necessarily run before the
13141        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13142        // are coherent.  In the non-restore case, the app has already completed install
13143        // and been launched through some other means, so it is not in a problematic
13144        // state for observers to see the FIRST_LAUNCH signal.
13145        mHandler.post(new Runnable() {
13146            @Override
13147            public void run() {
13148                for (int i = 0; i < mRunningInstalls.size(); i++) {
13149                    final PostInstallData data = mRunningInstalls.valueAt(i);
13150                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13151                        continue;
13152                    }
13153                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13154                        // right package; but is it for the right user?
13155                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13156                            if (userId == data.res.newUsers[uIndex]) {
13157                                if (DEBUG_BACKUP) {
13158                                    Slog.i(TAG, "Package " + pkgName
13159                                            + " being restored so deferring FIRST_LAUNCH");
13160                                }
13161                                return;
13162                            }
13163                        }
13164                    }
13165                }
13166                // didn't find it, so not being restored
13167                if (DEBUG_BACKUP) {
13168                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13169                }
13170                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13171            }
13172        });
13173    }
13174
13175    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13176        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13177                installerPkg, null, userIds);
13178    }
13179
13180    private abstract class HandlerParams {
13181        private static final int MAX_RETRIES = 4;
13182
13183        /**
13184         * Number of times startCopy() has been attempted and had a non-fatal
13185         * error.
13186         */
13187        private int mRetries = 0;
13188
13189        /** User handle for the user requesting the information or installation. */
13190        private final UserHandle mUser;
13191        String traceMethod;
13192        int traceCookie;
13193
13194        HandlerParams(UserHandle user) {
13195            mUser = user;
13196        }
13197
13198        UserHandle getUser() {
13199            return mUser;
13200        }
13201
13202        HandlerParams setTraceMethod(String traceMethod) {
13203            this.traceMethod = traceMethod;
13204            return this;
13205        }
13206
13207        HandlerParams setTraceCookie(int traceCookie) {
13208            this.traceCookie = traceCookie;
13209            return this;
13210        }
13211
13212        final boolean startCopy() {
13213            boolean res;
13214            try {
13215                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13216
13217                if (++mRetries > MAX_RETRIES) {
13218                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13219                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13220                    handleServiceError();
13221                    return false;
13222                } else {
13223                    handleStartCopy();
13224                    res = true;
13225                }
13226            } catch (RemoteException e) {
13227                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13228                mHandler.sendEmptyMessage(MCS_RECONNECT);
13229                res = false;
13230            }
13231            handleReturnCode();
13232            return res;
13233        }
13234
13235        final void serviceError() {
13236            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13237            handleServiceError();
13238            handleReturnCode();
13239        }
13240
13241        abstract void handleStartCopy() throws RemoteException;
13242        abstract void handleServiceError();
13243        abstract void handleReturnCode();
13244    }
13245
13246    class MeasureParams extends HandlerParams {
13247        private final PackageStats mStats;
13248        private boolean mSuccess;
13249
13250        private final IPackageStatsObserver mObserver;
13251
13252        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13253            super(new UserHandle(stats.userHandle));
13254            mObserver = observer;
13255            mStats = stats;
13256        }
13257
13258        @Override
13259        public String toString() {
13260            return "MeasureParams{"
13261                + Integer.toHexString(System.identityHashCode(this))
13262                + " " + mStats.packageName + "}";
13263        }
13264
13265        @Override
13266        void handleStartCopy() throws RemoteException {
13267            synchronized (mInstallLock) {
13268                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13269            }
13270
13271            if (mSuccess) {
13272                boolean mounted = false;
13273                try {
13274                    final String status = Environment.getExternalStorageState();
13275                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13276                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13277                } catch (Exception e) {
13278                }
13279
13280                if (mounted) {
13281                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13282
13283                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13284                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13285
13286                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13287                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13288
13289                    // Always subtract cache size, since it's a subdirectory
13290                    mStats.externalDataSize -= mStats.externalCacheSize;
13291
13292                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13293                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13294
13295                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13296                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13297                }
13298            }
13299        }
13300
13301        @Override
13302        void handleReturnCode() {
13303            if (mObserver != null) {
13304                try {
13305                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13306                } catch (RemoteException e) {
13307                    Slog.i(TAG, "Observer no longer exists.");
13308                }
13309            }
13310        }
13311
13312        @Override
13313        void handleServiceError() {
13314            Slog.e(TAG, "Could not measure application " + mStats.packageName
13315                            + " external storage");
13316        }
13317    }
13318
13319    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13320            throws RemoteException {
13321        long result = 0;
13322        for (File path : paths) {
13323            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13324        }
13325        return result;
13326    }
13327
13328    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13329        for (File path : paths) {
13330            try {
13331                mcs.clearDirectory(path.getAbsolutePath());
13332            } catch (RemoteException e) {
13333            }
13334        }
13335    }
13336
13337    static class OriginInfo {
13338        /**
13339         * Location where install is coming from, before it has been
13340         * copied/renamed into place. This could be a single monolithic APK
13341         * file, or a cluster directory. This location may be untrusted.
13342         */
13343        final File file;
13344        final String cid;
13345
13346        /**
13347         * Flag indicating that {@link #file} or {@link #cid} has already been
13348         * staged, meaning downstream users don't need to defensively copy the
13349         * contents.
13350         */
13351        final boolean staged;
13352
13353        /**
13354         * Flag indicating that {@link #file} or {@link #cid} is an already
13355         * installed app that is being moved.
13356         */
13357        final boolean existing;
13358
13359        final String resolvedPath;
13360        final File resolvedFile;
13361
13362        static OriginInfo fromNothing() {
13363            return new OriginInfo(null, null, false, false);
13364        }
13365
13366        static OriginInfo fromUntrustedFile(File file) {
13367            return new OriginInfo(file, null, false, false);
13368        }
13369
13370        static OriginInfo fromExistingFile(File file) {
13371            return new OriginInfo(file, null, false, true);
13372        }
13373
13374        static OriginInfo fromStagedFile(File file) {
13375            return new OriginInfo(file, null, true, false);
13376        }
13377
13378        static OriginInfo fromStagedContainer(String cid) {
13379            return new OriginInfo(null, cid, true, false);
13380        }
13381
13382        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13383            this.file = file;
13384            this.cid = cid;
13385            this.staged = staged;
13386            this.existing = existing;
13387
13388            if (cid != null) {
13389                resolvedPath = PackageHelper.getSdDir(cid);
13390                resolvedFile = new File(resolvedPath);
13391            } else if (file != null) {
13392                resolvedPath = file.getAbsolutePath();
13393                resolvedFile = file;
13394            } else {
13395                resolvedPath = null;
13396                resolvedFile = null;
13397            }
13398        }
13399    }
13400
13401    static class MoveInfo {
13402        final int moveId;
13403        final String fromUuid;
13404        final String toUuid;
13405        final String packageName;
13406        final String dataAppName;
13407        final int appId;
13408        final String seinfo;
13409        final int targetSdkVersion;
13410
13411        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13412                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13413            this.moveId = moveId;
13414            this.fromUuid = fromUuid;
13415            this.toUuid = toUuid;
13416            this.packageName = packageName;
13417            this.dataAppName = dataAppName;
13418            this.appId = appId;
13419            this.seinfo = seinfo;
13420            this.targetSdkVersion = targetSdkVersion;
13421        }
13422    }
13423
13424    static class VerificationInfo {
13425        /** A constant used to indicate that a uid value is not present. */
13426        public static final int NO_UID = -1;
13427
13428        /** URI referencing where the package was downloaded from. */
13429        final Uri originatingUri;
13430
13431        /** HTTP referrer URI associated with the originatingURI. */
13432        final Uri referrer;
13433
13434        /** UID of the application that the install request originated from. */
13435        final int originatingUid;
13436
13437        /** UID of application requesting the install */
13438        final int installerUid;
13439
13440        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13441            this.originatingUri = originatingUri;
13442            this.referrer = referrer;
13443            this.originatingUid = originatingUid;
13444            this.installerUid = installerUid;
13445        }
13446    }
13447
13448    class InstallParams extends HandlerParams {
13449        final OriginInfo origin;
13450        final MoveInfo move;
13451        final IPackageInstallObserver2 observer;
13452        int installFlags;
13453        final String installerPackageName;
13454        final String volumeUuid;
13455        private InstallArgs mArgs;
13456        private int mRet;
13457        final String packageAbiOverride;
13458        final String[] grantedRuntimePermissions;
13459        final VerificationInfo verificationInfo;
13460        final Certificate[][] certificates;
13461        final int installReason;
13462
13463        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13464                int installFlags, String installerPackageName, String volumeUuid,
13465                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13466                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
13467            super(user);
13468            this.origin = origin;
13469            this.move = move;
13470            this.observer = observer;
13471            this.installFlags = installFlags;
13472            this.installerPackageName = installerPackageName;
13473            this.volumeUuid = volumeUuid;
13474            this.verificationInfo = verificationInfo;
13475            this.packageAbiOverride = packageAbiOverride;
13476            this.grantedRuntimePermissions = grantedPermissions;
13477            this.certificates = certificates;
13478            this.installReason = installReason;
13479        }
13480
13481        @Override
13482        public String toString() {
13483            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13484                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13485        }
13486
13487        private int installLocationPolicy(PackageInfoLite pkgLite) {
13488            String packageName = pkgLite.packageName;
13489            int installLocation = pkgLite.installLocation;
13490            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13491            // reader
13492            synchronized (mPackages) {
13493                // Currently installed package which the new package is attempting to replace or
13494                // null if no such package is installed.
13495                PackageParser.Package installedPkg = mPackages.get(packageName);
13496                // Package which currently owns the data which the new package will own if installed.
13497                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13498                // will be null whereas dataOwnerPkg will contain information about the package
13499                // which was uninstalled while keeping its data.
13500                PackageParser.Package dataOwnerPkg = installedPkg;
13501                if (dataOwnerPkg  == null) {
13502                    PackageSetting ps = mSettings.mPackages.get(packageName);
13503                    if (ps != null) {
13504                        dataOwnerPkg = ps.pkg;
13505                    }
13506                }
13507
13508                if (dataOwnerPkg != null) {
13509                    // If installed, the package will get access to data left on the device by its
13510                    // predecessor. As a security measure, this is permited only if this is not a
13511                    // version downgrade or if the predecessor package is marked as debuggable and
13512                    // a downgrade is explicitly requested.
13513                    //
13514                    // On debuggable platform builds, downgrades are permitted even for
13515                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13516                    // not offer security guarantees and thus it's OK to disable some security
13517                    // mechanisms to make debugging/testing easier on those builds. However, even on
13518                    // debuggable builds downgrades of packages are permitted only if requested via
13519                    // installFlags. This is because we aim to keep the behavior of debuggable
13520                    // platform builds as close as possible to the behavior of non-debuggable
13521                    // platform builds.
13522                    final boolean downgradeRequested =
13523                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13524                    final boolean packageDebuggable =
13525                                (dataOwnerPkg.applicationInfo.flags
13526                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13527                    final boolean downgradePermitted =
13528                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13529                    if (!downgradePermitted) {
13530                        try {
13531                            checkDowngrade(dataOwnerPkg, pkgLite);
13532                        } catch (PackageManagerException e) {
13533                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13534                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13535                        }
13536                    }
13537                }
13538
13539                if (installedPkg != null) {
13540                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13541                        // Check for updated system application.
13542                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13543                            if (onSd) {
13544                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13545                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13546                            }
13547                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13548                        } else {
13549                            if (onSd) {
13550                                // Install flag overrides everything.
13551                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13552                            }
13553                            // If current upgrade specifies particular preference
13554                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13555                                // Application explicitly specified internal.
13556                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13557                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13558                                // App explictly prefers external. Let policy decide
13559                            } else {
13560                                // Prefer previous location
13561                                if (isExternal(installedPkg)) {
13562                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13563                                }
13564                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13565                            }
13566                        }
13567                    } else {
13568                        // Invalid install. Return error code
13569                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13570                    }
13571                }
13572            }
13573            // All the special cases have been taken care of.
13574            // Return result based on recommended install location.
13575            if (onSd) {
13576                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13577            }
13578            return pkgLite.recommendedInstallLocation;
13579        }
13580
13581        /*
13582         * Invoke remote method to get package information and install
13583         * location values. Override install location based on default
13584         * policy if needed and then create install arguments based
13585         * on the install location.
13586         */
13587        public void handleStartCopy() throws RemoteException {
13588            int ret = PackageManager.INSTALL_SUCCEEDED;
13589
13590            // If we're already staged, we've firmly committed to an install location
13591            if (origin.staged) {
13592                if (origin.file != null) {
13593                    installFlags |= PackageManager.INSTALL_INTERNAL;
13594                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13595                } else if (origin.cid != null) {
13596                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13597                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13598                } else {
13599                    throw new IllegalStateException("Invalid stage location");
13600                }
13601            }
13602
13603            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13604            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13605            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13606            PackageInfoLite pkgLite = null;
13607
13608            if (onInt && onSd) {
13609                // Check if both bits are set.
13610                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13611                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13612            } else if (onSd && ephemeral) {
13613                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13614                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13615            } else {
13616                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13617                        packageAbiOverride);
13618
13619                if (DEBUG_EPHEMERAL && ephemeral) {
13620                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13621                }
13622
13623                /*
13624                 * If we have too little free space, try to free cache
13625                 * before giving up.
13626                 */
13627                if (!origin.staged && pkgLite.recommendedInstallLocation
13628                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13629                    // TODO: focus freeing disk space on the target device
13630                    final StorageManager storage = StorageManager.from(mContext);
13631                    final long lowThreshold = storage.getStorageLowBytes(
13632                            Environment.getDataDirectory());
13633
13634                    final long sizeBytes = mContainerService.calculateInstalledSize(
13635                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13636
13637                    try {
13638                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13639                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13640                                installFlags, packageAbiOverride);
13641                    } catch (InstallerException e) {
13642                        Slog.w(TAG, "Failed to free cache", e);
13643                    }
13644
13645                    /*
13646                     * The cache free must have deleted the file we
13647                     * downloaded to install.
13648                     *
13649                     * TODO: fix the "freeCache" call to not delete
13650                     *       the file we care about.
13651                     */
13652                    if (pkgLite.recommendedInstallLocation
13653                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13654                        pkgLite.recommendedInstallLocation
13655                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13656                    }
13657                }
13658            }
13659
13660            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13661                int loc = pkgLite.recommendedInstallLocation;
13662                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13663                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13664                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13665                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13666                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13667                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13668                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13669                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13670                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13671                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13672                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13673                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13674                } else {
13675                    // Override with defaults if needed.
13676                    loc = installLocationPolicy(pkgLite);
13677                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13678                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13679                    } else if (!onSd && !onInt) {
13680                        // Override install location with flags
13681                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13682                            // Set the flag to install on external media.
13683                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13684                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13685                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13686                            if (DEBUG_EPHEMERAL) {
13687                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13688                            }
13689                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13690                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13691                                    |PackageManager.INSTALL_INTERNAL);
13692                        } else {
13693                            // Make sure the flag for installing on external
13694                            // media is unset
13695                            installFlags |= PackageManager.INSTALL_INTERNAL;
13696                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13697                        }
13698                    }
13699                }
13700            }
13701
13702            final InstallArgs args = createInstallArgs(this);
13703            mArgs = args;
13704
13705            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13706                // TODO: http://b/22976637
13707                // Apps installed for "all" users use the device owner to verify the app
13708                UserHandle verifierUser = getUser();
13709                if (verifierUser == UserHandle.ALL) {
13710                    verifierUser = UserHandle.SYSTEM;
13711                }
13712
13713                /*
13714                 * Determine if we have any installed package verifiers. If we
13715                 * do, then we'll defer to them to verify the packages.
13716                 */
13717                final int requiredUid = mRequiredVerifierPackage == null ? -1
13718                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13719                                verifierUser.getIdentifier());
13720                if (!origin.existing && requiredUid != -1
13721                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13722                    final Intent verification = new Intent(
13723                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13724                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13725                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13726                            PACKAGE_MIME_TYPE);
13727                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13728
13729                    // Query all live verifiers based on current user state
13730                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13731                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13732
13733                    if (DEBUG_VERIFY) {
13734                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13735                                + verification.toString() + " with " + pkgLite.verifiers.length
13736                                + " optional verifiers");
13737                    }
13738
13739                    final int verificationId = mPendingVerificationToken++;
13740
13741                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13742
13743                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13744                            installerPackageName);
13745
13746                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13747                            installFlags);
13748
13749                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13750                            pkgLite.packageName);
13751
13752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13753                            pkgLite.versionCode);
13754
13755                    if (verificationInfo != null) {
13756                        if (verificationInfo.originatingUri != null) {
13757                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13758                                    verificationInfo.originatingUri);
13759                        }
13760                        if (verificationInfo.referrer != null) {
13761                            verification.putExtra(Intent.EXTRA_REFERRER,
13762                                    verificationInfo.referrer);
13763                        }
13764                        if (verificationInfo.originatingUid >= 0) {
13765                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13766                                    verificationInfo.originatingUid);
13767                        }
13768                        if (verificationInfo.installerUid >= 0) {
13769                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13770                                    verificationInfo.installerUid);
13771                        }
13772                    }
13773
13774                    final PackageVerificationState verificationState = new PackageVerificationState(
13775                            requiredUid, args);
13776
13777                    mPendingVerification.append(verificationId, verificationState);
13778
13779                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13780                            receivers, verificationState);
13781
13782                    /*
13783                     * If any sufficient verifiers were listed in the package
13784                     * manifest, attempt to ask them.
13785                     */
13786                    if (sufficientVerifiers != null) {
13787                        final int N = sufficientVerifiers.size();
13788                        if (N == 0) {
13789                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13790                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13791                        } else {
13792                            for (int i = 0; i < N; i++) {
13793                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13794
13795                                final Intent sufficientIntent = new Intent(verification);
13796                                sufficientIntent.setComponent(verifierComponent);
13797                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13798                            }
13799                        }
13800                    }
13801
13802                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13803                            mRequiredVerifierPackage, receivers);
13804                    if (ret == PackageManager.INSTALL_SUCCEEDED
13805                            && mRequiredVerifierPackage != null) {
13806                        Trace.asyncTraceBegin(
13807                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13808                        /*
13809                         * Send the intent to the required verification agent,
13810                         * but only start the verification timeout after the
13811                         * target BroadcastReceivers have run.
13812                         */
13813                        verification.setComponent(requiredVerifierComponent);
13814                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13815                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13816                                new BroadcastReceiver() {
13817                                    @Override
13818                                    public void onReceive(Context context, Intent intent) {
13819                                        final Message msg = mHandler
13820                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13821                                        msg.arg1 = verificationId;
13822                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13823                                    }
13824                                }, null, 0, null, null);
13825
13826                        /*
13827                         * We don't want the copy to proceed until verification
13828                         * succeeds, so null out this field.
13829                         */
13830                        mArgs = null;
13831                    }
13832                } else {
13833                    /*
13834                     * No package verification is enabled, so immediately start
13835                     * the remote call to initiate copy using temporary file.
13836                     */
13837                    ret = args.copyApk(mContainerService, true);
13838                }
13839            }
13840
13841            mRet = ret;
13842        }
13843
13844        @Override
13845        void handleReturnCode() {
13846            // If mArgs is null, then MCS couldn't be reached. When it
13847            // reconnects, it will try again to install. At that point, this
13848            // will succeed.
13849            if (mArgs != null) {
13850                processPendingInstall(mArgs, mRet);
13851            }
13852        }
13853
13854        @Override
13855        void handleServiceError() {
13856            mArgs = createInstallArgs(this);
13857            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13858        }
13859
13860        public boolean isForwardLocked() {
13861            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13862        }
13863    }
13864
13865    /**
13866     * Used during creation of InstallArgs
13867     *
13868     * @param installFlags package installation flags
13869     * @return true if should be installed on external storage
13870     */
13871    private static boolean installOnExternalAsec(int installFlags) {
13872        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13873            return false;
13874        }
13875        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13876            return true;
13877        }
13878        return false;
13879    }
13880
13881    /**
13882     * Used during creation of InstallArgs
13883     *
13884     * @param installFlags package installation flags
13885     * @return true if should be installed as forward locked
13886     */
13887    private static boolean installForwardLocked(int installFlags) {
13888        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13889    }
13890
13891    private InstallArgs createInstallArgs(InstallParams params) {
13892        if (params.move != null) {
13893            return new MoveInstallArgs(params);
13894        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13895            return new AsecInstallArgs(params);
13896        } else {
13897            return new FileInstallArgs(params);
13898        }
13899    }
13900
13901    /**
13902     * Create args that describe an existing installed package. Typically used
13903     * when cleaning up old installs, or used as a move source.
13904     */
13905    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13906            String resourcePath, String[] instructionSets) {
13907        final boolean isInAsec;
13908        if (installOnExternalAsec(installFlags)) {
13909            /* Apps on SD card are always in ASEC containers. */
13910            isInAsec = true;
13911        } else if (installForwardLocked(installFlags)
13912                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13913            /*
13914             * Forward-locked apps are only in ASEC containers if they're the
13915             * new style
13916             */
13917            isInAsec = true;
13918        } else {
13919            isInAsec = false;
13920        }
13921
13922        if (isInAsec) {
13923            return new AsecInstallArgs(codePath, instructionSets,
13924                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13925        } else {
13926            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13927        }
13928    }
13929
13930    static abstract class InstallArgs {
13931        /** @see InstallParams#origin */
13932        final OriginInfo origin;
13933        /** @see InstallParams#move */
13934        final MoveInfo move;
13935
13936        final IPackageInstallObserver2 observer;
13937        // Always refers to PackageManager flags only
13938        final int installFlags;
13939        final String installerPackageName;
13940        final String volumeUuid;
13941        final UserHandle user;
13942        final String abiOverride;
13943        final String[] installGrantPermissions;
13944        /** If non-null, drop an async trace when the install completes */
13945        final String traceMethod;
13946        final int traceCookie;
13947        final Certificate[][] certificates;
13948        final int installReason;
13949
13950        // The list of instruction sets supported by this app. This is currently
13951        // only used during the rmdex() phase to clean up resources. We can get rid of this
13952        // if we move dex files under the common app path.
13953        /* nullable */ String[] instructionSets;
13954
13955        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13956                int installFlags, String installerPackageName, String volumeUuid,
13957                UserHandle user, String[] instructionSets,
13958                String abiOverride, String[] installGrantPermissions,
13959                String traceMethod, int traceCookie, Certificate[][] certificates,
13960                int installReason) {
13961            this.origin = origin;
13962            this.move = move;
13963            this.installFlags = installFlags;
13964            this.observer = observer;
13965            this.installerPackageName = installerPackageName;
13966            this.volumeUuid = volumeUuid;
13967            this.user = user;
13968            this.instructionSets = instructionSets;
13969            this.abiOverride = abiOverride;
13970            this.installGrantPermissions = installGrantPermissions;
13971            this.traceMethod = traceMethod;
13972            this.traceCookie = traceCookie;
13973            this.certificates = certificates;
13974            this.installReason = installReason;
13975        }
13976
13977        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13978        abstract int doPreInstall(int status);
13979
13980        /**
13981         * Rename package into final resting place. All paths on the given
13982         * scanned package should be updated to reflect the rename.
13983         */
13984        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13985        abstract int doPostInstall(int status, int uid);
13986
13987        /** @see PackageSettingBase#codePathString */
13988        abstract String getCodePath();
13989        /** @see PackageSettingBase#resourcePathString */
13990        abstract String getResourcePath();
13991
13992        // Need installer lock especially for dex file removal.
13993        abstract void cleanUpResourcesLI();
13994        abstract boolean doPostDeleteLI(boolean delete);
13995
13996        /**
13997         * Called before the source arguments are copied. This is used mostly
13998         * for MoveParams when it needs to read the source file to put it in the
13999         * destination.
14000         */
14001        int doPreCopy() {
14002            return PackageManager.INSTALL_SUCCEEDED;
14003        }
14004
14005        /**
14006         * Called after the source arguments are copied. This is used mostly for
14007         * MoveParams when it needs to read the source file to put it in the
14008         * destination.
14009         */
14010        int doPostCopy(int uid) {
14011            return PackageManager.INSTALL_SUCCEEDED;
14012        }
14013
14014        protected boolean isFwdLocked() {
14015            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14016        }
14017
14018        protected boolean isExternalAsec() {
14019            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14020        }
14021
14022        protected boolean isEphemeral() {
14023            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14024        }
14025
14026        UserHandle getUser() {
14027            return user;
14028        }
14029    }
14030
14031    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14032        if (!allCodePaths.isEmpty()) {
14033            if (instructionSets == null) {
14034                throw new IllegalStateException("instructionSet == null");
14035            }
14036            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14037            for (String codePath : allCodePaths) {
14038                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14039                    try {
14040                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14041                    } catch (InstallerException ignored) {
14042                    }
14043                }
14044            }
14045        }
14046    }
14047
14048    /**
14049     * Logic to handle installation of non-ASEC applications, including copying
14050     * and renaming logic.
14051     */
14052    class FileInstallArgs extends InstallArgs {
14053        private File codeFile;
14054        private File resourceFile;
14055
14056        // Example topology:
14057        // /data/app/com.example/base.apk
14058        // /data/app/com.example/split_foo.apk
14059        // /data/app/com.example/lib/arm/libfoo.so
14060        // /data/app/com.example/lib/arm64/libfoo.so
14061        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14062
14063        /** New install */
14064        FileInstallArgs(InstallParams params) {
14065            super(params.origin, params.move, params.observer, params.installFlags,
14066                    params.installerPackageName, params.volumeUuid,
14067                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14068                    params.grantedRuntimePermissions,
14069                    params.traceMethod, params.traceCookie, params.certificates,
14070                    params.installReason);
14071            if (isFwdLocked()) {
14072                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14073            }
14074        }
14075
14076        /** Existing install */
14077        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14078            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14079                    null, null, null, 0, null /*certificates*/,
14080                    PackageManager.INSTALL_REASON_UNKNOWN);
14081            this.codeFile = (codePath != null) ? new File(codePath) : null;
14082            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14083        }
14084
14085        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14086            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14087            try {
14088                return doCopyApk(imcs, temp);
14089            } finally {
14090                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14091            }
14092        }
14093
14094        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14095            if (origin.staged) {
14096                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14097                codeFile = origin.file;
14098                resourceFile = origin.file;
14099                return PackageManager.INSTALL_SUCCEEDED;
14100            }
14101
14102            try {
14103                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14104                final File tempDir =
14105                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14106                codeFile = tempDir;
14107                resourceFile = tempDir;
14108            } catch (IOException e) {
14109                Slog.w(TAG, "Failed to create copy file: " + e);
14110                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14111            }
14112
14113            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14114                @Override
14115                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14116                    if (!FileUtils.isValidExtFilename(name)) {
14117                        throw new IllegalArgumentException("Invalid filename: " + name);
14118                    }
14119                    try {
14120                        final File file = new File(codeFile, name);
14121                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14122                                O_RDWR | O_CREAT, 0644);
14123                        Os.chmod(file.getAbsolutePath(), 0644);
14124                        return new ParcelFileDescriptor(fd);
14125                    } catch (ErrnoException e) {
14126                        throw new RemoteException("Failed to open: " + e.getMessage());
14127                    }
14128                }
14129            };
14130
14131            int ret = PackageManager.INSTALL_SUCCEEDED;
14132            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14133            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14134                Slog.e(TAG, "Failed to copy package");
14135                return ret;
14136            }
14137
14138            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14139            NativeLibraryHelper.Handle handle = null;
14140            try {
14141                handle = NativeLibraryHelper.Handle.create(codeFile);
14142                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14143                        abiOverride);
14144            } catch (IOException e) {
14145                Slog.e(TAG, "Copying native libraries failed", e);
14146                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14147            } finally {
14148                IoUtils.closeQuietly(handle);
14149            }
14150
14151            return ret;
14152        }
14153
14154        int doPreInstall(int status) {
14155            if (status != PackageManager.INSTALL_SUCCEEDED) {
14156                cleanUp();
14157            }
14158            return status;
14159        }
14160
14161        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14162            if (status != PackageManager.INSTALL_SUCCEEDED) {
14163                cleanUp();
14164                return false;
14165            }
14166
14167            final File targetDir = codeFile.getParentFile();
14168            final File beforeCodeFile = codeFile;
14169            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14170
14171            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14172            try {
14173                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14174            } catch (ErrnoException e) {
14175                Slog.w(TAG, "Failed to rename", e);
14176                return false;
14177            }
14178
14179            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14180                Slog.w(TAG, "Failed to restorecon");
14181                return false;
14182            }
14183
14184            // Reflect the rename internally
14185            codeFile = afterCodeFile;
14186            resourceFile = afterCodeFile;
14187
14188            // Reflect the rename in scanned details
14189            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14190            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14191                    afterCodeFile, pkg.baseCodePath));
14192            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14193                    afterCodeFile, pkg.splitCodePaths));
14194
14195            // Reflect the rename in app info
14196            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14197            pkg.setApplicationInfoCodePath(pkg.codePath);
14198            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14199            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14200            pkg.setApplicationInfoResourcePath(pkg.codePath);
14201            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14202            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14203
14204            return true;
14205        }
14206
14207        int doPostInstall(int status, int uid) {
14208            if (status != PackageManager.INSTALL_SUCCEEDED) {
14209                cleanUp();
14210            }
14211            return status;
14212        }
14213
14214        @Override
14215        String getCodePath() {
14216            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14217        }
14218
14219        @Override
14220        String getResourcePath() {
14221            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14222        }
14223
14224        private boolean cleanUp() {
14225            if (codeFile == null || !codeFile.exists()) {
14226                return false;
14227            }
14228
14229            removeCodePathLI(codeFile);
14230
14231            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14232                resourceFile.delete();
14233            }
14234
14235            return true;
14236        }
14237
14238        void cleanUpResourcesLI() {
14239            // Try enumerating all code paths before deleting
14240            List<String> allCodePaths = Collections.EMPTY_LIST;
14241            if (codeFile != null && codeFile.exists()) {
14242                try {
14243                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14244                    allCodePaths = pkg.getAllCodePaths();
14245                } catch (PackageParserException e) {
14246                    // Ignored; we tried our best
14247                }
14248            }
14249
14250            cleanUp();
14251            removeDexFiles(allCodePaths, instructionSets);
14252        }
14253
14254        boolean doPostDeleteLI(boolean delete) {
14255            // XXX err, shouldn't we respect the delete flag?
14256            cleanUpResourcesLI();
14257            return true;
14258        }
14259    }
14260
14261    private boolean isAsecExternal(String cid) {
14262        final String asecPath = PackageHelper.getSdFilesystem(cid);
14263        return !asecPath.startsWith(mAsecInternalPath);
14264    }
14265
14266    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14267            PackageManagerException {
14268        if (copyRet < 0) {
14269            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14270                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14271                throw new PackageManagerException(copyRet, message);
14272            }
14273        }
14274    }
14275
14276    /**
14277     * Extract the StorageManagerService "container ID" from the full code path of an
14278     * .apk.
14279     */
14280    static String cidFromCodePath(String fullCodePath) {
14281        int eidx = fullCodePath.lastIndexOf("/");
14282        String subStr1 = fullCodePath.substring(0, eidx);
14283        int sidx = subStr1.lastIndexOf("/");
14284        return subStr1.substring(sidx+1, eidx);
14285    }
14286
14287    /**
14288     * Logic to handle installation of ASEC applications, including copying and
14289     * renaming logic.
14290     */
14291    class AsecInstallArgs extends InstallArgs {
14292        static final String RES_FILE_NAME = "pkg.apk";
14293        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14294
14295        String cid;
14296        String packagePath;
14297        String resourcePath;
14298
14299        /** New install */
14300        AsecInstallArgs(InstallParams params) {
14301            super(params.origin, params.move, params.observer, params.installFlags,
14302                    params.installerPackageName, params.volumeUuid,
14303                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14304                    params.grantedRuntimePermissions,
14305                    params.traceMethod, params.traceCookie, params.certificates,
14306                    params.installReason);
14307        }
14308
14309        /** Existing install */
14310        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14311                        boolean isExternal, boolean isForwardLocked) {
14312            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14313                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14314                    instructionSets, null, null, null, 0, null /*certificates*/,
14315                    PackageManager.INSTALL_REASON_UNKNOWN);
14316            // Hackily pretend we're still looking at a full code path
14317            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14318                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14319            }
14320
14321            // Extract cid from fullCodePath
14322            int eidx = fullCodePath.lastIndexOf("/");
14323            String subStr1 = fullCodePath.substring(0, eidx);
14324            int sidx = subStr1.lastIndexOf("/");
14325            cid = subStr1.substring(sidx+1, eidx);
14326            setMountPath(subStr1);
14327        }
14328
14329        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14330            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14331                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14332                    instructionSets, null, null, null, 0, null /*certificates*/,
14333                    PackageManager.INSTALL_REASON_UNKNOWN);
14334            this.cid = cid;
14335            setMountPath(PackageHelper.getSdDir(cid));
14336        }
14337
14338        void createCopyFile() {
14339            cid = mInstallerService.allocateExternalStageCidLegacy();
14340        }
14341
14342        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14343            if (origin.staged && origin.cid != null) {
14344                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14345                cid = origin.cid;
14346                setMountPath(PackageHelper.getSdDir(cid));
14347                return PackageManager.INSTALL_SUCCEEDED;
14348            }
14349
14350            if (temp) {
14351                createCopyFile();
14352            } else {
14353                /*
14354                 * Pre-emptively destroy the container since it's destroyed if
14355                 * copying fails due to it existing anyway.
14356                 */
14357                PackageHelper.destroySdDir(cid);
14358            }
14359
14360            final String newMountPath = imcs.copyPackageToContainer(
14361                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14362                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14363
14364            if (newMountPath != null) {
14365                setMountPath(newMountPath);
14366                return PackageManager.INSTALL_SUCCEEDED;
14367            } else {
14368                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14369            }
14370        }
14371
14372        @Override
14373        String getCodePath() {
14374            return packagePath;
14375        }
14376
14377        @Override
14378        String getResourcePath() {
14379            return resourcePath;
14380        }
14381
14382        int doPreInstall(int status) {
14383            if (status != PackageManager.INSTALL_SUCCEEDED) {
14384                // Destroy container
14385                PackageHelper.destroySdDir(cid);
14386            } else {
14387                boolean mounted = PackageHelper.isContainerMounted(cid);
14388                if (!mounted) {
14389                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14390                            Process.SYSTEM_UID);
14391                    if (newMountPath != null) {
14392                        setMountPath(newMountPath);
14393                    } else {
14394                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14395                    }
14396                }
14397            }
14398            return status;
14399        }
14400
14401        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14402            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14403            String newMountPath = null;
14404            if (PackageHelper.isContainerMounted(cid)) {
14405                // Unmount the container
14406                if (!PackageHelper.unMountSdDir(cid)) {
14407                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14408                    return false;
14409                }
14410            }
14411            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14412                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14413                        " which might be stale. Will try to clean up.");
14414                // Clean up the stale container and proceed to recreate.
14415                if (!PackageHelper.destroySdDir(newCacheId)) {
14416                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14417                    return false;
14418                }
14419                // Successfully cleaned up stale container. Try to rename again.
14420                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14421                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14422                            + " inspite of cleaning it up.");
14423                    return false;
14424                }
14425            }
14426            if (!PackageHelper.isContainerMounted(newCacheId)) {
14427                Slog.w(TAG, "Mounting container " + newCacheId);
14428                newMountPath = PackageHelper.mountSdDir(newCacheId,
14429                        getEncryptKey(), Process.SYSTEM_UID);
14430            } else {
14431                newMountPath = PackageHelper.getSdDir(newCacheId);
14432            }
14433            if (newMountPath == null) {
14434                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14435                return false;
14436            }
14437            Log.i(TAG, "Succesfully renamed " + cid +
14438                    " to " + newCacheId +
14439                    " at new path: " + newMountPath);
14440            cid = newCacheId;
14441
14442            final File beforeCodeFile = new File(packagePath);
14443            setMountPath(newMountPath);
14444            final File afterCodeFile = new File(packagePath);
14445
14446            // Reflect the rename in scanned details
14447            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14448            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14449                    afterCodeFile, pkg.baseCodePath));
14450            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14451                    afterCodeFile, pkg.splitCodePaths));
14452
14453            // Reflect the rename in app info
14454            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14455            pkg.setApplicationInfoCodePath(pkg.codePath);
14456            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14457            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14458            pkg.setApplicationInfoResourcePath(pkg.codePath);
14459            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14460            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14461
14462            return true;
14463        }
14464
14465        private void setMountPath(String mountPath) {
14466            final File mountFile = new File(mountPath);
14467
14468            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14469            if (monolithicFile.exists()) {
14470                packagePath = monolithicFile.getAbsolutePath();
14471                if (isFwdLocked()) {
14472                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14473                } else {
14474                    resourcePath = packagePath;
14475                }
14476            } else {
14477                packagePath = mountFile.getAbsolutePath();
14478                resourcePath = packagePath;
14479            }
14480        }
14481
14482        int doPostInstall(int status, int uid) {
14483            if (status != PackageManager.INSTALL_SUCCEEDED) {
14484                cleanUp();
14485            } else {
14486                final int groupOwner;
14487                final String protectedFile;
14488                if (isFwdLocked()) {
14489                    groupOwner = UserHandle.getSharedAppGid(uid);
14490                    protectedFile = RES_FILE_NAME;
14491                } else {
14492                    groupOwner = -1;
14493                    protectedFile = null;
14494                }
14495
14496                if (uid < Process.FIRST_APPLICATION_UID
14497                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14498                    Slog.e(TAG, "Failed to finalize " + cid);
14499                    PackageHelper.destroySdDir(cid);
14500                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14501                }
14502
14503                boolean mounted = PackageHelper.isContainerMounted(cid);
14504                if (!mounted) {
14505                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14506                }
14507            }
14508            return status;
14509        }
14510
14511        private void cleanUp() {
14512            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14513
14514            // Destroy secure container
14515            PackageHelper.destroySdDir(cid);
14516        }
14517
14518        private List<String> getAllCodePaths() {
14519            final File codeFile = new File(getCodePath());
14520            if (codeFile != null && codeFile.exists()) {
14521                try {
14522                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14523                    return pkg.getAllCodePaths();
14524                } catch (PackageParserException e) {
14525                    // Ignored; we tried our best
14526                }
14527            }
14528            return Collections.EMPTY_LIST;
14529        }
14530
14531        void cleanUpResourcesLI() {
14532            // Enumerate all code paths before deleting
14533            cleanUpResourcesLI(getAllCodePaths());
14534        }
14535
14536        private void cleanUpResourcesLI(List<String> allCodePaths) {
14537            cleanUp();
14538            removeDexFiles(allCodePaths, instructionSets);
14539        }
14540
14541        String getPackageName() {
14542            return getAsecPackageName(cid);
14543        }
14544
14545        boolean doPostDeleteLI(boolean delete) {
14546            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14547            final List<String> allCodePaths = getAllCodePaths();
14548            boolean mounted = PackageHelper.isContainerMounted(cid);
14549            if (mounted) {
14550                // Unmount first
14551                if (PackageHelper.unMountSdDir(cid)) {
14552                    mounted = false;
14553                }
14554            }
14555            if (!mounted && delete) {
14556                cleanUpResourcesLI(allCodePaths);
14557            }
14558            return !mounted;
14559        }
14560
14561        @Override
14562        int doPreCopy() {
14563            if (isFwdLocked()) {
14564                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14565                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14566                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14567                }
14568            }
14569
14570            return PackageManager.INSTALL_SUCCEEDED;
14571        }
14572
14573        @Override
14574        int doPostCopy(int uid) {
14575            if (isFwdLocked()) {
14576                if (uid < Process.FIRST_APPLICATION_UID
14577                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14578                                RES_FILE_NAME)) {
14579                    Slog.e(TAG, "Failed to finalize " + cid);
14580                    PackageHelper.destroySdDir(cid);
14581                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14582                }
14583            }
14584
14585            return PackageManager.INSTALL_SUCCEEDED;
14586        }
14587    }
14588
14589    /**
14590     * Logic to handle movement of existing installed applications.
14591     */
14592    class MoveInstallArgs extends InstallArgs {
14593        private File codeFile;
14594        private File resourceFile;
14595
14596        /** New install */
14597        MoveInstallArgs(InstallParams params) {
14598            super(params.origin, params.move, params.observer, params.installFlags,
14599                    params.installerPackageName, params.volumeUuid,
14600                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14601                    params.grantedRuntimePermissions,
14602                    params.traceMethod, params.traceCookie, params.certificates,
14603                    params.installReason);
14604        }
14605
14606        int copyApk(IMediaContainerService imcs, boolean temp) {
14607            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14608                    + move.fromUuid + " to " + move.toUuid);
14609            synchronized (mInstaller) {
14610                try {
14611                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14612                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14613                } catch (InstallerException e) {
14614                    Slog.w(TAG, "Failed to move app", e);
14615                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14616                }
14617            }
14618
14619            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14620            resourceFile = codeFile;
14621            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14622
14623            return PackageManager.INSTALL_SUCCEEDED;
14624        }
14625
14626        int doPreInstall(int status) {
14627            if (status != PackageManager.INSTALL_SUCCEEDED) {
14628                cleanUp(move.toUuid);
14629            }
14630            return status;
14631        }
14632
14633        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14634            if (status != PackageManager.INSTALL_SUCCEEDED) {
14635                cleanUp(move.toUuid);
14636                return false;
14637            }
14638
14639            // Reflect the move in app info
14640            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14641            pkg.setApplicationInfoCodePath(pkg.codePath);
14642            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14643            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14644            pkg.setApplicationInfoResourcePath(pkg.codePath);
14645            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14646            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14647
14648            return true;
14649        }
14650
14651        int doPostInstall(int status, int uid) {
14652            if (status == PackageManager.INSTALL_SUCCEEDED) {
14653                cleanUp(move.fromUuid);
14654            } else {
14655                cleanUp(move.toUuid);
14656            }
14657            return status;
14658        }
14659
14660        @Override
14661        String getCodePath() {
14662            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14663        }
14664
14665        @Override
14666        String getResourcePath() {
14667            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14668        }
14669
14670        private boolean cleanUp(String volumeUuid) {
14671            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14672                    move.dataAppName);
14673            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14674            final int[] userIds = sUserManager.getUserIds();
14675            synchronized (mInstallLock) {
14676                // Clean up both app data and code
14677                // All package moves are frozen until finished
14678                for (int userId : userIds) {
14679                    try {
14680                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14681                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14682                    } catch (InstallerException e) {
14683                        Slog.w(TAG, String.valueOf(e));
14684                    }
14685                }
14686                removeCodePathLI(codeFile);
14687            }
14688            return true;
14689        }
14690
14691        void cleanUpResourcesLI() {
14692            throw new UnsupportedOperationException();
14693        }
14694
14695        boolean doPostDeleteLI(boolean delete) {
14696            throw new UnsupportedOperationException();
14697        }
14698    }
14699
14700    static String getAsecPackageName(String packageCid) {
14701        int idx = packageCid.lastIndexOf("-");
14702        if (idx == -1) {
14703            return packageCid;
14704        }
14705        return packageCid.substring(0, idx);
14706    }
14707
14708    // Utility method used to create code paths based on package name and available index.
14709    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14710        String idxStr = "";
14711        int idx = 1;
14712        // Fall back to default value of idx=1 if prefix is not
14713        // part of oldCodePath
14714        if (oldCodePath != null) {
14715            String subStr = oldCodePath;
14716            // Drop the suffix right away
14717            if (suffix != null && subStr.endsWith(suffix)) {
14718                subStr = subStr.substring(0, subStr.length() - suffix.length());
14719            }
14720            // If oldCodePath already contains prefix find out the
14721            // ending index to either increment or decrement.
14722            int sidx = subStr.lastIndexOf(prefix);
14723            if (sidx != -1) {
14724                subStr = subStr.substring(sidx + prefix.length());
14725                if (subStr != null) {
14726                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14727                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14728                    }
14729                    try {
14730                        idx = Integer.parseInt(subStr);
14731                        if (idx <= 1) {
14732                            idx++;
14733                        } else {
14734                            idx--;
14735                        }
14736                    } catch(NumberFormatException e) {
14737                    }
14738                }
14739            }
14740        }
14741        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14742        return prefix + idxStr;
14743    }
14744
14745    private File getNextCodePath(File targetDir, String packageName) {
14746        File result;
14747        SecureRandom random = new SecureRandom();
14748        byte[] bytes = new byte[16];
14749        do {
14750            random.nextBytes(bytes);
14751            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14752            result = new File(targetDir, packageName + "-" + suffix);
14753        } while (result.exists());
14754        return result;
14755    }
14756
14757    // Utility method that returns the relative package path with respect
14758    // to the installation directory. Like say for /data/data/com.test-1.apk
14759    // string com.test-1 is returned.
14760    static String deriveCodePathName(String codePath) {
14761        if (codePath == null) {
14762            return null;
14763        }
14764        final File codeFile = new File(codePath);
14765        final String name = codeFile.getName();
14766        if (codeFile.isDirectory()) {
14767            return name;
14768        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14769            final int lastDot = name.lastIndexOf('.');
14770            return name.substring(0, lastDot);
14771        } else {
14772            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14773            return null;
14774        }
14775    }
14776
14777    static class PackageInstalledInfo {
14778        String name;
14779        int uid;
14780        // The set of users that originally had this package installed.
14781        int[] origUsers;
14782        // The set of users that now have this package installed.
14783        int[] newUsers;
14784        PackageParser.Package pkg;
14785        int returnCode;
14786        String returnMsg;
14787        PackageRemovedInfo removedInfo;
14788        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14789
14790        public void setError(int code, String msg) {
14791            setReturnCode(code);
14792            setReturnMessage(msg);
14793            Slog.w(TAG, msg);
14794        }
14795
14796        public void setError(String msg, PackageParserException e) {
14797            setReturnCode(e.error);
14798            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14799            Slog.w(TAG, msg, e);
14800        }
14801
14802        public void setError(String msg, PackageManagerException e) {
14803            returnCode = e.error;
14804            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14805            Slog.w(TAG, msg, e);
14806        }
14807
14808        public void setReturnCode(int returnCode) {
14809            this.returnCode = returnCode;
14810            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14811            for (int i = 0; i < childCount; i++) {
14812                addedChildPackages.valueAt(i).returnCode = returnCode;
14813            }
14814        }
14815
14816        private void setReturnMessage(String returnMsg) {
14817            this.returnMsg = returnMsg;
14818            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14819            for (int i = 0; i < childCount; i++) {
14820                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14821            }
14822        }
14823
14824        // In some error cases we want to convey more info back to the observer
14825        String origPackage;
14826        String origPermission;
14827    }
14828
14829    /*
14830     * Install a non-existing package.
14831     */
14832    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14833            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14834            PackageInstalledInfo res, int installReason) {
14835        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14836
14837        // Remember this for later, in case we need to rollback this install
14838        String pkgName = pkg.packageName;
14839
14840        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14841
14842        synchronized(mPackages) {
14843            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14844            if (renamedPackage != null) {
14845                // A package with the same name is already installed, though
14846                // it has been renamed to an older name.  The package we
14847                // are trying to install should be installed as an update to
14848                // the existing one, but that has not been requested, so bail.
14849                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14850                        + " without first uninstalling package running as "
14851                        + renamedPackage);
14852                return;
14853            }
14854            if (mPackages.containsKey(pkgName)) {
14855                // Don't allow installation over an existing package with the same name.
14856                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14857                        + " without first uninstalling.");
14858                return;
14859            }
14860        }
14861
14862        try {
14863            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14864                    System.currentTimeMillis(), user);
14865
14866            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
14867
14868            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14869                prepareAppDataAfterInstallLIF(newPackage);
14870
14871            } else {
14872                // Remove package from internal structures, but keep around any
14873                // data that might have already existed
14874                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14875                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14876            }
14877        } catch (PackageManagerException e) {
14878            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14879        }
14880
14881        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14882    }
14883
14884    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14885        // Can't rotate keys during boot or if sharedUser.
14886        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14887                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14888            return false;
14889        }
14890        // app is using upgradeKeySets; make sure all are valid
14891        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14892        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14893        for (int i = 0; i < upgradeKeySets.length; i++) {
14894            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14895                Slog.wtf(TAG, "Package "
14896                         + (oldPs.name != null ? oldPs.name : "<null>")
14897                         + " contains upgrade-key-set reference to unknown key-set: "
14898                         + upgradeKeySets[i]
14899                         + " reverting to signatures check.");
14900                return false;
14901            }
14902        }
14903        return true;
14904    }
14905
14906    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14907        // Upgrade keysets are being used.  Determine if new package has a superset of the
14908        // required keys.
14909        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14910        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14911        for (int i = 0; i < upgradeKeySets.length; i++) {
14912            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14913            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14914                return true;
14915            }
14916        }
14917        return false;
14918    }
14919
14920    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14921        try (DigestInputStream digestStream =
14922                new DigestInputStream(new FileInputStream(file), digest)) {
14923            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14924        }
14925    }
14926
14927    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14928            UserHandle user, String installerPackageName, PackageInstalledInfo res,
14929            int installReason) {
14930        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14931
14932        final PackageParser.Package oldPackage;
14933        final String pkgName = pkg.packageName;
14934        final int[] allUsers;
14935        final int[] installedUsers;
14936
14937        synchronized(mPackages) {
14938            oldPackage = mPackages.get(pkgName);
14939            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14940
14941            // don't allow upgrade to target a release SDK from a pre-release SDK
14942            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14943                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14944            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14945                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14946            if (oldTargetsPreRelease
14947                    && !newTargetsPreRelease
14948                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14949                Slog.w(TAG, "Can't install package targeting released sdk");
14950                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14951                return;
14952            }
14953
14954            // don't allow an upgrade from full to ephemeral
14955            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14956            if (isEphemeral && !oldIsEphemeral) {
14957                // can't downgrade from full to ephemeral
14958                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14959                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14960                return;
14961            }
14962
14963            // verify signatures are valid
14964            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14965            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14966                if (!checkUpgradeKeySetLP(ps, pkg)) {
14967                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14968                            "New package not signed by keys specified by upgrade-keysets: "
14969                                    + pkgName);
14970                    return;
14971                }
14972            } else {
14973                // default to original signature matching
14974                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14975                        != PackageManager.SIGNATURE_MATCH) {
14976                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14977                            "New package has a different signature: " + pkgName);
14978                    return;
14979                }
14980            }
14981
14982            // don't allow a system upgrade unless the upgrade hash matches
14983            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14984                byte[] digestBytes = null;
14985                try {
14986                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14987                    updateDigest(digest, new File(pkg.baseCodePath));
14988                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14989                        for (String path : pkg.splitCodePaths) {
14990                            updateDigest(digest, new File(path));
14991                        }
14992                    }
14993                    digestBytes = digest.digest();
14994                } catch (NoSuchAlgorithmException | IOException e) {
14995                    res.setError(INSTALL_FAILED_INVALID_APK,
14996                            "Could not compute hash: " + pkgName);
14997                    return;
14998                }
14999                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15000                    res.setError(INSTALL_FAILED_INVALID_APK,
15001                            "New package fails restrict-update check: " + pkgName);
15002                    return;
15003                }
15004                // retain upgrade restriction
15005                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15006            }
15007
15008            // Check for shared user id changes
15009            String invalidPackageName =
15010                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15011            if (invalidPackageName != null) {
15012                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15013                        "Package " + invalidPackageName + " tried to change user "
15014                                + oldPackage.mSharedUserId);
15015                return;
15016            }
15017
15018            // In case of rollback, remember per-user/profile install state
15019            allUsers = sUserManager.getUserIds();
15020            installedUsers = ps.queryInstalledUsers(allUsers, true);
15021        }
15022
15023        // Update what is removed
15024        res.removedInfo = new PackageRemovedInfo();
15025        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15026        res.removedInfo.removedPackage = oldPackage.packageName;
15027        res.removedInfo.isUpdate = true;
15028        res.removedInfo.origUsers = installedUsers;
15029        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15030        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15031        for (int i = 0; i < installedUsers.length; i++) {
15032            final int userId = installedUsers[i];
15033            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15034        }
15035
15036        final int childCount = (oldPackage.childPackages != null)
15037                ? oldPackage.childPackages.size() : 0;
15038        for (int i = 0; i < childCount; i++) {
15039            boolean childPackageUpdated = false;
15040            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15041            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15042            if (res.addedChildPackages != null) {
15043                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15044                if (childRes != null) {
15045                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15046                    childRes.removedInfo.removedPackage = childPkg.packageName;
15047                    childRes.removedInfo.isUpdate = true;
15048                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15049                    childPackageUpdated = true;
15050                }
15051            }
15052            if (!childPackageUpdated) {
15053                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15054                childRemovedRes.removedPackage = childPkg.packageName;
15055                childRemovedRes.isUpdate = false;
15056                childRemovedRes.dataRemoved = true;
15057                synchronized (mPackages) {
15058                    if (childPs != null) {
15059                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15060                    }
15061                }
15062                if (res.removedInfo.removedChildPackages == null) {
15063                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15064                }
15065                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15066            }
15067        }
15068
15069        boolean sysPkg = (isSystemApp(oldPackage));
15070        if (sysPkg) {
15071            // Set the system/privileged flags as needed
15072            final boolean privileged =
15073                    (oldPackage.applicationInfo.privateFlags
15074                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15075            final int systemPolicyFlags = policyFlags
15076                    | PackageParser.PARSE_IS_SYSTEM
15077                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15078
15079            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15080                    user, allUsers, installerPackageName, res, installReason);
15081        } else {
15082            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15083                    user, allUsers, installerPackageName, res, installReason);
15084        }
15085    }
15086
15087    public List<String> getPreviousCodePaths(String packageName) {
15088        final PackageSetting ps = mSettings.mPackages.get(packageName);
15089        final List<String> result = new ArrayList<String>();
15090        if (ps != null && ps.oldCodePaths != null) {
15091            result.addAll(ps.oldCodePaths);
15092        }
15093        return result;
15094    }
15095
15096    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15097            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15098            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15099            int installReason) {
15100        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15101                + deletedPackage);
15102
15103        String pkgName = deletedPackage.packageName;
15104        boolean deletedPkg = true;
15105        boolean addedPkg = false;
15106        boolean updatedSettings = false;
15107        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15108        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15109                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15110
15111        final long origUpdateTime = (pkg.mExtras != null)
15112                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15113
15114        // First delete the existing package while retaining the data directory
15115        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15116                res.removedInfo, true, pkg)) {
15117            // If the existing package wasn't successfully deleted
15118            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15119            deletedPkg = false;
15120        } else {
15121            // Successfully deleted the old package; proceed with replace.
15122
15123            // If deleted package lived in a container, give users a chance to
15124            // relinquish resources before killing.
15125            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15126                if (DEBUG_INSTALL) {
15127                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15128                }
15129                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15130                final ArrayList<String> pkgList = new ArrayList<String>(1);
15131                pkgList.add(deletedPackage.applicationInfo.packageName);
15132                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15133            }
15134
15135            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15136                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15137            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15138
15139            try {
15140                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15141                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15142                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15143                        installReason);
15144
15145                // Update the in-memory copy of the previous code paths.
15146                PackageSetting ps = mSettings.mPackages.get(pkgName);
15147                if (!killApp) {
15148                    if (ps.oldCodePaths == null) {
15149                        ps.oldCodePaths = new ArraySet<>();
15150                    }
15151                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15152                    if (deletedPackage.splitCodePaths != null) {
15153                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15154                    }
15155                } else {
15156                    ps.oldCodePaths = null;
15157                }
15158                if (ps.childPackageNames != null) {
15159                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15160                        final String childPkgName = ps.childPackageNames.get(i);
15161                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15162                        childPs.oldCodePaths = ps.oldCodePaths;
15163                    }
15164                }
15165                prepareAppDataAfterInstallLIF(newPackage);
15166                addedPkg = true;
15167            } catch (PackageManagerException e) {
15168                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15169            }
15170        }
15171
15172        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15173            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15174
15175            // Revert all internal state mutations and added folders for the failed install
15176            if (addedPkg) {
15177                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15178                        res.removedInfo, true, null);
15179            }
15180
15181            // Restore the old package
15182            if (deletedPkg) {
15183                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15184                File restoreFile = new File(deletedPackage.codePath);
15185                // Parse old package
15186                boolean oldExternal = isExternal(deletedPackage);
15187                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15188                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15189                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15190                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15191                try {
15192                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15193                            null);
15194                } catch (PackageManagerException e) {
15195                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15196                            + e.getMessage());
15197                    return;
15198                }
15199
15200                synchronized (mPackages) {
15201                    // Ensure the installer package name up to date
15202                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15203
15204                    // Update permissions for restored package
15205                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15206
15207                    mSettings.writeLPr();
15208                }
15209
15210                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15211            }
15212        } else {
15213            synchronized (mPackages) {
15214                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15215                if (ps != null) {
15216                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15217                    if (res.removedInfo.removedChildPackages != null) {
15218                        final int childCount = res.removedInfo.removedChildPackages.size();
15219                        // Iterate in reverse as we may modify the collection
15220                        for (int i = childCount - 1; i >= 0; i--) {
15221                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15222                            if (res.addedChildPackages.containsKey(childPackageName)) {
15223                                res.removedInfo.removedChildPackages.removeAt(i);
15224                            } else {
15225                                PackageRemovedInfo childInfo = res.removedInfo
15226                                        .removedChildPackages.valueAt(i);
15227                                childInfo.removedForAllUsers = mPackages.get(
15228                                        childInfo.removedPackage) == null;
15229                            }
15230                        }
15231                    }
15232                }
15233            }
15234        }
15235    }
15236
15237    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15238            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15239            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15240            int installReason) {
15241        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15242                + ", old=" + deletedPackage);
15243
15244        final boolean disabledSystem;
15245
15246        // Remove existing system package
15247        removePackageLI(deletedPackage, true);
15248
15249        synchronized (mPackages) {
15250            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15251        }
15252        if (!disabledSystem) {
15253            // We didn't need to disable the .apk as a current system package,
15254            // which means we are replacing another update that is already
15255            // installed.  We need to make sure to delete the older one's .apk.
15256            res.removedInfo.args = createInstallArgsForExisting(0,
15257                    deletedPackage.applicationInfo.getCodePath(),
15258                    deletedPackage.applicationInfo.getResourcePath(),
15259                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15260        } else {
15261            res.removedInfo.args = null;
15262        }
15263
15264        // Successfully disabled the old package. Now proceed with re-installation
15265        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15266                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15267        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15268
15269        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15270        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15271                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15272
15273        PackageParser.Package newPackage = null;
15274        try {
15275            // Add the package to the internal data structures
15276            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15277
15278            // Set the update and install times
15279            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15280            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15281                    System.currentTimeMillis());
15282
15283            // Update the package dynamic state if succeeded
15284            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15285                // Now that the install succeeded make sure we remove data
15286                // directories for any child package the update removed.
15287                final int deletedChildCount = (deletedPackage.childPackages != null)
15288                        ? deletedPackage.childPackages.size() : 0;
15289                final int newChildCount = (newPackage.childPackages != null)
15290                        ? newPackage.childPackages.size() : 0;
15291                for (int i = 0; i < deletedChildCount; i++) {
15292                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15293                    boolean childPackageDeleted = true;
15294                    for (int j = 0; j < newChildCount; j++) {
15295                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15296                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15297                            childPackageDeleted = false;
15298                            break;
15299                        }
15300                    }
15301                    if (childPackageDeleted) {
15302                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15303                                deletedChildPkg.packageName);
15304                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15305                            PackageRemovedInfo removedChildRes = res.removedInfo
15306                                    .removedChildPackages.get(deletedChildPkg.packageName);
15307                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15308                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15309                        }
15310                    }
15311                }
15312
15313                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15314                        installReason);
15315                prepareAppDataAfterInstallLIF(newPackage);
15316            }
15317        } catch (PackageManagerException e) {
15318            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15319            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15320        }
15321
15322        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15323            // Re installation failed. Restore old information
15324            // Remove new pkg information
15325            if (newPackage != null) {
15326                removeInstalledPackageLI(newPackage, true);
15327            }
15328            // Add back the old system package
15329            try {
15330                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15331            } catch (PackageManagerException e) {
15332                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15333            }
15334
15335            synchronized (mPackages) {
15336                if (disabledSystem) {
15337                    enableSystemPackageLPw(deletedPackage);
15338                }
15339
15340                // Ensure the installer package name up to date
15341                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15342
15343                // Update permissions for restored package
15344                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15345
15346                mSettings.writeLPr();
15347            }
15348
15349            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15350                    + " after failed upgrade");
15351        }
15352    }
15353
15354    /**
15355     * Checks whether the parent or any of the child packages have a change shared
15356     * user. For a package to be a valid update the shred users of the parent and
15357     * the children should match. We may later support changing child shared users.
15358     * @param oldPkg The updated package.
15359     * @param newPkg The update package.
15360     * @return The shared user that change between the versions.
15361     */
15362    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15363            PackageParser.Package newPkg) {
15364        // Check parent shared user
15365        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15366            return newPkg.packageName;
15367        }
15368        // Check child shared users
15369        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15370        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15371        for (int i = 0; i < newChildCount; i++) {
15372            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15373            // If this child was present, did it have the same shared user?
15374            for (int j = 0; j < oldChildCount; j++) {
15375                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15376                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15377                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15378                    return newChildPkg.packageName;
15379                }
15380            }
15381        }
15382        return null;
15383    }
15384
15385    private void removeNativeBinariesLI(PackageSetting ps) {
15386        // Remove the lib path for the parent package
15387        if (ps != null) {
15388            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15389            // Remove the lib path for the child packages
15390            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15391            for (int i = 0; i < childCount; i++) {
15392                PackageSetting childPs = null;
15393                synchronized (mPackages) {
15394                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15395                }
15396                if (childPs != null) {
15397                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15398                            .legacyNativeLibraryPathString);
15399                }
15400            }
15401        }
15402    }
15403
15404    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15405        // Enable the parent package
15406        mSettings.enableSystemPackageLPw(pkg.packageName);
15407        // Enable the child packages
15408        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15409        for (int i = 0; i < childCount; i++) {
15410            PackageParser.Package childPkg = pkg.childPackages.get(i);
15411            mSettings.enableSystemPackageLPw(childPkg.packageName);
15412        }
15413    }
15414
15415    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15416            PackageParser.Package newPkg) {
15417        // Disable the parent package (parent always replaced)
15418        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15419        // Disable the child packages
15420        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15421        for (int i = 0; i < childCount; i++) {
15422            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15423            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15424            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15425        }
15426        return disabled;
15427    }
15428
15429    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15430            String installerPackageName) {
15431        // Enable the parent package
15432        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15433        // Enable the child packages
15434        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15435        for (int i = 0; i < childCount; i++) {
15436            PackageParser.Package childPkg = pkg.childPackages.get(i);
15437            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15438        }
15439    }
15440
15441    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15442        // Collect all used permissions in the UID
15443        ArraySet<String> usedPermissions = new ArraySet<>();
15444        final int packageCount = su.packages.size();
15445        for (int i = 0; i < packageCount; i++) {
15446            PackageSetting ps = su.packages.valueAt(i);
15447            if (ps.pkg == null) {
15448                continue;
15449            }
15450            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15451            for (int j = 0; j < requestedPermCount; j++) {
15452                String permission = ps.pkg.requestedPermissions.get(j);
15453                BasePermission bp = mSettings.mPermissions.get(permission);
15454                if (bp != null) {
15455                    usedPermissions.add(permission);
15456                }
15457            }
15458        }
15459
15460        PermissionsState permissionsState = su.getPermissionsState();
15461        // Prune install permissions
15462        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15463        final int installPermCount = installPermStates.size();
15464        for (int i = installPermCount - 1; i >= 0;  i--) {
15465            PermissionState permissionState = installPermStates.get(i);
15466            if (!usedPermissions.contains(permissionState.getName())) {
15467                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15468                if (bp != null) {
15469                    permissionsState.revokeInstallPermission(bp);
15470                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15471                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15472                }
15473            }
15474        }
15475
15476        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15477
15478        // Prune runtime permissions
15479        for (int userId : allUserIds) {
15480            List<PermissionState> runtimePermStates = permissionsState
15481                    .getRuntimePermissionStates(userId);
15482            final int runtimePermCount = runtimePermStates.size();
15483            for (int i = runtimePermCount - 1; i >= 0; i--) {
15484                PermissionState permissionState = runtimePermStates.get(i);
15485                if (!usedPermissions.contains(permissionState.getName())) {
15486                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15487                    if (bp != null) {
15488                        permissionsState.revokeRuntimePermission(bp, userId);
15489                        permissionsState.updatePermissionFlags(bp, userId,
15490                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15491                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15492                                runtimePermissionChangedUserIds, userId);
15493                    }
15494                }
15495            }
15496        }
15497
15498        return runtimePermissionChangedUserIds;
15499    }
15500
15501    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15502            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15503        // Update the parent package setting
15504        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15505                res, user, installReason);
15506        // Update the child packages setting
15507        final int childCount = (newPackage.childPackages != null)
15508                ? newPackage.childPackages.size() : 0;
15509        for (int i = 0; i < childCount; i++) {
15510            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15511            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15512            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15513                    childRes.origUsers, childRes, user, installReason);
15514        }
15515    }
15516
15517    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15518            String installerPackageName, int[] allUsers, int[] installedForUsers,
15519            PackageInstalledInfo res, UserHandle user, int installReason) {
15520        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15521
15522        String pkgName = newPackage.packageName;
15523        synchronized (mPackages) {
15524            //write settings. the installStatus will be incomplete at this stage.
15525            //note that the new package setting would have already been
15526            //added to mPackages. It hasn't been persisted yet.
15527            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15528            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15529            mSettings.writeLPr();
15530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15531        }
15532
15533        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15534        synchronized (mPackages) {
15535            updatePermissionsLPw(newPackage.packageName, newPackage,
15536                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15537                            ? UPDATE_PERMISSIONS_ALL : 0));
15538            // For system-bundled packages, we assume that installing an upgraded version
15539            // of the package implies that the user actually wants to run that new code,
15540            // so we enable the package.
15541            PackageSetting ps = mSettings.mPackages.get(pkgName);
15542            final int userId = user.getIdentifier();
15543            if (ps != null) {
15544                if (isSystemApp(newPackage)) {
15545                    if (DEBUG_INSTALL) {
15546                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15547                    }
15548                    // Enable system package for requested users
15549                    if (res.origUsers != null) {
15550                        for (int origUserId : res.origUsers) {
15551                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15552                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15553                                        origUserId, installerPackageName);
15554                            }
15555                        }
15556                    }
15557                    // Also convey the prior install/uninstall state
15558                    if (allUsers != null && installedForUsers != null) {
15559                        for (int currentUserId : allUsers) {
15560                            final boolean installed = ArrayUtils.contains(
15561                                    installedForUsers, currentUserId);
15562                            if (DEBUG_INSTALL) {
15563                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15564                            }
15565                            ps.setInstalled(installed, currentUserId);
15566                        }
15567                        // these install state changes will be persisted in the
15568                        // upcoming call to mSettings.writeLPr().
15569                    }
15570                }
15571                // It's implied that when a user requests installation, they want the app to be
15572                // installed and enabled.
15573                if (userId != UserHandle.USER_ALL) {
15574                    ps.setInstalled(true, userId);
15575                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15576                }
15577
15578                // When replacing an existing package, preserve the original install reason for all
15579                // users that had the package installed before.
15580                final Set<Integer> previousUserIds = new ArraySet<>();
15581                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15582                    final int installReasonCount = res.removedInfo.installReasons.size();
15583                    for (int i = 0; i < installReasonCount; i++) {
15584                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15585                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15586                        ps.setInstallReason(previousInstallReason, previousUserId);
15587                        previousUserIds.add(previousUserId);
15588                    }
15589                }
15590
15591                // Set install reason for users that are having the package newly installed.
15592                if (userId == UserHandle.USER_ALL) {
15593                    for (int currentUserId : sUserManager.getUserIds()) {
15594                        if (!previousUserIds.contains(currentUserId)) {
15595                            ps.setInstallReason(installReason, currentUserId);
15596                        }
15597                    }
15598                } else if (!previousUserIds.contains(userId)) {
15599                    ps.setInstallReason(installReason, userId);
15600                }
15601            }
15602            res.name = pkgName;
15603            res.uid = newPackage.applicationInfo.uid;
15604            res.pkg = newPackage;
15605            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15606            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15607            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15608            //to update install status
15609            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15610            mSettings.writeLPr();
15611            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15612        }
15613
15614        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15615    }
15616
15617    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15618        try {
15619            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15620            installPackageLI(args, res);
15621        } finally {
15622            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15623        }
15624    }
15625
15626    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15627        final int installFlags = args.installFlags;
15628        final String installerPackageName = args.installerPackageName;
15629        final String volumeUuid = args.volumeUuid;
15630        final File tmpPackageFile = new File(args.getCodePath());
15631        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15632        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15633                || (args.volumeUuid != null));
15634        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15635        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15636        boolean replace = false;
15637        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15638        if (args.move != null) {
15639            // moving a complete application; perform an initial scan on the new install location
15640            scanFlags |= SCAN_INITIAL;
15641        }
15642        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15643            scanFlags |= SCAN_DONT_KILL_APP;
15644        }
15645
15646        // Result object to be returned
15647        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15648
15649        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15650
15651        // Sanity check
15652        if (ephemeral && (forwardLocked || onExternal)) {
15653            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15654                    + " external=" + onExternal);
15655            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15656            return;
15657        }
15658
15659        // Retrieve PackageSettings and parse package
15660        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15661                | PackageParser.PARSE_ENFORCE_CODE
15662                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15663                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15664                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15665                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15666        PackageParser pp = new PackageParser();
15667        pp.setSeparateProcesses(mSeparateProcesses);
15668        pp.setDisplayMetrics(mMetrics);
15669
15670        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15671        final PackageParser.Package pkg;
15672        try {
15673            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15674        } catch (PackageParserException e) {
15675            res.setError("Failed parse during installPackageLI", e);
15676            return;
15677        } finally {
15678            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15679        }
15680
15681        // Ephemeral apps must have target SDK >= O.
15682        // TODO: Update conditional and error message when O gets locked down
15683        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15684            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15685                    "Ephemeral apps must have target SDK version of at least O");
15686            return;
15687        }
15688
15689        // If we are installing a clustered package add results for the children
15690        if (pkg.childPackages != null) {
15691            synchronized (mPackages) {
15692                final int childCount = pkg.childPackages.size();
15693                for (int i = 0; i < childCount; i++) {
15694                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15695                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15696                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15697                    childRes.pkg = childPkg;
15698                    childRes.name = childPkg.packageName;
15699                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15700                    if (childPs != null) {
15701                        childRes.origUsers = childPs.queryInstalledUsers(
15702                                sUserManager.getUserIds(), true);
15703                    }
15704                    if ((mPackages.containsKey(childPkg.packageName))) {
15705                        childRes.removedInfo = new PackageRemovedInfo();
15706                        childRes.removedInfo.removedPackage = childPkg.packageName;
15707                    }
15708                    if (res.addedChildPackages == null) {
15709                        res.addedChildPackages = new ArrayMap<>();
15710                    }
15711                    res.addedChildPackages.put(childPkg.packageName, childRes);
15712                }
15713            }
15714        }
15715
15716        // If package doesn't declare API override, mark that we have an install
15717        // time CPU ABI override.
15718        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15719            pkg.cpuAbiOverride = args.abiOverride;
15720        }
15721
15722        String pkgName = res.name = pkg.packageName;
15723        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15724            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15725                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15726                return;
15727            }
15728        }
15729
15730        try {
15731            // either use what we've been given or parse directly from the APK
15732            if (args.certificates != null) {
15733                try {
15734                    PackageParser.populateCertificates(pkg, args.certificates);
15735                } catch (PackageParserException e) {
15736                    // there was something wrong with the certificates we were given;
15737                    // try to pull them from the APK
15738                    PackageParser.collectCertificates(pkg, parseFlags);
15739                }
15740            } else {
15741                PackageParser.collectCertificates(pkg, parseFlags);
15742            }
15743        } catch (PackageParserException e) {
15744            res.setError("Failed collect during installPackageLI", e);
15745            return;
15746        }
15747
15748        // Get rid of all references to package scan path via parser.
15749        pp = null;
15750        String oldCodePath = null;
15751        boolean systemApp = false;
15752        synchronized (mPackages) {
15753            // Check if installing already existing package
15754            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15755                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15756                if (pkg.mOriginalPackages != null
15757                        && pkg.mOriginalPackages.contains(oldName)
15758                        && mPackages.containsKey(oldName)) {
15759                    // This package is derived from an original package,
15760                    // and this device has been updating from that original
15761                    // name.  We must continue using the original name, so
15762                    // rename the new package here.
15763                    pkg.setPackageName(oldName);
15764                    pkgName = pkg.packageName;
15765                    replace = true;
15766                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15767                            + oldName + " pkgName=" + pkgName);
15768                } else if (mPackages.containsKey(pkgName)) {
15769                    // This package, under its official name, already exists
15770                    // on the device; we should replace it.
15771                    replace = true;
15772                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15773                }
15774
15775                // Child packages are installed through the parent package
15776                if (pkg.parentPackage != null) {
15777                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15778                            "Package " + pkg.packageName + " is child of package "
15779                                    + pkg.parentPackage.parentPackage + ". Child packages "
15780                                    + "can be updated only through the parent package.");
15781                    return;
15782                }
15783
15784                if (replace) {
15785                    // Prevent apps opting out from runtime permissions
15786                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15787                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15788                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15789                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15790                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15791                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15792                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15793                                        + " doesn't support runtime permissions but the old"
15794                                        + " target SDK " + oldTargetSdk + " does.");
15795                        return;
15796                    }
15797
15798                    // Prevent installing of child packages
15799                    if (oldPackage.parentPackage != null) {
15800                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15801                                "Package " + pkg.packageName + " is child of package "
15802                                        + oldPackage.parentPackage + ". Child packages "
15803                                        + "can be updated only through the parent package.");
15804                        return;
15805                    }
15806                }
15807            }
15808
15809            PackageSetting ps = mSettings.mPackages.get(pkgName);
15810            if (ps != null) {
15811                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15812
15813                // Quick sanity check that we're signed correctly if updating;
15814                // we'll check this again later when scanning, but we want to
15815                // bail early here before tripping over redefined permissions.
15816                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15817                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15818                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15819                                + pkg.packageName + " upgrade keys do not match the "
15820                                + "previously installed version");
15821                        return;
15822                    }
15823                } else {
15824                    try {
15825                        verifySignaturesLP(ps, pkg);
15826                    } catch (PackageManagerException e) {
15827                        res.setError(e.error, e.getMessage());
15828                        return;
15829                    }
15830                }
15831
15832                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15833                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15834                    systemApp = (ps.pkg.applicationInfo.flags &
15835                            ApplicationInfo.FLAG_SYSTEM) != 0;
15836                }
15837                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15838            }
15839
15840            // Check whether the newly-scanned package wants to define an already-defined perm
15841            int N = pkg.permissions.size();
15842            for (int i = N-1; i >= 0; i--) {
15843                PackageParser.Permission perm = pkg.permissions.get(i);
15844                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15845                if (bp != null) {
15846                    // If the defining package is signed with our cert, it's okay.  This
15847                    // also includes the "updating the same package" case, of course.
15848                    // "updating same package" could also involve key-rotation.
15849                    final boolean sigsOk;
15850                    if (bp.sourcePackage.equals(pkg.packageName)
15851                            && (bp.packageSetting instanceof PackageSetting)
15852                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15853                                    scanFlags))) {
15854                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15855                    } else {
15856                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15857                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15858                    }
15859                    if (!sigsOk) {
15860                        // If the owning package is the system itself, we log but allow
15861                        // install to proceed; we fail the install on all other permission
15862                        // redefinitions.
15863                        if (!bp.sourcePackage.equals("android")) {
15864                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15865                                    + pkg.packageName + " attempting to redeclare permission "
15866                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15867                            res.origPermission = perm.info.name;
15868                            res.origPackage = bp.sourcePackage;
15869                            return;
15870                        } else {
15871                            Slog.w(TAG, "Package " + pkg.packageName
15872                                    + " attempting to redeclare system permission "
15873                                    + perm.info.name + "; ignoring new declaration");
15874                            pkg.permissions.remove(i);
15875                        }
15876                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15877                        // Prevent apps to change protection level to dangerous from any other
15878                        // type as this would allow a privilege escalation where an app adds a
15879                        // normal/signature permission in other app's group and later redefines
15880                        // it as dangerous leading to the group auto-grant.
15881                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15882                                == PermissionInfo.PROTECTION_DANGEROUS) {
15883                            if (bp != null && !bp.isRuntime()) {
15884                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15885                                        + "non-runtime permission " + perm.info.name
15886                                        + " to runtime; keeping old protection level");
15887                                perm.info.protectionLevel = bp.protectionLevel;
15888                            }
15889                        }
15890                    }
15891                }
15892            }
15893        }
15894
15895        if (systemApp) {
15896            if (onExternal) {
15897                // Abort update; system app can't be replaced with app on sdcard
15898                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15899                        "Cannot install updates to system apps on sdcard");
15900                return;
15901            } else if (ephemeral) {
15902                // Abort update; system app can't be replaced with an ephemeral app
15903                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15904                        "Cannot update a system app with an ephemeral app");
15905                return;
15906            }
15907        }
15908
15909        if (args.move != null) {
15910            // We did an in-place move, so dex is ready to roll
15911            scanFlags |= SCAN_NO_DEX;
15912            scanFlags |= SCAN_MOVE;
15913
15914            synchronized (mPackages) {
15915                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15916                if (ps == null) {
15917                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15918                            "Missing settings for moved package " + pkgName);
15919                }
15920
15921                // We moved the entire application as-is, so bring over the
15922                // previously derived ABI information.
15923                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15924                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15925            }
15926
15927        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15928            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15929            scanFlags |= SCAN_NO_DEX;
15930
15931            try {
15932                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15933                    args.abiOverride : pkg.cpuAbiOverride);
15934                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15935                        true /*extractLibs*/, mAppLib32InstallDir);
15936            } catch (PackageManagerException pme) {
15937                Slog.e(TAG, "Error deriving application ABI", pme);
15938                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15939                return;
15940            }
15941
15942            // Shared libraries for the package need to be updated.
15943            synchronized (mPackages) {
15944                try {
15945                    updateSharedLibrariesLPr(pkg, null);
15946                } catch (PackageManagerException e) {
15947                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15948                }
15949            }
15950            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15951            // Do not run PackageDexOptimizer through the local performDexOpt
15952            // method because `pkg` may not be in `mPackages` yet.
15953            //
15954            // Also, don't fail application installs if the dexopt step fails.
15955            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15956                    null /* instructionSets */, false /* checkProfiles */,
15957                    getCompilerFilterForReason(REASON_INSTALL),
15958                    getOrCreateCompilerPackageStats(pkg));
15959            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15960
15961            // Notify BackgroundDexOptService that the package has been changed.
15962            // If this is an update of a package which used to fail to compile,
15963            // BDOS will remove it from its blacklist.
15964            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15965        }
15966
15967        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15968            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15969            return;
15970        }
15971
15972        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15973
15974        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15975                "installPackageLI")) {
15976            if (replace) {
15977                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15978                        installerPackageName, res, args.installReason);
15979            } else {
15980                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15981                        args.user, installerPackageName, volumeUuid, res, args.installReason);
15982            }
15983        }
15984        synchronized (mPackages) {
15985            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15986            if (ps != null) {
15987                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15988            }
15989
15990            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15991            for (int i = 0; i < childCount; i++) {
15992                PackageParser.Package childPkg = pkg.childPackages.get(i);
15993                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15994                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15995                if (childPs != null) {
15996                    childRes.newUsers = childPs.queryInstalledUsers(
15997                            sUserManager.getUserIds(), true);
15998                }
15999            }
16000        }
16001    }
16002
16003    private void startIntentFilterVerifications(int userId, boolean replacing,
16004            PackageParser.Package pkg) {
16005        if (mIntentFilterVerifierComponent == null) {
16006            Slog.w(TAG, "No IntentFilter verification will not be done as "
16007                    + "there is no IntentFilterVerifier available!");
16008            return;
16009        }
16010
16011        final int verifierUid = getPackageUid(
16012                mIntentFilterVerifierComponent.getPackageName(),
16013                MATCH_DEBUG_TRIAGED_MISSING,
16014                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16015
16016        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16017        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16018        mHandler.sendMessage(msg);
16019
16020        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16021        for (int i = 0; i < childCount; i++) {
16022            PackageParser.Package childPkg = pkg.childPackages.get(i);
16023            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16024            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16025            mHandler.sendMessage(msg);
16026        }
16027    }
16028
16029    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16030            PackageParser.Package pkg) {
16031        int size = pkg.activities.size();
16032        if (size == 0) {
16033            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16034                    "No activity, so no need to verify any IntentFilter!");
16035            return;
16036        }
16037
16038        final boolean hasDomainURLs = hasDomainURLs(pkg);
16039        if (!hasDomainURLs) {
16040            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16041                    "No domain URLs, so no need to verify any IntentFilter!");
16042            return;
16043        }
16044
16045        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16046                + " if any IntentFilter from the " + size
16047                + " Activities needs verification ...");
16048
16049        int count = 0;
16050        final String packageName = pkg.packageName;
16051
16052        synchronized (mPackages) {
16053            // If this is a new install and we see that we've already run verification for this
16054            // package, we have nothing to do: it means the state was restored from backup.
16055            if (!replacing) {
16056                IntentFilterVerificationInfo ivi =
16057                        mSettings.getIntentFilterVerificationLPr(packageName);
16058                if (ivi != null) {
16059                    if (DEBUG_DOMAIN_VERIFICATION) {
16060                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16061                                + ivi.getStatusString());
16062                    }
16063                    return;
16064                }
16065            }
16066
16067            // If any filters need to be verified, then all need to be.
16068            boolean needToVerify = false;
16069            for (PackageParser.Activity a : pkg.activities) {
16070                for (ActivityIntentInfo filter : a.intents) {
16071                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16072                        if (DEBUG_DOMAIN_VERIFICATION) {
16073                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16074                        }
16075                        needToVerify = true;
16076                        break;
16077                    }
16078                }
16079            }
16080
16081            if (needToVerify) {
16082                final int verificationId = mIntentFilterVerificationToken++;
16083                for (PackageParser.Activity a : pkg.activities) {
16084                    for (ActivityIntentInfo filter : a.intents) {
16085                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16086                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16087                                    "Verification needed for IntentFilter:" + filter.toString());
16088                            mIntentFilterVerifier.addOneIntentFilterVerification(
16089                                    verifierUid, userId, verificationId, filter, packageName);
16090                            count++;
16091                        }
16092                    }
16093                }
16094            }
16095        }
16096
16097        if (count > 0) {
16098            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16099                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16100                    +  " for userId:" + userId);
16101            mIntentFilterVerifier.startVerifications(userId);
16102        } else {
16103            if (DEBUG_DOMAIN_VERIFICATION) {
16104                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16105            }
16106        }
16107    }
16108
16109    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16110        final ComponentName cn  = filter.activity.getComponentName();
16111        final String packageName = cn.getPackageName();
16112
16113        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16114                packageName);
16115        if (ivi == null) {
16116            return true;
16117        }
16118        int status = ivi.getStatus();
16119        switch (status) {
16120            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16121            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16122                return true;
16123
16124            default:
16125                // Nothing to do
16126                return false;
16127        }
16128    }
16129
16130    private static boolean isMultiArch(ApplicationInfo info) {
16131        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16132    }
16133
16134    private static boolean isExternal(PackageParser.Package pkg) {
16135        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16136    }
16137
16138    private static boolean isExternal(PackageSetting ps) {
16139        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16140    }
16141
16142    private static boolean isEphemeral(PackageParser.Package pkg) {
16143        return pkg.applicationInfo.isEphemeralApp();
16144    }
16145
16146    private static boolean isEphemeral(PackageSetting ps) {
16147        return ps.pkg != null && isEphemeral(ps.pkg);
16148    }
16149
16150    private static boolean isSystemApp(PackageParser.Package pkg) {
16151        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16152    }
16153
16154    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16155        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16156    }
16157
16158    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16159        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16160    }
16161
16162    private static boolean isSystemApp(PackageSetting ps) {
16163        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16164    }
16165
16166    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16167        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16168    }
16169
16170    private int packageFlagsToInstallFlags(PackageSetting ps) {
16171        int installFlags = 0;
16172        if (isEphemeral(ps)) {
16173            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16174        }
16175        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16176            // This existing package was an external ASEC install when we have
16177            // the external flag without a UUID
16178            installFlags |= PackageManager.INSTALL_EXTERNAL;
16179        }
16180        if (ps.isForwardLocked()) {
16181            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16182        }
16183        return installFlags;
16184    }
16185
16186    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16187        if (isExternal(pkg)) {
16188            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16189                return StorageManager.UUID_PRIMARY_PHYSICAL;
16190            } else {
16191                return pkg.volumeUuid;
16192            }
16193        } else {
16194            return StorageManager.UUID_PRIVATE_INTERNAL;
16195        }
16196    }
16197
16198    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16199        if (isExternal(pkg)) {
16200            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16201                return mSettings.getExternalVersion();
16202            } else {
16203                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16204            }
16205        } else {
16206            return mSettings.getInternalVersion();
16207        }
16208    }
16209
16210    private void deleteTempPackageFiles() {
16211        final FilenameFilter filter = new FilenameFilter() {
16212            public boolean accept(File dir, String name) {
16213                return name.startsWith("vmdl") && name.endsWith(".tmp");
16214            }
16215        };
16216        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16217            file.delete();
16218        }
16219    }
16220
16221    @Override
16222    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16223            int flags) {
16224        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16225                flags);
16226    }
16227
16228    @Override
16229    public void deletePackage(final String packageName,
16230            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16231        mContext.enforceCallingOrSelfPermission(
16232                android.Manifest.permission.DELETE_PACKAGES, null);
16233        Preconditions.checkNotNull(packageName);
16234        Preconditions.checkNotNull(observer);
16235        final int uid = Binder.getCallingUid();
16236        if (!isOrphaned(packageName)
16237                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16238            try {
16239                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16240                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16241                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16242                observer.onUserActionRequired(intent);
16243            } catch (RemoteException re) {
16244            }
16245            return;
16246        }
16247        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16248        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16249        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16250            mContext.enforceCallingOrSelfPermission(
16251                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16252                    "deletePackage for user " + userId);
16253        }
16254
16255        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16256            try {
16257                observer.onPackageDeleted(packageName,
16258                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16259            } catch (RemoteException re) {
16260            }
16261            return;
16262        }
16263
16264        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16265            try {
16266                observer.onPackageDeleted(packageName,
16267                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16268            } catch (RemoteException re) {
16269            }
16270            return;
16271        }
16272
16273        if (DEBUG_REMOVE) {
16274            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16275                    + " deleteAllUsers: " + deleteAllUsers );
16276        }
16277        // Queue up an async operation since the package deletion may take a little while.
16278        mHandler.post(new Runnable() {
16279            public void run() {
16280                mHandler.removeCallbacks(this);
16281                int returnCode;
16282                if (!deleteAllUsers) {
16283                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16284                } else {
16285                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16286                    // If nobody is blocking uninstall, proceed with delete for all users
16287                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16288                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16289                    } else {
16290                        // Otherwise uninstall individually for users with blockUninstalls=false
16291                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16292                        for (int userId : users) {
16293                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16294                                returnCode = deletePackageX(packageName, userId, userFlags);
16295                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16296                                    Slog.w(TAG, "Package delete failed for user " + userId
16297                                            + ", returnCode " + returnCode);
16298                                }
16299                            }
16300                        }
16301                        // The app has only been marked uninstalled for certain users.
16302                        // We still need to report that delete was blocked
16303                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16304                    }
16305                }
16306                try {
16307                    observer.onPackageDeleted(packageName, returnCode, null);
16308                } catch (RemoteException e) {
16309                    Log.i(TAG, "Observer no longer exists.");
16310                } //end catch
16311            } //end run
16312        });
16313    }
16314
16315    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16316        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16317              || callingUid == Process.SYSTEM_UID) {
16318            return true;
16319        }
16320        final int callingUserId = UserHandle.getUserId(callingUid);
16321        // If the caller installed the pkgName, then allow it to silently uninstall.
16322        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16323            return true;
16324        }
16325
16326        // Allow package verifier to silently uninstall.
16327        if (mRequiredVerifierPackage != null &&
16328                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16329            return true;
16330        }
16331
16332        // Allow package uninstaller to silently uninstall.
16333        if (mRequiredUninstallerPackage != null &&
16334                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16335            return true;
16336        }
16337
16338        // Allow storage manager to silently uninstall.
16339        if (mStorageManagerPackage != null &&
16340                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16341            return true;
16342        }
16343        return false;
16344    }
16345
16346    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16347        int[] result = EMPTY_INT_ARRAY;
16348        for (int userId : userIds) {
16349            if (getBlockUninstallForUser(packageName, userId)) {
16350                result = ArrayUtils.appendInt(result, userId);
16351            }
16352        }
16353        return result;
16354    }
16355
16356    @Override
16357    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16358        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16359    }
16360
16361    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16362        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16363                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16364        try {
16365            if (dpm != null) {
16366                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16367                        /* callingUserOnly =*/ false);
16368                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16369                        : deviceOwnerComponentName.getPackageName();
16370                // Does the package contains the device owner?
16371                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16372                // this check is probably not needed, since DO should be registered as a device
16373                // admin on some user too. (Original bug for this: b/17657954)
16374                if (packageName.equals(deviceOwnerPackageName)) {
16375                    return true;
16376                }
16377                // Does it contain a device admin for any user?
16378                int[] users;
16379                if (userId == UserHandle.USER_ALL) {
16380                    users = sUserManager.getUserIds();
16381                } else {
16382                    users = new int[]{userId};
16383                }
16384                for (int i = 0; i < users.length; ++i) {
16385                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16386                        return true;
16387                    }
16388                }
16389            }
16390        } catch (RemoteException e) {
16391        }
16392        return false;
16393    }
16394
16395    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16396        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16397    }
16398
16399    /**
16400     *  This method is an internal method that could be get invoked either
16401     *  to delete an installed package or to clean up a failed installation.
16402     *  After deleting an installed package, a broadcast is sent to notify any
16403     *  listeners that the package has been removed. For cleaning up a failed
16404     *  installation, the broadcast is not necessary since the package's
16405     *  installation wouldn't have sent the initial broadcast either
16406     *  The key steps in deleting a package are
16407     *  deleting the package information in internal structures like mPackages,
16408     *  deleting the packages base directories through installd
16409     *  updating mSettings to reflect current status
16410     *  persisting settings for later use
16411     *  sending a broadcast if necessary
16412     */
16413    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16414        final PackageRemovedInfo info = new PackageRemovedInfo();
16415        final boolean res;
16416
16417        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16418                ? UserHandle.USER_ALL : userId;
16419
16420        if (isPackageDeviceAdmin(packageName, removeUser)) {
16421            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16422            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16423        }
16424
16425        PackageSetting uninstalledPs = null;
16426
16427        // for the uninstall-updates case and restricted profiles, remember the per-
16428        // user handle installed state
16429        int[] allUsers;
16430        synchronized (mPackages) {
16431            uninstalledPs = mSettings.mPackages.get(packageName);
16432            if (uninstalledPs == null) {
16433                Slog.w(TAG, "Not removing non-existent package " + packageName);
16434                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16435            }
16436            allUsers = sUserManager.getUserIds();
16437            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16438        }
16439
16440        final int freezeUser;
16441        if (isUpdatedSystemApp(uninstalledPs)
16442                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16443            // We're downgrading a system app, which will apply to all users, so
16444            // freeze them all during the downgrade
16445            freezeUser = UserHandle.USER_ALL;
16446        } else {
16447            freezeUser = removeUser;
16448        }
16449
16450        synchronized (mInstallLock) {
16451            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16452            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16453                    deleteFlags, "deletePackageX")) {
16454                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16455                        deleteFlags | REMOVE_CHATTY, info, true, null);
16456            }
16457            synchronized (mPackages) {
16458                if (res) {
16459                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16460                }
16461            }
16462        }
16463
16464        if (res) {
16465            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16466            info.sendPackageRemovedBroadcasts(killApp);
16467            info.sendSystemPackageUpdatedBroadcasts();
16468            info.sendSystemPackageAppearedBroadcasts();
16469        }
16470        // Force a gc here.
16471        Runtime.getRuntime().gc();
16472        // Delete the resources here after sending the broadcast to let
16473        // other processes clean up before deleting resources.
16474        if (info.args != null) {
16475            synchronized (mInstallLock) {
16476                info.args.doPostDeleteLI(true);
16477            }
16478        }
16479
16480        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16481    }
16482
16483    class PackageRemovedInfo {
16484        String removedPackage;
16485        int uid = -1;
16486        int removedAppId = -1;
16487        int[] origUsers;
16488        int[] removedUsers = null;
16489        SparseArray<Integer> installReasons;
16490        boolean isRemovedPackageSystemUpdate = false;
16491        boolean isUpdate;
16492        boolean dataRemoved;
16493        boolean removedForAllUsers;
16494        // Clean up resources deleted packages.
16495        InstallArgs args = null;
16496        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16497        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16498
16499        void sendPackageRemovedBroadcasts(boolean killApp) {
16500            sendPackageRemovedBroadcastInternal(killApp);
16501            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16502            for (int i = 0; i < childCount; i++) {
16503                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16504                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16505            }
16506        }
16507
16508        void sendSystemPackageUpdatedBroadcasts() {
16509            if (isRemovedPackageSystemUpdate) {
16510                sendSystemPackageUpdatedBroadcastsInternal();
16511                final int childCount = (removedChildPackages != null)
16512                        ? removedChildPackages.size() : 0;
16513                for (int i = 0; i < childCount; i++) {
16514                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16515                    if (childInfo.isRemovedPackageSystemUpdate) {
16516                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16517                    }
16518                }
16519            }
16520        }
16521
16522        void sendSystemPackageAppearedBroadcasts() {
16523            final int packageCount = (appearedChildPackages != null)
16524                    ? appearedChildPackages.size() : 0;
16525            for (int i = 0; i < packageCount; i++) {
16526                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16527                sendPackageAddedForNewUsers(installedInfo.name, true,
16528                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16529            }
16530        }
16531
16532        private void sendSystemPackageUpdatedBroadcastsInternal() {
16533            Bundle extras = new Bundle(2);
16534            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16535            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16536            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16537                    extras, 0, null, null, null);
16538            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16539                    extras, 0, null, null, null);
16540            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16541                    null, 0, removedPackage, null, null);
16542        }
16543
16544        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16545            Bundle extras = new Bundle(2);
16546            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16547            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16548            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16549            if (isUpdate || isRemovedPackageSystemUpdate) {
16550                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16551            }
16552            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16553            if (removedPackage != null) {
16554                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16555                        extras, 0, null, null, removedUsers);
16556                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16557                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16558                            removedPackage, extras, 0, null, null, removedUsers);
16559                }
16560            }
16561            if (removedAppId >= 0) {
16562                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16563                        removedUsers);
16564            }
16565        }
16566    }
16567
16568    /*
16569     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16570     * flag is not set, the data directory is removed as well.
16571     * make sure this flag is set for partially installed apps. If not its meaningless to
16572     * delete a partially installed application.
16573     */
16574    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16575            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16576        String packageName = ps.name;
16577        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16578        // Retrieve object to delete permissions for shared user later on
16579        final PackageParser.Package deletedPkg;
16580        final PackageSetting deletedPs;
16581        // reader
16582        synchronized (mPackages) {
16583            deletedPkg = mPackages.get(packageName);
16584            deletedPs = mSettings.mPackages.get(packageName);
16585            if (outInfo != null) {
16586                outInfo.removedPackage = packageName;
16587                outInfo.removedUsers = deletedPs != null
16588                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16589                        : null;
16590            }
16591        }
16592
16593        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16594
16595        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16596            final PackageParser.Package resolvedPkg;
16597            if (deletedPkg != null) {
16598                resolvedPkg = deletedPkg;
16599            } else {
16600                // We don't have a parsed package when it lives on an ejected
16601                // adopted storage device, so fake something together
16602                resolvedPkg = new PackageParser.Package(ps.name);
16603                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16604            }
16605            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16606                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16607            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16608            if (outInfo != null) {
16609                outInfo.dataRemoved = true;
16610            }
16611            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16612        }
16613
16614        // writer
16615        synchronized (mPackages) {
16616            if (deletedPs != null) {
16617                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16618                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16619                    clearDefaultBrowserIfNeeded(packageName);
16620                    if (outInfo != null) {
16621                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16622                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16623                    }
16624                    updatePermissionsLPw(deletedPs.name, null, 0);
16625                    if (deletedPs.sharedUser != null) {
16626                        // Remove permissions associated with package. Since runtime
16627                        // permissions are per user we have to kill the removed package
16628                        // or packages running under the shared user of the removed
16629                        // package if revoking the permissions requested only by the removed
16630                        // package is successful and this causes a change in gids.
16631                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16632                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16633                                    userId);
16634                            if (userIdToKill == UserHandle.USER_ALL
16635                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16636                                // If gids changed for this user, kill all affected packages.
16637                                mHandler.post(new Runnable() {
16638                                    @Override
16639                                    public void run() {
16640                                        // This has to happen with no lock held.
16641                                        killApplication(deletedPs.name, deletedPs.appId,
16642                                                KILL_APP_REASON_GIDS_CHANGED);
16643                                    }
16644                                });
16645                                break;
16646                            }
16647                        }
16648                    }
16649                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16650                }
16651                // make sure to preserve per-user disabled state if this removal was just
16652                // a downgrade of a system app to the factory package
16653                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16654                    if (DEBUG_REMOVE) {
16655                        Slog.d(TAG, "Propagating install state across downgrade");
16656                    }
16657                    for (int userId : allUserHandles) {
16658                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16659                        if (DEBUG_REMOVE) {
16660                            Slog.d(TAG, "    user " + userId + " => " + installed);
16661                        }
16662                        ps.setInstalled(installed, userId);
16663                    }
16664                }
16665            }
16666            // can downgrade to reader
16667            if (writeSettings) {
16668                // Save settings now
16669                mSettings.writeLPr();
16670            }
16671        }
16672        if (outInfo != null) {
16673            // A user ID was deleted here. Go through all users and remove it
16674            // from KeyStore.
16675            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16676        }
16677    }
16678
16679    static boolean locationIsPrivileged(File path) {
16680        try {
16681            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16682                    .getCanonicalPath();
16683            return path.getCanonicalPath().startsWith(privilegedAppDir);
16684        } catch (IOException e) {
16685            Slog.e(TAG, "Unable to access code path " + path);
16686        }
16687        return false;
16688    }
16689
16690    /*
16691     * Tries to delete system package.
16692     */
16693    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16694            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16695            boolean writeSettings) {
16696        if (deletedPs.parentPackageName != null) {
16697            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16698            return false;
16699        }
16700
16701        final boolean applyUserRestrictions
16702                = (allUserHandles != null) && (outInfo.origUsers != null);
16703        final PackageSetting disabledPs;
16704        // Confirm if the system package has been updated
16705        // An updated system app can be deleted. This will also have to restore
16706        // the system pkg from system partition
16707        // reader
16708        synchronized (mPackages) {
16709            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16710        }
16711
16712        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16713                + " disabledPs=" + disabledPs);
16714
16715        if (disabledPs == null) {
16716            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16717            return false;
16718        } else if (DEBUG_REMOVE) {
16719            Slog.d(TAG, "Deleting system pkg from data partition");
16720        }
16721
16722        if (DEBUG_REMOVE) {
16723            if (applyUserRestrictions) {
16724                Slog.d(TAG, "Remembering install states:");
16725                for (int userId : allUserHandles) {
16726                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16727                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16728                }
16729            }
16730        }
16731
16732        // Delete the updated package
16733        outInfo.isRemovedPackageSystemUpdate = true;
16734        if (outInfo.removedChildPackages != null) {
16735            final int childCount = (deletedPs.childPackageNames != null)
16736                    ? deletedPs.childPackageNames.size() : 0;
16737            for (int i = 0; i < childCount; i++) {
16738                String childPackageName = deletedPs.childPackageNames.get(i);
16739                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16740                        .contains(childPackageName)) {
16741                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16742                            childPackageName);
16743                    if (childInfo != null) {
16744                        childInfo.isRemovedPackageSystemUpdate = true;
16745                    }
16746                }
16747            }
16748        }
16749
16750        if (disabledPs.versionCode < deletedPs.versionCode) {
16751            // Delete data for downgrades
16752            flags &= ~PackageManager.DELETE_KEEP_DATA;
16753        } else {
16754            // Preserve data by setting flag
16755            flags |= PackageManager.DELETE_KEEP_DATA;
16756        }
16757
16758        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16759                outInfo, writeSettings, disabledPs.pkg);
16760        if (!ret) {
16761            return false;
16762        }
16763
16764        // writer
16765        synchronized (mPackages) {
16766            // Reinstate the old system package
16767            enableSystemPackageLPw(disabledPs.pkg);
16768            // Remove any native libraries from the upgraded package.
16769            removeNativeBinariesLI(deletedPs);
16770        }
16771
16772        // Install the system package
16773        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16774        int parseFlags = mDefParseFlags
16775                | PackageParser.PARSE_MUST_BE_APK
16776                | PackageParser.PARSE_IS_SYSTEM
16777                | PackageParser.PARSE_IS_SYSTEM_DIR;
16778        if (locationIsPrivileged(disabledPs.codePath)) {
16779            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16780        }
16781
16782        final PackageParser.Package newPkg;
16783        try {
16784            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16785                0 /* currentTime */, null);
16786        } catch (PackageManagerException e) {
16787            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16788                    + e.getMessage());
16789            return false;
16790        }
16791        try {
16792            // update shared libraries for the newly re-installed system package
16793            updateSharedLibrariesLPr(newPkg, null);
16794        } catch (PackageManagerException e) {
16795            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16796        }
16797
16798        prepareAppDataAfterInstallLIF(newPkg);
16799
16800        // writer
16801        synchronized (mPackages) {
16802            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16803
16804            // Propagate the permissions state as we do not want to drop on the floor
16805            // runtime permissions. The update permissions method below will take
16806            // care of removing obsolete permissions and grant install permissions.
16807            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16808            updatePermissionsLPw(newPkg.packageName, newPkg,
16809                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16810
16811            if (applyUserRestrictions) {
16812                if (DEBUG_REMOVE) {
16813                    Slog.d(TAG, "Propagating install state across reinstall");
16814                }
16815                for (int userId : allUserHandles) {
16816                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16817                    if (DEBUG_REMOVE) {
16818                        Slog.d(TAG, "    user " + userId + " => " + installed);
16819                    }
16820                    ps.setInstalled(installed, userId);
16821
16822                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16823                }
16824                // Regardless of writeSettings we need to ensure that this restriction
16825                // state propagation is persisted
16826                mSettings.writeAllUsersPackageRestrictionsLPr();
16827            }
16828            // can downgrade to reader here
16829            if (writeSettings) {
16830                mSettings.writeLPr();
16831            }
16832        }
16833        return true;
16834    }
16835
16836    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16837            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16838            PackageRemovedInfo outInfo, boolean writeSettings,
16839            PackageParser.Package replacingPackage) {
16840        synchronized (mPackages) {
16841            if (outInfo != null) {
16842                outInfo.uid = ps.appId;
16843            }
16844
16845            if (outInfo != null && outInfo.removedChildPackages != null) {
16846                final int childCount = (ps.childPackageNames != null)
16847                        ? ps.childPackageNames.size() : 0;
16848                for (int i = 0; i < childCount; i++) {
16849                    String childPackageName = ps.childPackageNames.get(i);
16850                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16851                    if (childPs == null) {
16852                        return false;
16853                    }
16854                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16855                            childPackageName);
16856                    if (childInfo != null) {
16857                        childInfo.uid = childPs.appId;
16858                    }
16859                }
16860            }
16861        }
16862
16863        // Delete package data from internal structures and also remove data if flag is set
16864        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16865
16866        // Delete the child packages data
16867        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16868        for (int i = 0; i < childCount; i++) {
16869            PackageSetting childPs;
16870            synchronized (mPackages) {
16871                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16872            }
16873            if (childPs != null) {
16874                PackageRemovedInfo childOutInfo = (outInfo != null
16875                        && outInfo.removedChildPackages != null)
16876                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16877                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16878                        && (replacingPackage != null
16879                        && !replacingPackage.hasChildPackage(childPs.name))
16880                        ? flags & ~DELETE_KEEP_DATA : flags;
16881                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16882                        deleteFlags, writeSettings);
16883            }
16884        }
16885
16886        // Delete application code and resources only for parent packages
16887        if (ps.parentPackageName == null) {
16888            if (deleteCodeAndResources && (outInfo != null)) {
16889                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16890                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16891                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16892            }
16893        }
16894
16895        return true;
16896    }
16897
16898    @Override
16899    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16900            int userId) {
16901        mContext.enforceCallingOrSelfPermission(
16902                android.Manifest.permission.DELETE_PACKAGES, null);
16903        synchronized (mPackages) {
16904            PackageSetting ps = mSettings.mPackages.get(packageName);
16905            if (ps == null) {
16906                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16907                return false;
16908            }
16909            if (!ps.getInstalled(userId)) {
16910                // Can't block uninstall for an app that is not installed or enabled.
16911                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16912                return false;
16913            }
16914            ps.setBlockUninstall(blockUninstall, userId);
16915            mSettings.writePackageRestrictionsLPr(userId);
16916        }
16917        return true;
16918    }
16919
16920    @Override
16921    public boolean getBlockUninstallForUser(String packageName, int userId) {
16922        synchronized (mPackages) {
16923            PackageSetting ps = mSettings.mPackages.get(packageName);
16924            if (ps == null) {
16925                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16926                return false;
16927            }
16928            return ps.getBlockUninstall(userId);
16929        }
16930    }
16931
16932    @Override
16933    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16934        int callingUid = Binder.getCallingUid();
16935        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16936            throw new SecurityException(
16937                    "setRequiredForSystemUser can only be run by the system or root");
16938        }
16939        synchronized (mPackages) {
16940            PackageSetting ps = mSettings.mPackages.get(packageName);
16941            if (ps == null) {
16942                Log.w(TAG, "Package doesn't exist: " + packageName);
16943                return false;
16944            }
16945            if (systemUserApp) {
16946                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16947            } else {
16948                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16949            }
16950            mSettings.writeLPr();
16951        }
16952        return true;
16953    }
16954
16955    /*
16956     * This method handles package deletion in general
16957     */
16958    private boolean deletePackageLIF(String packageName, UserHandle user,
16959            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16960            PackageRemovedInfo outInfo, boolean writeSettings,
16961            PackageParser.Package replacingPackage) {
16962        if (packageName == null) {
16963            Slog.w(TAG, "Attempt to delete null packageName.");
16964            return false;
16965        }
16966
16967        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16968
16969        PackageSetting ps;
16970
16971        synchronized (mPackages) {
16972            ps = mSettings.mPackages.get(packageName);
16973            if (ps == null) {
16974                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16975                return false;
16976            }
16977
16978            if (ps.parentPackageName != null && (!isSystemApp(ps)
16979                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16980                if (DEBUG_REMOVE) {
16981                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16982                            + ((user == null) ? UserHandle.USER_ALL : user));
16983                }
16984                final int removedUserId = (user != null) ? user.getIdentifier()
16985                        : UserHandle.USER_ALL;
16986                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16987                    return false;
16988                }
16989                markPackageUninstalledForUserLPw(ps, user);
16990                scheduleWritePackageRestrictionsLocked(user);
16991                return true;
16992            }
16993        }
16994
16995        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16996                && user.getIdentifier() != UserHandle.USER_ALL)) {
16997            // The caller is asking that the package only be deleted for a single
16998            // user.  To do this, we just mark its uninstalled state and delete
16999            // its data. If this is a system app, we only allow this to happen if
17000            // they have set the special DELETE_SYSTEM_APP which requests different
17001            // semantics than normal for uninstalling system apps.
17002            markPackageUninstalledForUserLPw(ps, user);
17003
17004            if (!isSystemApp(ps)) {
17005                // Do not uninstall the APK if an app should be cached
17006                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17007                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17008                    // Other user still have this package installed, so all
17009                    // we need to do is clear this user's data and save that
17010                    // it is uninstalled.
17011                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17012                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17013                        return false;
17014                    }
17015                    scheduleWritePackageRestrictionsLocked(user);
17016                    return true;
17017                } else {
17018                    // We need to set it back to 'installed' so the uninstall
17019                    // broadcasts will be sent correctly.
17020                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17021                    ps.setInstalled(true, user.getIdentifier());
17022                }
17023            } else {
17024                // This is a system app, so we assume that the
17025                // other users still have this package installed, so all
17026                // we need to do is clear this user's data and save that
17027                // it is uninstalled.
17028                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17029                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17030                    return false;
17031                }
17032                scheduleWritePackageRestrictionsLocked(user);
17033                return true;
17034            }
17035        }
17036
17037        // If we are deleting a composite package for all users, keep track
17038        // of result for each child.
17039        if (ps.childPackageNames != null && outInfo != null) {
17040            synchronized (mPackages) {
17041                final int childCount = ps.childPackageNames.size();
17042                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17043                for (int i = 0; i < childCount; i++) {
17044                    String childPackageName = ps.childPackageNames.get(i);
17045                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17046                    childInfo.removedPackage = childPackageName;
17047                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17048                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17049                    if (childPs != null) {
17050                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17051                    }
17052                }
17053            }
17054        }
17055
17056        boolean ret = false;
17057        if (isSystemApp(ps)) {
17058            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17059            // When an updated system application is deleted we delete the existing resources
17060            // as well and fall back to existing code in system partition
17061            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17062        } else {
17063            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17064            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17065                    outInfo, writeSettings, replacingPackage);
17066        }
17067
17068        // Take a note whether we deleted the package for all users
17069        if (outInfo != null) {
17070            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17071            if (outInfo.removedChildPackages != null) {
17072                synchronized (mPackages) {
17073                    final int childCount = outInfo.removedChildPackages.size();
17074                    for (int i = 0; i < childCount; i++) {
17075                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17076                        if (childInfo != null) {
17077                            childInfo.removedForAllUsers = mPackages.get(
17078                                    childInfo.removedPackage) == null;
17079                        }
17080                    }
17081                }
17082            }
17083            // If we uninstalled an update to a system app there may be some
17084            // child packages that appeared as they are declared in the system
17085            // app but were not declared in the update.
17086            if (isSystemApp(ps)) {
17087                synchronized (mPackages) {
17088                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17089                    final int childCount = (updatedPs.childPackageNames != null)
17090                            ? updatedPs.childPackageNames.size() : 0;
17091                    for (int i = 0; i < childCount; i++) {
17092                        String childPackageName = updatedPs.childPackageNames.get(i);
17093                        if (outInfo.removedChildPackages == null
17094                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17095                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17096                            if (childPs == null) {
17097                                continue;
17098                            }
17099                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17100                            installRes.name = childPackageName;
17101                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17102                            installRes.pkg = mPackages.get(childPackageName);
17103                            installRes.uid = childPs.pkg.applicationInfo.uid;
17104                            if (outInfo.appearedChildPackages == null) {
17105                                outInfo.appearedChildPackages = new ArrayMap<>();
17106                            }
17107                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17108                        }
17109                    }
17110                }
17111            }
17112        }
17113
17114        return ret;
17115    }
17116
17117    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17118        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17119                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17120        for (int nextUserId : userIds) {
17121            if (DEBUG_REMOVE) {
17122                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17123            }
17124            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17125                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
17126                    false /*hidden*/, false /*suspended*/, null, null, null,
17127                    false /*blockUninstall*/,
17128                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
17129                    PackageManager.INSTALL_REASON_UNKNOWN);
17130        }
17131    }
17132
17133    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17134            PackageRemovedInfo outInfo) {
17135        final PackageParser.Package pkg;
17136        synchronized (mPackages) {
17137            pkg = mPackages.get(ps.name);
17138        }
17139
17140        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17141                : new int[] {userId};
17142        for (int nextUserId : userIds) {
17143            if (DEBUG_REMOVE) {
17144                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17145                        + nextUserId);
17146            }
17147
17148            destroyAppDataLIF(pkg, userId,
17149                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17150            destroyAppProfilesLIF(pkg, userId);
17151            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17152            schedulePackageCleaning(ps.name, nextUserId, false);
17153            synchronized (mPackages) {
17154                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17155                    scheduleWritePackageRestrictionsLocked(nextUserId);
17156                }
17157                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17158            }
17159        }
17160
17161        if (outInfo != null) {
17162            outInfo.removedPackage = ps.name;
17163            outInfo.removedAppId = ps.appId;
17164            outInfo.removedUsers = userIds;
17165        }
17166
17167        return true;
17168    }
17169
17170    private final class ClearStorageConnection implements ServiceConnection {
17171        IMediaContainerService mContainerService;
17172
17173        @Override
17174        public void onServiceConnected(ComponentName name, IBinder service) {
17175            synchronized (this) {
17176                mContainerService = IMediaContainerService.Stub
17177                        .asInterface(Binder.allowBlocking(service));
17178                notifyAll();
17179            }
17180        }
17181
17182        @Override
17183        public void onServiceDisconnected(ComponentName name) {
17184        }
17185    }
17186
17187    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17188        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17189
17190        final boolean mounted;
17191        if (Environment.isExternalStorageEmulated()) {
17192            mounted = true;
17193        } else {
17194            final String status = Environment.getExternalStorageState();
17195
17196            mounted = status.equals(Environment.MEDIA_MOUNTED)
17197                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17198        }
17199
17200        if (!mounted) {
17201            return;
17202        }
17203
17204        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17205        int[] users;
17206        if (userId == UserHandle.USER_ALL) {
17207            users = sUserManager.getUserIds();
17208        } else {
17209            users = new int[] { userId };
17210        }
17211        final ClearStorageConnection conn = new ClearStorageConnection();
17212        if (mContext.bindServiceAsUser(
17213                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17214            try {
17215                for (int curUser : users) {
17216                    long timeout = SystemClock.uptimeMillis() + 5000;
17217                    synchronized (conn) {
17218                        long now;
17219                        while (conn.mContainerService == null &&
17220                                (now = SystemClock.uptimeMillis()) < timeout) {
17221                            try {
17222                                conn.wait(timeout - now);
17223                            } catch (InterruptedException e) {
17224                            }
17225                        }
17226                    }
17227                    if (conn.mContainerService == null) {
17228                        return;
17229                    }
17230
17231                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17232                    clearDirectory(conn.mContainerService,
17233                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17234                    if (allData) {
17235                        clearDirectory(conn.mContainerService,
17236                                userEnv.buildExternalStorageAppDataDirs(packageName));
17237                        clearDirectory(conn.mContainerService,
17238                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17239                    }
17240                }
17241            } finally {
17242                mContext.unbindService(conn);
17243            }
17244        }
17245    }
17246
17247    @Override
17248    public void clearApplicationProfileData(String packageName) {
17249        enforceSystemOrRoot("Only the system can clear all profile data");
17250
17251        final PackageParser.Package pkg;
17252        synchronized (mPackages) {
17253            pkg = mPackages.get(packageName);
17254        }
17255
17256        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17257            synchronized (mInstallLock) {
17258                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17259                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17260                        true /* removeBaseMarker */);
17261            }
17262        }
17263    }
17264
17265    @Override
17266    public void clearApplicationUserData(final String packageName,
17267            final IPackageDataObserver observer, final int userId) {
17268        mContext.enforceCallingOrSelfPermission(
17269                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17270
17271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17272                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17273
17274        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17275            throw new SecurityException("Cannot clear data for a protected package: "
17276                    + packageName);
17277        }
17278        // Queue up an async operation since the package deletion may take a little while.
17279        mHandler.post(new Runnable() {
17280            public void run() {
17281                mHandler.removeCallbacks(this);
17282                final boolean succeeded;
17283                try (PackageFreezer freezer = freezePackage(packageName,
17284                        "clearApplicationUserData")) {
17285                    synchronized (mInstallLock) {
17286                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17287                    }
17288                    clearExternalStorageDataSync(packageName, userId, true);
17289                }
17290                if (succeeded) {
17291                    // invoke DeviceStorageMonitor's update method to clear any notifications
17292                    DeviceStorageMonitorInternal dsm = LocalServices
17293                            .getService(DeviceStorageMonitorInternal.class);
17294                    if (dsm != null) {
17295                        dsm.checkMemory();
17296                    }
17297                }
17298                if(observer != null) {
17299                    try {
17300                        observer.onRemoveCompleted(packageName, succeeded);
17301                    } catch (RemoteException e) {
17302                        Log.i(TAG, "Observer no longer exists.");
17303                    }
17304                } //end if observer
17305            } //end run
17306        });
17307    }
17308
17309    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17310        if (packageName == null) {
17311            Slog.w(TAG, "Attempt to delete null packageName.");
17312            return false;
17313        }
17314
17315        // Try finding details about the requested package
17316        PackageParser.Package pkg;
17317        synchronized (mPackages) {
17318            pkg = mPackages.get(packageName);
17319            if (pkg == null) {
17320                final PackageSetting ps = mSettings.mPackages.get(packageName);
17321                if (ps != null) {
17322                    pkg = ps.pkg;
17323                }
17324            }
17325
17326            if (pkg == null) {
17327                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17328                return false;
17329            }
17330
17331            PackageSetting ps = (PackageSetting) pkg.mExtras;
17332            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17333        }
17334
17335        clearAppDataLIF(pkg, userId,
17336                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17337
17338        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17339        removeKeystoreDataIfNeeded(userId, appId);
17340
17341        UserManagerInternal umInternal = getUserManagerInternal();
17342        final int flags;
17343        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17344            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17345        } else if (umInternal.isUserRunning(userId)) {
17346            flags = StorageManager.FLAG_STORAGE_DE;
17347        } else {
17348            flags = 0;
17349        }
17350        prepareAppDataContentsLIF(pkg, userId, flags);
17351
17352        return true;
17353    }
17354
17355    /**
17356     * Reverts user permission state changes (permissions and flags) in
17357     * all packages for a given user.
17358     *
17359     * @param userId The device user for which to do a reset.
17360     */
17361    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17362        final int packageCount = mPackages.size();
17363        for (int i = 0; i < packageCount; i++) {
17364            PackageParser.Package pkg = mPackages.valueAt(i);
17365            PackageSetting ps = (PackageSetting) pkg.mExtras;
17366            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17367        }
17368    }
17369
17370    private void resetNetworkPolicies(int userId) {
17371        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17372    }
17373
17374    /**
17375     * Reverts user permission state changes (permissions and flags).
17376     *
17377     * @param ps The package for which to reset.
17378     * @param userId The device user for which to do a reset.
17379     */
17380    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17381            final PackageSetting ps, final int userId) {
17382        if (ps.pkg == null) {
17383            return;
17384        }
17385
17386        // These are flags that can change base on user actions.
17387        final int userSettableMask = FLAG_PERMISSION_USER_SET
17388                | FLAG_PERMISSION_USER_FIXED
17389                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17390                | FLAG_PERMISSION_REVIEW_REQUIRED;
17391
17392        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17393                | FLAG_PERMISSION_POLICY_FIXED;
17394
17395        boolean writeInstallPermissions = false;
17396        boolean writeRuntimePermissions = false;
17397
17398        final int permissionCount = ps.pkg.requestedPermissions.size();
17399        for (int i = 0; i < permissionCount; i++) {
17400            String permission = ps.pkg.requestedPermissions.get(i);
17401
17402            BasePermission bp = mSettings.mPermissions.get(permission);
17403            if (bp == null) {
17404                continue;
17405            }
17406
17407            // If shared user we just reset the state to which only this app contributed.
17408            if (ps.sharedUser != null) {
17409                boolean used = false;
17410                final int packageCount = ps.sharedUser.packages.size();
17411                for (int j = 0; j < packageCount; j++) {
17412                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17413                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17414                            && pkg.pkg.requestedPermissions.contains(permission)) {
17415                        used = true;
17416                        break;
17417                    }
17418                }
17419                if (used) {
17420                    continue;
17421                }
17422            }
17423
17424            PermissionsState permissionsState = ps.getPermissionsState();
17425
17426            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17427
17428            // Always clear the user settable flags.
17429            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17430                    bp.name) != null;
17431            // If permission review is enabled and this is a legacy app, mark the
17432            // permission as requiring a review as this is the initial state.
17433            int flags = 0;
17434            if (mPermissionReviewRequired
17435                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17436                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17437            }
17438            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17439                if (hasInstallState) {
17440                    writeInstallPermissions = true;
17441                } else {
17442                    writeRuntimePermissions = true;
17443                }
17444            }
17445
17446            // Below is only runtime permission handling.
17447            if (!bp.isRuntime()) {
17448                continue;
17449            }
17450
17451            // Never clobber system or policy.
17452            if ((oldFlags & policyOrSystemFlags) != 0) {
17453                continue;
17454            }
17455
17456            // If this permission was granted by default, make sure it is.
17457            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17458                if (permissionsState.grantRuntimePermission(bp, userId)
17459                        != PERMISSION_OPERATION_FAILURE) {
17460                    writeRuntimePermissions = true;
17461                }
17462            // If permission review is enabled the permissions for a legacy apps
17463            // are represented as constantly granted runtime ones, so don't revoke.
17464            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17465                // Otherwise, reset the permission.
17466                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17467                switch (revokeResult) {
17468                    case PERMISSION_OPERATION_SUCCESS:
17469                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17470                        writeRuntimePermissions = true;
17471                        final int appId = ps.appId;
17472                        mHandler.post(new Runnable() {
17473                            @Override
17474                            public void run() {
17475                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17476                            }
17477                        });
17478                    } break;
17479                }
17480            }
17481        }
17482
17483        // Synchronously write as we are taking permissions away.
17484        if (writeRuntimePermissions) {
17485            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17486        }
17487
17488        // Synchronously write as we are taking permissions away.
17489        if (writeInstallPermissions) {
17490            mSettings.writeLPr();
17491        }
17492    }
17493
17494    /**
17495     * Remove entries from the keystore daemon. Will only remove it if the
17496     * {@code appId} is valid.
17497     */
17498    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17499        if (appId < 0) {
17500            return;
17501        }
17502
17503        final KeyStore keyStore = KeyStore.getInstance();
17504        if (keyStore != null) {
17505            if (userId == UserHandle.USER_ALL) {
17506                for (final int individual : sUserManager.getUserIds()) {
17507                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17508                }
17509            } else {
17510                keyStore.clearUid(UserHandle.getUid(userId, appId));
17511            }
17512        } else {
17513            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17514        }
17515    }
17516
17517    @Override
17518    public void deleteApplicationCacheFiles(final String packageName,
17519            final IPackageDataObserver observer) {
17520        final int userId = UserHandle.getCallingUserId();
17521        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17522    }
17523
17524    @Override
17525    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17526            final IPackageDataObserver observer) {
17527        mContext.enforceCallingOrSelfPermission(
17528                android.Manifest.permission.DELETE_CACHE_FILES, null);
17529        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17530                /* requireFullPermission= */ true, /* checkShell= */ false,
17531                "delete application cache files");
17532
17533        final PackageParser.Package pkg;
17534        synchronized (mPackages) {
17535            pkg = mPackages.get(packageName);
17536        }
17537
17538        // Queue up an async operation since the package deletion may take a little while.
17539        mHandler.post(new Runnable() {
17540            public void run() {
17541                synchronized (mInstallLock) {
17542                    final int flags = StorageManager.FLAG_STORAGE_DE
17543                            | StorageManager.FLAG_STORAGE_CE;
17544                    // We're only clearing cache files, so we don't care if the
17545                    // app is unfrozen and still able to run
17546                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17547                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17548                }
17549                clearExternalStorageDataSync(packageName, userId, false);
17550                if (observer != null) {
17551                    try {
17552                        observer.onRemoveCompleted(packageName, true);
17553                    } catch (RemoteException e) {
17554                        Log.i(TAG, "Observer no longer exists.");
17555                    }
17556                }
17557            }
17558        });
17559    }
17560
17561    @Override
17562    public void getPackageSizeInfo(final String packageName, int userHandle,
17563            final IPackageStatsObserver observer) {
17564        mContext.enforceCallingOrSelfPermission(
17565                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17566        if (packageName == null) {
17567            throw new IllegalArgumentException("Attempt to get size of null packageName");
17568        }
17569
17570        PackageStats stats = new PackageStats(packageName, userHandle);
17571
17572        /*
17573         * Queue up an async operation since the package measurement may take a
17574         * little while.
17575         */
17576        Message msg = mHandler.obtainMessage(INIT_COPY);
17577        msg.obj = new MeasureParams(stats, observer);
17578        mHandler.sendMessage(msg);
17579    }
17580
17581    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17582        final PackageSetting ps;
17583        synchronized (mPackages) {
17584            ps = mSettings.mPackages.get(packageName);
17585            if (ps == null) {
17586                Slog.w(TAG, "Failed to find settings for " + packageName);
17587                return false;
17588            }
17589        }
17590
17591        final String[] packageNames = { packageName };
17592        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
17593        final String[] codePaths = { ps.codePathString };
17594
17595        try {
17596            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
17597                    ps.appId, ceDataInodes, codePaths, stats);
17598
17599            // For now, ignore code size of packages on system partition
17600            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17601                stats.codeSize = 0;
17602            }
17603
17604            // External clients expect these to be tracked separately
17605            stats.dataSize -= stats.cacheSize;
17606
17607        } catch (InstallerException e) {
17608            Slog.w(TAG, String.valueOf(e));
17609            return false;
17610        }
17611
17612        return true;
17613    }
17614
17615    private int getUidTargetSdkVersionLockedLPr(int uid) {
17616        Object obj = mSettings.getUserIdLPr(uid);
17617        if (obj instanceof SharedUserSetting) {
17618            final SharedUserSetting sus = (SharedUserSetting) obj;
17619            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17620            final Iterator<PackageSetting> it = sus.packages.iterator();
17621            while (it.hasNext()) {
17622                final PackageSetting ps = it.next();
17623                if (ps.pkg != null) {
17624                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17625                    if (v < vers) vers = v;
17626                }
17627            }
17628            return vers;
17629        } else if (obj instanceof PackageSetting) {
17630            final PackageSetting ps = (PackageSetting) obj;
17631            if (ps.pkg != null) {
17632                return ps.pkg.applicationInfo.targetSdkVersion;
17633            }
17634        }
17635        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17636    }
17637
17638    @Override
17639    public void addPreferredActivity(IntentFilter filter, int match,
17640            ComponentName[] set, ComponentName activity, int userId) {
17641        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17642                "Adding preferred");
17643    }
17644
17645    private void addPreferredActivityInternal(IntentFilter filter, int match,
17646            ComponentName[] set, ComponentName activity, boolean always, int userId,
17647            String opname) {
17648        // writer
17649        int callingUid = Binder.getCallingUid();
17650        enforceCrossUserPermission(callingUid, userId,
17651                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17652        if (filter.countActions() == 0) {
17653            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17654            return;
17655        }
17656        synchronized (mPackages) {
17657            if (mContext.checkCallingOrSelfPermission(
17658                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17659                    != PackageManager.PERMISSION_GRANTED) {
17660                if (getUidTargetSdkVersionLockedLPr(callingUid)
17661                        < Build.VERSION_CODES.FROYO) {
17662                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17663                            + callingUid);
17664                    return;
17665                }
17666                mContext.enforceCallingOrSelfPermission(
17667                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17668            }
17669
17670            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17671            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17672                    + userId + ":");
17673            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17674            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17675            scheduleWritePackageRestrictionsLocked(userId);
17676            postPreferredActivityChangedBroadcast(userId);
17677        }
17678    }
17679
17680    private void postPreferredActivityChangedBroadcast(int userId) {
17681        mHandler.post(() -> {
17682            final IActivityManager am = ActivityManager.getService();
17683            if (am == null) {
17684                return;
17685            }
17686
17687            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17688            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17689            try {
17690                am.broadcastIntent(null, intent, null, null,
17691                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17692                        null, false, false, userId);
17693            } catch (RemoteException e) {
17694            }
17695        });
17696    }
17697
17698    @Override
17699    public void replacePreferredActivity(IntentFilter filter, int match,
17700            ComponentName[] set, ComponentName activity, int userId) {
17701        if (filter.countActions() != 1) {
17702            throw new IllegalArgumentException(
17703                    "replacePreferredActivity expects filter to have only 1 action.");
17704        }
17705        if (filter.countDataAuthorities() != 0
17706                || filter.countDataPaths() != 0
17707                || filter.countDataSchemes() > 1
17708                || filter.countDataTypes() != 0) {
17709            throw new IllegalArgumentException(
17710                    "replacePreferredActivity expects filter to have no data authorities, " +
17711                    "paths, or types; and at most one scheme.");
17712        }
17713
17714        final int callingUid = Binder.getCallingUid();
17715        enforceCrossUserPermission(callingUid, userId,
17716                true /* requireFullPermission */, false /* checkShell */,
17717                "replace preferred activity");
17718        synchronized (mPackages) {
17719            if (mContext.checkCallingOrSelfPermission(
17720                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17721                    != PackageManager.PERMISSION_GRANTED) {
17722                if (getUidTargetSdkVersionLockedLPr(callingUid)
17723                        < Build.VERSION_CODES.FROYO) {
17724                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17725                            + Binder.getCallingUid());
17726                    return;
17727                }
17728                mContext.enforceCallingOrSelfPermission(
17729                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17730            }
17731
17732            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17733            if (pir != null) {
17734                // Get all of the existing entries that exactly match this filter.
17735                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17736                if (existing != null && existing.size() == 1) {
17737                    PreferredActivity cur = existing.get(0);
17738                    if (DEBUG_PREFERRED) {
17739                        Slog.i(TAG, "Checking replace of preferred:");
17740                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17741                        if (!cur.mPref.mAlways) {
17742                            Slog.i(TAG, "  -- CUR; not mAlways!");
17743                        } else {
17744                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17745                            Slog.i(TAG, "  -- CUR: mSet="
17746                                    + Arrays.toString(cur.mPref.mSetComponents));
17747                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17748                            Slog.i(TAG, "  -- NEW: mMatch="
17749                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17750                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17751                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17752                        }
17753                    }
17754                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17755                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17756                            && cur.mPref.sameSet(set)) {
17757                        // Setting the preferred activity to what it happens to be already
17758                        if (DEBUG_PREFERRED) {
17759                            Slog.i(TAG, "Replacing with same preferred activity "
17760                                    + cur.mPref.mShortComponent + " for user "
17761                                    + userId + ":");
17762                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17763                        }
17764                        return;
17765                    }
17766                }
17767
17768                if (existing != null) {
17769                    if (DEBUG_PREFERRED) {
17770                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17771                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17772                    }
17773                    for (int i = 0; i < existing.size(); i++) {
17774                        PreferredActivity pa = existing.get(i);
17775                        if (DEBUG_PREFERRED) {
17776                            Slog.i(TAG, "Removing existing preferred activity "
17777                                    + pa.mPref.mComponent + ":");
17778                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17779                        }
17780                        pir.removeFilter(pa);
17781                    }
17782                }
17783            }
17784            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17785                    "Replacing preferred");
17786        }
17787    }
17788
17789    @Override
17790    public void clearPackagePreferredActivities(String packageName) {
17791        final int uid = Binder.getCallingUid();
17792        // writer
17793        synchronized (mPackages) {
17794            PackageParser.Package pkg = mPackages.get(packageName);
17795            if (pkg == null || pkg.applicationInfo.uid != uid) {
17796                if (mContext.checkCallingOrSelfPermission(
17797                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17798                        != PackageManager.PERMISSION_GRANTED) {
17799                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17800                            < Build.VERSION_CODES.FROYO) {
17801                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17802                                + Binder.getCallingUid());
17803                        return;
17804                    }
17805                    mContext.enforceCallingOrSelfPermission(
17806                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17807                }
17808            }
17809
17810            int user = UserHandle.getCallingUserId();
17811            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17812                scheduleWritePackageRestrictionsLocked(user);
17813            }
17814        }
17815    }
17816
17817    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17818    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17819        ArrayList<PreferredActivity> removed = null;
17820        boolean changed = false;
17821        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17822            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17823            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17824            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17825                continue;
17826            }
17827            Iterator<PreferredActivity> it = pir.filterIterator();
17828            while (it.hasNext()) {
17829                PreferredActivity pa = it.next();
17830                // Mark entry for removal only if it matches the package name
17831                // and the entry is of type "always".
17832                if (packageName == null ||
17833                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17834                                && pa.mPref.mAlways)) {
17835                    if (removed == null) {
17836                        removed = new ArrayList<PreferredActivity>();
17837                    }
17838                    removed.add(pa);
17839                }
17840            }
17841            if (removed != null) {
17842                for (int j=0; j<removed.size(); j++) {
17843                    PreferredActivity pa = removed.get(j);
17844                    pir.removeFilter(pa);
17845                }
17846                changed = true;
17847            }
17848        }
17849        if (changed) {
17850            postPreferredActivityChangedBroadcast(userId);
17851        }
17852        return changed;
17853    }
17854
17855    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17856    private void clearIntentFilterVerificationsLPw(int userId) {
17857        final int packageCount = mPackages.size();
17858        for (int i = 0; i < packageCount; i++) {
17859            PackageParser.Package pkg = mPackages.valueAt(i);
17860            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17861        }
17862    }
17863
17864    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17865    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17866        if (userId == UserHandle.USER_ALL) {
17867            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17868                    sUserManager.getUserIds())) {
17869                for (int oneUserId : sUserManager.getUserIds()) {
17870                    scheduleWritePackageRestrictionsLocked(oneUserId);
17871                }
17872            }
17873        } else {
17874            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17875                scheduleWritePackageRestrictionsLocked(userId);
17876            }
17877        }
17878    }
17879
17880    void clearDefaultBrowserIfNeeded(String packageName) {
17881        for (int oneUserId : sUserManager.getUserIds()) {
17882            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17883            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17884            if (packageName.equals(defaultBrowserPackageName)) {
17885                setDefaultBrowserPackageName(null, oneUserId);
17886            }
17887        }
17888    }
17889
17890    @Override
17891    public void resetApplicationPreferences(int userId) {
17892        mContext.enforceCallingOrSelfPermission(
17893                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17894        final long identity = Binder.clearCallingIdentity();
17895        // writer
17896        try {
17897            synchronized (mPackages) {
17898                clearPackagePreferredActivitiesLPw(null, userId);
17899                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17900                // TODO: We have to reset the default SMS and Phone. This requires
17901                // significant refactoring to keep all default apps in the package
17902                // manager (cleaner but more work) or have the services provide
17903                // callbacks to the package manager to request a default app reset.
17904                applyFactoryDefaultBrowserLPw(userId);
17905                clearIntentFilterVerificationsLPw(userId);
17906                primeDomainVerificationsLPw(userId);
17907                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17908                scheduleWritePackageRestrictionsLocked(userId);
17909            }
17910            resetNetworkPolicies(userId);
17911        } finally {
17912            Binder.restoreCallingIdentity(identity);
17913        }
17914    }
17915
17916    @Override
17917    public int getPreferredActivities(List<IntentFilter> outFilters,
17918            List<ComponentName> outActivities, String packageName) {
17919
17920        int num = 0;
17921        final int userId = UserHandle.getCallingUserId();
17922        // reader
17923        synchronized (mPackages) {
17924            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17925            if (pir != null) {
17926                final Iterator<PreferredActivity> it = pir.filterIterator();
17927                while (it.hasNext()) {
17928                    final PreferredActivity pa = it.next();
17929                    if (packageName == null
17930                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17931                                    && pa.mPref.mAlways)) {
17932                        if (outFilters != null) {
17933                            outFilters.add(new IntentFilter(pa));
17934                        }
17935                        if (outActivities != null) {
17936                            outActivities.add(pa.mPref.mComponent);
17937                        }
17938                    }
17939                }
17940            }
17941        }
17942
17943        return num;
17944    }
17945
17946    @Override
17947    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17948            int userId) {
17949        int callingUid = Binder.getCallingUid();
17950        if (callingUid != Process.SYSTEM_UID) {
17951            throw new SecurityException(
17952                    "addPersistentPreferredActivity can only be run by the system");
17953        }
17954        if (filter.countActions() == 0) {
17955            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17956            return;
17957        }
17958        synchronized (mPackages) {
17959            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17960                    ":");
17961            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17962            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17963                    new PersistentPreferredActivity(filter, activity));
17964            scheduleWritePackageRestrictionsLocked(userId);
17965            postPreferredActivityChangedBroadcast(userId);
17966        }
17967    }
17968
17969    @Override
17970    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17971        int callingUid = Binder.getCallingUid();
17972        if (callingUid != Process.SYSTEM_UID) {
17973            throw new SecurityException(
17974                    "clearPackagePersistentPreferredActivities can only be run by the system");
17975        }
17976        ArrayList<PersistentPreferredActivity> removed = null;
17977        boolean changed = false;
17978        synchronized (mPackages) {
17979            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17980                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17981                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17982                        .valueAt(i);
17983                if (userId != thisUserId) {
17984                    continue;
17985                }
17986                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17987                while (it.hasNext()) {
17988                    PersistentPreferredActivity ppa = it.next();
17989                    // Mark entry for removal only if it matches the package name.
17990                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17991                        if (removed == null) {
17992                            removed = new ArrayList<PersistentPreferredActivity>();
17993                        }
17994                        removed.add(ppa);
17995                    }
17996                }
17997                if (removed != null) {
17998                    for (int j=0; j<removed.size(); j++) {
17999                        PersistentPreferredActivity ppa = removed.get(j);
18000                        ppir.removeFilter(ppa);
18001                    }
18002                    changed = true;
18003                }
18004            }
18005
18006            if (changed) {
18007                scheduleWritePackageRestrictionsLocked(userId);
18008                postPreferredActivityChangedBroadcast(userId);
18009            }
18010        }
18011    }
18012
18013    /**
18014     * Common machinery for picking apart a restored XML blob and passing
18015     * it to a caller-supplied functor to be applied to the running system.
18016     */
18017    private void restoreFromXml(XmlPullParser parser, int userId,
18018            String expectedStartTag, BlobXmlRestorer functor)
18019            throws IOException, XmlPullParserException {
18020        int type;
18021        while ((type = parser.next()) != XmlPullParser.START_TAG
18022                && type != XmlPullParser.END_DOCUMENT) {
18023        }
18024        if (type != XmlPullParser.START_TAG) {
18025            // oops didn't find a start tag?!
18026            if (DEBUG_BACKUP) {
18027                Slog.e(TAG, "Didn't find start tag during restore");
18028            }
18029            return;
18030        }
18031Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18032        // this is supposed to be TAG_PREFERRED_BACKUP
18033        if (!expectedStartTag.equals(parser.getName())) {
18034            if (DEBUG_BACKUP) {
18035                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18036            }
18037            return;
18038        }
18039
18040        // skip interfering stuff, then we're aligned with the backing implementation
18041        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18042Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18043        functor.apply(parser, userId);
18044    }
18045
18046    private interface BlobXmlRestorer {
18047        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18048    }
18049
18050    /**
18051     * Non-Binder method, support for the backup/restore mechanism: write the
18052     * full set of preferred activities in its canonical XML format.  Returns the
18053     * XML output as a byte array, or null if there is none.
18054     */
18055    @Override
18056    public byte[] getPreferredActivityBackup(int userId) {
18057        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18058            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18059        }
18060
18061        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18062        try {
18063            final XmlSerializer serializer = new FastXmlSerializer();
18064            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18065            serializer.startDocument(null, true);
18066            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18067
18068            synchronized (mPackages) {
18069                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18070            }
18071
18072            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18073            serializer.endDocument();
18074            serializer.flush();
18075        } catch (Exception e) {
18076            if (DEBUG_BACKUP) {
18077                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18078            }
18079            return null;
18080        }
18081
18082        return dataStream.toByteArray();
18083    }
18084
18085    @Override
18086    public void restorePreferredActivities(byte[] backup, int userId) {
18087        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18088            throw new SecurityException("Only the system may call restorePreferredActivities()");
18089        }
18090
18091        try {
18092            final XmlPullParser parser = Xml.newPullParser();
18093            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18094            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18095                    new BlobXmlRestorer() {
18096                        @Override
18097                        public void apply(XmlPullParser parser, int userId)
18098                                throws XmlPullParserException, IOException {
18099                            synchronized (mPackages) {
18100                                mSettings.readPreferredActivitiesLPw(parser, userId);
18101                            }
18102                        }
18103                    } );
18104        } catch (Exception e) {
18105            if (DEBUG_BACKUP) {
18106                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18107            }
18108        }
18109    }
18110
18111    /**
18112     * Non-Binder method, support for the backup/restore mechanism: write the
18113     * default browser (etc) settings in its canonical XML format.  Returns the default
18114     * browser XML representation as a byte array, or null if there is none.
18115     */
18116    @Override
18117    public byte[] getDefaultAppsBackup(int userId) {
18118        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18119            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18120        }
18121
18122        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18123        try {
18124            final XmlSerializer serializer = new FastXmlSerializer();
18125            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18126            serializer.startDocument(null, true);
18127            serializer.startTag(null, TAG_DEFAULT_APPS);
18128
18129            synchronized (mPackages) {
18130                mSettings.writeDefaultAppsLPr(serializer, userId);
18131            }
18132
18133            serializer.endTag(null, TAG_DEFAULT_APPS);
18134            serializer.endDocument();
18135            serializer.flush();
18136        } catch (Exception e) {
18137            if (DEBUG_BACKUP) {
18138                Slog.e(TAG, "Unable to write default apps for backup", e);
18139            }
18140            return null;
18141        }
18142
18143        return dataStream.toByteArray();
18144    }
18145
18146    @Override
18147    public void restoreDefaultApps(byte[] backup, int userId) {
18148        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18149            throw new SecurityException("Only the system may call restoreDefaultApps()");
18150        }
18151
18152        try {
18153            final XmlPullParser parser = Xml.newPullParser();
18154            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18155            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18156                    new BlobXmlRestorer() {
18157                        @Override
18158                        public void apply(XmlPullParser parser, int userId)
18159                                throws XmlPullParserException, IOException {
18160                            synchronized (mPackages) {
18161                                mSettings.readDefaultAppsLPw(parser, userId);
18162                            }
18163                        }
18164                    } );
18165        } catch (Exception e) {
18166            if (DEBUG_BACKUP) {
18167                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18168            }
18169        }
18170    }
18171
18172    @Override
18173    public byte[] getIntentFilterVerificationBackup(int userId) {
18174        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18175            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18176        }
18177
18178        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18179        try {
18180            final XmlSerializer serializer = new FastXmlSerializer();
18181            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18182            serializer.startDocument(null, true);
18183            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18184
18185            synchronized (mPackages) {
18186                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18187            }
18188
18189            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18190            serializer.endDocument();
18191            serializer.flush();
18192        } catch (Exception e) {
18193            if (DEBUG_BACKUP) {
18194                Slog.e(TAG, "Unable to write default apps for backup", e);
18195            }
18196            return null;
18197        }
18198
18199        return dataStream.toByteArray();
18200    }
18201
18202    @Override
18203    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18204        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18205            throw new SecurityException("Only the system may call restorePreferredActivities()");
18206        }
18207
18208        try {
18209            final XmlPullParser parser = Xml.newPullParser();
18210            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18211            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18212                    new BlobXmlRestorer() {
18213                        @Override
18214                        public void apply(XmlPullParser parser, int userId)
18215                                throws XmlPullParserException, IOException {
18216                            synchronized (mPackages) {
18217                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18218                                mSettings.writeLPr();
18219                            }
18220                        }
18221                    } );
18222        } catch (Exception e) {
18223            if (DEBUG_BACKUP) {
18224                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18225            }
18226        }
18227    }
18228
18229    @Override
18230    public byte[] getPermissionGrantBackup(int userId) {
18231        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18232            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18233        }
18234
18235        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18236        try {
18237            final XmlSerializer serializer = new FastXmlSerializer();
18238            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18239            serializer.startDocument(null, true);
18240            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18241
18242            synchronized (mPackages) {
18243                serializeRuntimePermissionGrantsLPr(serializer, userId);
18244            }
18245
18246            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18247            serializer.endDocument();
18248            serializer.flush();
18249        } catch (Exception e) {
18250            if (DEBUG_BACKUP) {
18251                Slog.e(TAG, "Unable to write default apps for backup", e);
18252            }
18253            return null;
18254        }
18255
18256        return dataStream.toByteArray();
18257    }
18258
18259    @Override
18260    public void restorePermissionGrants(byte[] backup, int userId) {
18261        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18262            throw new SecurityException("Only the system may call restorePermissionGrants()");
18263        }
18264
18265        try {
18266            final XmlPullParser parser = Xml.newPullParser();
18267            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18268            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18269                    new BlobXmlRestorer() {
18270                        @Override
18271                        public void apply(XmlPullParser parser, int userId)
18272                                throws XmlPullParserException, IOException {
18273                            synchronized (mPackages) {
18274                                processRestoredPermissionGrantsLPr(parser, userId);
18275                            }
18276                        }
18277                    } );
18278        } catch (Exception e) {
18279            if (DEBUG_BACKUP) {
18280                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18281            }
18282        }
18283    }
18284
18285    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18286            throws IOException {
18287        serializer.startTag(null, TAG_ALL_GRANTS);
18288
18289        final int N = mSettings.mPackages.size();
18290        for (int i = 0; i < N; i++) {
18291            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18292            boolean pkgGrantsKnown = false;
18293
18294            PermissionsState packagePerms = ps.getPermissionsState();
18295
18296            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18297                final int grantFlags = state.getFlags();
18298                // only look at grants that are not system/policy fixed
18299                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18300                    final boolean isGranted = state.isGranted();
18301                    // And only back up the user-twiddled state bits
18302                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18303                        final String packageName = mSettings.mPackages.keyAt(i);
18304                        if (!pkgGrantsKnown) {
18305                            serializer.startTag(null, TAG_GRANT);
18306                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18307                            pkgGrantsKnown = true;
18308                        }
18309
18310                        final boolean userSet =
18311                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18312                        final boolean userFixed =
18313                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18314                        final boolean revoke =
18315                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18316
18317                        serializer.startTag(null, TAG_PERMISSION);
18318                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18319                        if (isGranted) {
18320                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18321                        }
18322                        if (userSet) {
18323                            serializer.attribute(null, ATTR_USER_SET, "true");
18324                        }
18325                        if (userFixed) {
18326                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18327                        }
18328                        if (revoke) {
18329                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18330                        }
18331                        serializer.endTag(null, TAG_PERMISSION);
18332                    }
18333                }
18334            }
18335
18336            if (pkgGrantsKnown) {
18337                serializer.endTag(null, TAG_GRANT);
18338            }
18339        }
18340
18341        serializer.endTag(null, TAG_ALL_GRANTS);
18342    }
18343
18344    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18345            throws XmlPullParserException, IOException {
18346        String pkgName = null;
18347        int outerDepth = parser.getDepth();
18348        int type;
18349        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18350                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18351            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18352                continue;
18353            }
18354
18355            final String tagName = parser.getName();
18356            if (tagName.equals(TAG_GRANT)) {
18357                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18358                if (DEBUG_BACKUP) {
18359                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18360                }
18361            } else if (tagName.equals(TAG_PERMISSION)) {
18362
18363                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18364                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18365
18366                int newFlagSet = 0;
18367                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18368                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18369                }
18370                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18371                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18372                }
18373                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18374                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18375                }
18376                if (DEBUG_BACKUP) {
18377                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18378                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18379                }
18380                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18381                if (ps != null) {
18382                    // Already installed so we apply the grant immediately
18383                    if (DEBUG_BACKUP) {
18384                        Slog.v(TAG, "        + already installed; applying");
18385                    }
18386                    PermissionsState perms = ps.getPermissionsState();
18387                    BasePermission bp = mSettings.mPermissions.get(permName);
18388                    if (bp != null) {
18389                        if (isGranted) {
18390                            perms.grantRuntimePermission(bp, userId);
18391                        }
18392                        if (newFlagSet != 0) {
18393                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18394                        }
18395                    }
18396                } else {
18397                    // Need to wait for post-restore install to apply the grant
18398                    if (DEBUG_BACKUP) {
18399                        Slog.v(TAG, "        - not yet installed; saving for later");
18400                    }
18401                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18402                            isGranted, newFlagSet, userId);
18403                }
18404            } else {
18405                PackageManagerService.reportSettingsProblem(Log.WARN,
18406                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18407                XmlUtils.skipCurrentTag(parser);
18408            }
18409        }
18410
18411        scheduleWriteSettingsLocked();
18412        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18413    }
18414
18415    @Override
18416    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18417            int sourceUserId, int targetUserId, int flags) {
18418        mContext.enforceCallingOrSelfPermission(
18419                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18420        int callingUid = Binder.getCallingUid();
18421        enforceOwnerRights(ownerPackage, callingUid);
18422        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18423        if (intentFilter.countActions() == 0) {
18424            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18425            return;
18426        }
18427        synchronized (mPackages) {
18428            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18429                    ownerPackage, targetUserId, flags);
18430            CrossProfileIntentResolver resolver =
18431                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18432            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18433            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18434            if (existing != null) {
18435                int size = existing.size();
18436                for (int i = 0; i < size; i++) {
18437                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18438                        return;
18439                    }
18440                }
18441            }
18442            resolver.addFilter(newFilter);
18443            scheduleWritePackageRestrictionsLocked(sourceUserId);
18444        }
18445    }
18446
18447    @Override
18448    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18449        mContext.enforceCallingOrSelfPermission(
18450                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18451        int callingUid = Binder.getCallingUid();
18452        enforceOwnerRights(ownerPackage, callingUid);
18453        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18454        synchronized (mPackages) {
18455            CrossProfileIntentResolver resolver =
18456                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18457            ArraySet<CrossProfileIntentFilter> set =
18458                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18459            for (CrossProfileIntentFilter filter : set) {
18460                if (filter.getOwnerPackage().equals(ownerPackage)) {
18461                    resolver.removeFilter(filter);
18462                }
18463            }
18464            scheduleWritePackageRestrictionsLocked(sourceUserId);
18465        }
18466    }
18467
18468    // Enforcing that callingUid is owning pkg on userId
18469    private void enforceOwnerRights(String pkg, int callingUid) {
18470        // The system owns everything.
18471        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18472            return;
18473        }
18474        int callingUserId = UserHandle.getUserId(callingUid);
18475        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18476        if (pi == null) {
18477            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18478                    + callingUserId);
18479        }
18480        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18481            throw new SecurityException("Calling uid " + callingUid
18482                    + " does not own package " + pkg);
18483        }
18484    }
18485
18486    @Override
18487    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18488        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18489    }
18490
18491    private Intent getHomeIntent() {
18492        Intent intent = new Intent(Intent.ACTION_MAIN);
18493        intent.addCategory(Intent.CATEGORY_HOME);
18494        intent.addCategory(Intent.CATEGORY_DEFAULT);
18495        return intent;
18496    }
18497
18498    private IntentFilter getHomeFilter() {
18499        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18500        filter.addCategory(Intent.CATEGORY_HOME);
18501        filter.addCategory(Intent.CATEGORY_DEFAULT);
18502        return filter;
18503    }
18504
18505    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18506            int userId) {
18507        Intent intent  = getHomeIntent();
18508        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18509                PackageManager.GET_META_DATA, userId);
18510        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18511                true, false, false, userId);
18512
18513        allHomeCandidates.clear();
18514        if (list != null) {
18515            for (ResolveInfo ri : list) {
18516                allHomeCandidates.add(ri);
18517            }
18518        }
18519        return (preferred == null || preferred.activityInfo == null)
18520                ? null
18521                : new ComponentName(preferred.activityInfo.packageName,
18522                        preferred.activityInfo.name);
18523    }
18524
18525    @Override
18526    public void setHomeActivity(ComponentName comp, int userId) {
18527        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18528        getHomeActivitiesAsUser(homeActivities, userId);
18529
18530        boolean found = false;
18531
18532        final int size = homeActivities.size();
18533        final ComponentName[] set = new ComponentName[size];
18534        for (int i = 0; i < size; i++) {
18535            final ResolveInfo candidate = homeActivities.get(i);
18536            final ActivityInfo info = candidate.activityInfo;
18537            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18538            set[i] = activityName;
18539            if (!found && activityName.equals(comp)) {
18540                found = true;
18541            }
18542        }
18543        if (!found) {
18544            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18545                    + userId);
18546        }
18547        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18548                set, comp, userId);
18549    }
18550
18551    private @Nullable String getSetupWizardPackageName() {
18552        final Intent intent = new Intent(Intent.ACTION_MAIN);
18553        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18554
18555        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18556                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18557                        | MATCH_DISABLED_COMPONENTS,
18558                UserHandle.myUserId());
18559        if (matches.size() == 1) {
18560            return matches.get(0).getComponentInfo().packageName;
18561        } else {
18562            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18563                    + ": matches=" + matches);
18564            return null;
18565        }
18566    }
18567
18568    private @Nullable String getStorageManagerPackageName() {
18569        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18570
18571        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18572                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18573                        | MATCH_DISABLED_COMPONENTS,
18574                UserHandle.myUserId());
18575        if (matches.size() == 1) {
18576            return matches.get(0).getComponentInfo().packageName;
18577        } else {
18578            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18579                    + matches.size() + ": matches=" + matches);
18580            return null;
18581        }
18582    }
18583
18584    @Override
18585    public void setApplicationEnabledSetting(String appPackageName,
18586            int newState, int flags, int userId, String callingPackage) {
18587        if (!sUserManager.exists(userId)) return;
18588        if (callingPackage == null) {
18589            callingPackage = Integer.toString(Binder.getCallingUid());
18590        }
18591        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18592    }
18593
18594    @Override
18595    public void setComponentEnabledSetting(ComponentName componentName,
18596            int newState, int flags, int userId) {
18597        if (!sUserManager.exists(userId)) return;
18598        setEnabledSetting(componentName.getPackageName(),
18599                componentName.getClassName(), newState, flags, userId, null);
18600    }
18601
18602    private void setEnabledSetting(final String packageName, String className, int newState,
18603            final int flags, int userId, String callingPackage) {
18604        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18605              || newState == COMPONENT_ENABLED_STATE_ENABLED
18606              || newState == COMPONENT_ENABLED_STATE_DISABLED
18607              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18608              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18609            throw new IllegalArgumentException("Invalid new component state: "
18610                    + newState);
18611        }
18612        PackageSetting pkgSetting;
18613        final int uid = Binder.getCallingUid();
18614        final int permission;
18615        if (uid == Process.SYSTEM_UID) {
18616            permission = PackageManager.PERMISSION_GRANTED;
18617        } else {
18618            permission = mContext.checkCallingOrSelfPermission(
18619                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18620        }
18621        enforceCrossUserPermission(uid, userId,
18622                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18623        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18624        boolean sendNow = false;
18625        boolean isApp = (className == null);
18626        String componentName = isApp ? packageName : className;
18627        int packageUid = -1;
18628        ArrayList<String> components;
18629
18630        // writer
18631        synchronized (mPackages) {
18632            pkgSetting = mSettings.mPackages.get(packageName);
18633            if (pkgSetting == null) {
18634                if (className == null) {
18635                    throw new IllegalArgumentException("Unknown package: " + packageName);
18636                }
18637                throw new IllegalArgumentException(
18638                        "Unknown component: " + packageName + "/" + className);
18639            }
18640        }
18641
18642        // Limit who can change which apps
18643        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18644            // Don't allow apps that don't have permission to modify other apps
18645            if (!allowedByPermission) {
18646                throw new SecurityException(
18647                        "Permission Denial: attempt to change component state from pid="
18648                        + Binder.getCallingPid()
18649                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18650            }
18651            // Don't allow changing protected packages.
18652            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18653                throw new SecurityException("Cannot disable a protected package: " + packageName);
18654            }
18655        }
18656
18657        synchronized (mPackages) {
18658            if (uid == Process.SHELL_UID
18659                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18660                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18661                // unless it is a test package.
18662                int oldState = pkgSetting.getEnabled(userId);
18663                if (className == null
18664                    &&
18665                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18666                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18667                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18668                    &&
18669                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18670                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18671                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18672                    // ok
18673                } else {
18674                    throw new SecurityException(
18675                            "Shell cannot change component state for " + packageName + "/"
18676                            + className + " to " + newState);
18677                }
18678            }
18679            if (className == null) {
18680                // We're dealing with an application/package level state change
18681                if (pkgSetting.getEnabled(userId) == newState) {
18682                    // Nothing to do
18683                    return;
18684                }
18685                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18686                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18687                    // Don't care about who enables an app.
18688                    callingPackage = null;
18689                }
18690                pkgSetting.setEnabled(newState, userId, callingPackage);
18691                // pkgSetting.pkg.mSetEnabled = newState;
18692            } else {
18693                // We're dealing with a component level state change
18694                // First, verify that this is a valid class name.
18695                PackageParser.Package pkg = pkgSetting.pkg;
18696                if (pkg == null || !pkg.hasComponentClassName(className)) {
18697                    if (pkg != null &&
18698                            pkg.applicationInfo.targetSdkVersion >=
18699                                    Build.VERSION_CODES.JELLY_BEAN) {
18700                        throw new IllegalArgumentException("Component class " + className
18701                                + " does not exist in " + packageName);
18702                    } else {
18703                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18704                                + className + " does not exist in " + packageName);
18705                    }
18706                }
18707                switch (newState) {
18708                case COMPONENT_ENABLED_STATE_ENABLED:
18709                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18710                        return;
18711                    }
18712                    break;
18713                case COMPONENT_ENABLED_STATE_DISABLED:
18714                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18715                        return;
18716                    }
18717                    break;
18718                case COMPONENT_ENABLED_STATE_DEFAULT:
18719                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18720                        return;
18721                    }
18722                    break;
18723                default:
18724                    Slog.e(TAG, "Invalid new component state: " + newState);
18725                    return;
18726                }
18727            }
18728            scheduleWritePackageRestrictionsLocked(userId);
18729            components = mPendingBroadcasts.get(userId, packageName);
18730            final boolean newPackage = components == null;
18731            if (newPackage) {
18732                components = new ArrayList<String>();
18733            }
18734            if (!components.contains(componentName)) {
18735                components.add(componentName);
18736            }
18737            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18738                sendNow = true;
18739                // Purge entry from pending broadcast list if another one exists already
18740                // since we are sending one right away.
18741                mPendingBroadcasts.remove(userId, packageName);
18742            } else {
18743                if (newPackage) {
18744                    mPendingBroadcasts.put(userId, packageName, components);
18745                }
18746                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18747                    // Schedule a message
18748                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18749                }
18750            }
18751        }
18752
18753        long callingId = Binder.clearCallingIdentity();
18754        try {
18755            if (sendNow) {
18756                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18757                sendPackageChangedBroadcast(packageName,
18758                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18759            }
18760        } finally {
18761            Binder.restoreCallingIdentity(callingId);
18762        }
18763    }
18764
18765    @Override
18766    public void flushPackageRestrictionsAsUser(int userId) {
18767        if (!sUserManager.exists(userId)) {
18768            return;
18769        }
18770        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18771                false /* checkShell */, "flushPackageRestrictions");
18772        synchronized (mPackages) {
18773            mSettings.writePackageRestrictionsLPr(userId);
18774            mDirtyUsers.remove(userId);
18775            if (mDirtyUsers.isEmpty()) {
18776                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18777            }
18778        }
18779    }
18780
18781    private void sendPackageChangedBroadcast(String packageName,
18782            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18783        if (DEBUG_INSTALL)
18784            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18785                    + componentNames);
18786        Bundle extras = new Bundle(4);
18787        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18788        String nameList[] = new String[componentNames.size()];
18789        componentNames.toArray(nameList);
18790        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18791        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18792        extras.putInt(Intent.EXTRA_UID, packageUid);
18793        // If this is not reporting a change of the overall package, then only send it
18794        // to registered receivers.  We don't want to launch a swath of apps for every
18795        // little component state change.
18796        final int flags = !componentNames.contains(packageName)
18797                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18798        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18799                new int[] {UserHandle.getUserId(packageUid)});
18800    }
18801
18802    @Override
18803    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18804        if (!sUserManager.exists(userId)) return;
18805        final int uid = Binder.getCallingUid();
18806        final int permission = mContext.checkCallingOrSelfPermission(
18807                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18808        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18809        enforceCrossUserPermission(uid, userId,
18810                true /* requireFullPermission */, true /* checkShell */, "stop package");
18811        // writer
18812        synchronized (mPackages) {
18813            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18814                    allowedByPermission, uid, userId)) {
18815                scheduleWritePackageRestrictionsLocked(userId);
18816            }
18817        }
18818    }
18819
18820    @Override
18821    public String getInstallerPackageName(String packageName) {
18822        // reader
18823        synchronized (mPackages) {
18824            return mSettings.getInstallerPackageNameLPr(packageName);
18825        }
18826    }
18827
18828    public boolean isOrphaned(String packageName) {
18829        // reader
18830        synchronized (mPackages) {
18831            return mSettings.isOrphaned(packageName);
18832        }
18833    }
18834
18835    @Override
18836    public int getApplicationEnabledSetting(String packageName, int userId) {
18837        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18838        int uid = Binder.getCallingUid();
18839        enforceCrossUserPermission(uid, userId,
18840                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18841        // reader
18842        synchronized (mPackages) {
18843            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18844        }
18845    }
18846
18847    @Override
18848    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18849        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18850        int uid = Binder.getCallingUid();
18851        enforceCrossUserPermission(uid, userId,
18852                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18853        // reader
18854        synchronized (mPackages) {
18855            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18856        }
18857    }
18858
18859    @Override
18860    public void enterSafeMode() {
18861        enforceSystemOrRoot("Only the system can request entering safe mode");
18862
18863        if (!mSystemReady) {
18864            mSafeMode = true;
18865        }
18866    }
18867
18868    @Override
18869    public void systemReady() {
18870        mSystemReady = true;
18871
18872        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18873        // disabled after already being started.
18874        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18875                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18876
18877        // Read the compatibilty setting when the system is ready.
18878        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18879                mContext.getContentResolver(),
18880                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18881        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18882        if (DEBUG_SETTINGS) {
18883            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18884        }
18885
18886        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18887
18888        synchronized (mPackages) {
18889            // Verify that all of the preferred activity components actually
18890            // exist.  It is possible for applications to be updated and at
18891            // that point remove a previously declared activity component that
18892            // had been set as a preferred activity.  We try to clean this up
18893            // the next time we encounter that preferred activity, but it is
18894            // possible for the user flow to never be able to return to that
18895            // situation so here we do a sanity check to make sure we haven't
18896            // left any junk around.
18897            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18898            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18899                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18900                removed.clear();
18901                for (PreferredActivity pa : pir.filterSet()) {
18902                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18903                        removed.add(pa);
18904                    }
18905                }
18906                if (removed.size() > 0) {
18907                    for (int r=0; r<removed.size(); r++) {
18908                        PreferredActivity pa = removed.get(r);
18909                        Slog.w(TAG, "Removing dangling preferred activity: "
18910                                + pa.mPref.mComponent);
18911                        pir.removeFilter(pa);
18912                    }
18913                    mSettings.writePackageRestrictionsLPr(
18914                            mSettings.mPreferredActivities.keyAt(i));
18915                }
18916            }
18917
18918            for (int userId : UserManagerService.getInstance().getUserIds()) {
18919                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18920                    grantPermissionsUserIds = ArrayUtils.appendInt(
18921                            grantPermissionsUserIds, userId);
18922                }
18923            }
18924        }
18925        sUserManager.systemReady();
18926
18927        // If we upgraded grant all default permissions before kicking off.
18928        for (int userId : grantPermissionsUserIds) {
18929            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18930        }
18931
18932        // If we did not grant default permissions, we preload from this the
18933        // default permission exceptions lazily to ensure we don't hit the
18934        // disk on a new user creation.
18935        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18936            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18937        }
18938
18939        // Kick off any messages waiting for system ready
18940        if (mPostSystemReadyMessages != null) {
18941            for (Message msg : mPostSystemReadyMessages) {
18942                msg.sendToTarget();
18943            }
18944            mPostSystemReadyMessages = null;
18945        }
18946
18947        // Watch for external volumes that come and go over time
18948        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18949        storage.registerListener(mStorageListener);
18950
18951        mInstallerService.systemReady();
18952        mPackageDexOptimizer.systemReady();
18953
18954        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18955                StorageManagerInternal.class);
18956        StorageManagerInternal.addExternalStoragePolicy(
18957                new StorageManagerInternal.ExternalStorageMountPolicy() {
18958            @Override
18959            public int getMountMode(int uid, String packageName) {
18960                if (Process.isIsolated(uid)) {
18961                    return Zygote.MOUNT_EXTERNAL_NONE;
18962                }
18963                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18964                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18965                }
18966                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18967                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18968                }
18969                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18970                    return Zygote.MOUNT_EXTERNAL_READ;
18971                }
18972                return Zygote.MOUNT_EXTERNAL_WRITE;
18973            }
18974
18975            @Override
18976            public boolean hasExternalStorage(int uid, String packageName) {
18977                return true;
18978            }
18979        });
18980
18981        // Now that we're mostly running, clean up stale users and apps
18982        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18983        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18984    }
18985
18986    @Override
18987    public boolean isSafeMode() {
18988        return mSafeMode;
18989    }
18990
18991    @Override
18992    public boolean hasSystemUidErrors() {
18993        return mHasSystemUidErrors;
18994    }
18995
18996    static String arrayToString(int[] array) {
18997        StringBuffer buf = new StringBuffer(128);
18998        buf.append('[');
18999        if (array != null) {
19000            for (int i=0; i<array.length; i++) {
19001                if (i > 0) buf.append(", ");
19002                buf.append(array[i]);
19003            }
19004        }
19005        buf.append(']');
19006        return buf.toString();
19007    }
19008
19009    static class DumpState {
19010        public static final int DUMP_LIBS = 1 << 0;
19011        public static final int DUMP_FEATURES = 1 << 1;
19012        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19013        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19014        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19015        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19016        public static final int DUMP_PERMISSIONS = 1 << 6;
19017        public static final int DUMP_PACKAGES = 1 << 7;
19018        public static final int DUMP_SHARED_USERS = 1 << 8;
19019        public static final int DUMP_MESSAGES = 1 << 9;
19020        public static final int DUMP_PROVIDERS = 1 << 10;
19021        public static final int DUMP_VERIFIERS = 1 << 11;
19022        public static final int DUMP_PREFERRED = 1 << 12;
19023        public static final int DUMP_PREFERRED_XML = 1 << 13;
19024        public static final int DUMP_KEYSETS = 1 << 14;
19025        public static final int DUMP_VERSION = 1 << 15;
19026        public static final int DUMP_INSTALLS = 1 << 16;
19027        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19028        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19029        public static final int DUMP_FROZEN = 1 << 19;
19030        public static final int DUMP_DEXOPT = 1 << 20;
19031        public static final int DUMP_COMPILER_STATS = 1 << 21;
19032
19033        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19034
19035        private int mTypes;
19036
19037        private int mOptions;
19038
19039        private boolean mTitlePrinted;
19040
19041        private SharedUserSetting mSharedUser;
19042
19043        public boolean isDumping(int type) {
19044            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19045                return true;
19046            }
19047
19048            return (mTypes & type) != 0;
19049        }
19050
19051        public void setDump(int type) {
19052            mTypes |= type;
19053        }
19054
19055        public boolean isOptionEnabled(int option) {
19056            return (mOptions & option) != 0;
19057        }
19058
19059        public void setOptionEnabled(int option) {
19060            mOptions |= option;
19061        }
19062
19063        public boolean onTitlePrinted() {
19064            final boolean printed = mTitlePrinted;
19065            mTitlePrinted = true;
19066            return printed;
19067        }
19068
19069        public boolean getTitlePrinted() {
19070            return mTitlePrinted;
19071        }
19072
19073        public void setTitlePrinted(boolean enabled) {
19074            mTitlePrinted = enabled;
19075        }
19076
19077        public SharedUserSetting getSharedUser() {
19078            return mSharedUser;
19079        }
19080
19081        public void setSharedUser(SharedUserSetting user) {
19082            mSharedUser = user;
19083        }
19084    }
19085
19086    @Override
19087    public void onShellCommand(FileDescriptor in, FileDescriptor out,
19088            FileDescriptor err, String[] args, ShellCallback callback,
19089            ResultReceiver resultReceiver) {
19090        (new PackageManagerShellCommand(this)).exec(
19091                this, in, out, err, args, callback, resultReceiver);
19092    }
19093
19094    @Override
19095    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
19096        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
19097                != PackageManager.PERMISSION_GRANTED) {
19098            pw.println("Permission Denial: can't dump ActivityManager from from pid="
19099                    + Binder.getCallingPid()
19100                    + ", uid=" + Binder.getCallingUid()
19101                    + " without permission "
19102                    + android.Manifest.permission.DUMP);
19103            return;
19104        }
19105
19106        DumpState dumpState = new DumpState();
19107        boolean fullPreferred = false;
19108        boolean checkin = false;
19109
19110        String packageName = null;
19111        ArraySet<String> permissionNames = null;
19112
19113        int opti = 0;
19114        while (opti < args.length) {
19115            String opt = args[opti];
19116            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
19117                break;
19118            }
19119            opti++;
19120
19121            if ("-a".equals(opt)) {
19122                // Right now we only know how to print all.
19123            } else if ("-h".equals(opt)) {
19124                pw.println("Package manager dump options:");
19125                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
19126                pw.println("    --checkin: dump for a checkin");
19127                pw.println("    -f: print details of intent filters");
19128                pw.println("    -h: print this help");
19129                pw.println("  cmd may be one of:");
19130                pw.println("    l[ibraries]: list known shared libraries");
19131                pw.println("    f[eatures]: list device features");
19132                pw.println("    k[eysets]: print known keysets");
19133                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
19134                pw.println("    perm[issions]: dump permissions");
19135                pw.println("    permission [name ...]: dump declaration and use of given permission");
19136                pw.println("    pref[erred]: print preferred package settings");
19137                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
19138                pw.println("    prov[iders]: dump content providers");
19139                pw.println("    p[ackages]: dump installed packages");
19140                pw.println("    s[hared-users]: dump shared user IDs");
19141                pw.println("    m[essages]: print collected runtime messages");
19142                pw.println("    v[erifiers]: print package verifier info");
19143                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
19144                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
19145                pw.println("    version: print database version info");
19146                pw.println("    write: write current settings now");
19147                pw.println("    installs: details about install sessions");
19148                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
19149                pw.println("    dexopt: dump dexopt state");
19150                pw.println("    compiler-stats: dump compiler statistics");
19151                pw.println("    <package.name>: info about given package");
19152                return;
19153            } else if ("--checkin".equals(opt)) {
19154                checkin = true;
19155            } else if ("-f".equals(opt)) {
19156                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19157            } else {
19158                pw.println("Unknown argument: " + opt + "; use -h for help");
19159            }
19160        }
19161
19162        // Is the caller requesting to dump a particular piece of data?
19163        if (opti < args.length) {
19164            String cmd = args[opti];
19165            opti++;
19166            // Is this a package name?
19167            if ("android".equals(cmd) || cmd.contains(".")) {
19168                packageName = cmd;
19169                // When dumping a single package, we always dump all of its
19170                // filter information since the amount of data will be reasonable.
19171                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19172            } else if ("check-permission".equals(cmd)) {
19173                if (opti >= args.length) {
19174                    pw.println("Error: check-permission missing permission argument");
19175                    return;
19176                }
19177                String perm = args[opti];
19178                opti++;
19179                if (opti >= args.length) {
19180                    pw.println("Error: check-permission missing package argument");
19181                    return;
19182                }
19183                String pkg = args[opti];
19184                opti++;
19185                int user = UserHandle.getUserId(Binder.getCallingUid());
19186                if (opti < args.length) {
19187                    try {
19188                        user = Integer.parseInt(args[opti]);
19189                    } catch (NumberFormatException e) {
19190                        pw.println("Error: check-permission user argument is not a number: "
19191                                + args[opti]);
19192                        return;
19193                    }
19194                }
19195                pw.println(checkPermission(perm, pkg, user));
19196                return;
19197            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
19198                dumpState.setDump(DumpState.DUMP_LIBS);
19199            } else if ("f".equals(cmd) || "features".equals(cmd)) {
19200                dumpState.setDump(DumpState.DUMP_FEATURES);
19201            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
19202                if (opti >= args.length) {
19203                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
19204                            | DumpState.DUMP_SERVICE_RESOLVERS
19205                            | DumpState.DUMP_RECEIVER_RESOLVERS
19206                            | DumpState.DUMP_CONTENT_RESOLVERS);
19207                } else {
19208                    while (opti < args.length) {
19209                        String name = args[opti];
19210                        if ("a".equals(name) || "activity".equals(name)) {
19211                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
19212                        } else if ("s".equals(name) || "service".equals(name)) {
19213                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
19214                        } else if ("r".equals(name) || "receiver".equals(name)) {
19215                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19216                        } else if ("c".equals(name) || "content".equals(name)) {
19217                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19218                        } else {
19219                            pw.println("Error: unknown resolver table type: " + name);
19220                            return;
19221                        }
19222                        opti++;
19223                    }
19224                }
19225            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19226                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19227            } else if ("permission".equals(cmd)) {
19228                if (opti >= args.length) {
19229                    pw.println("Error: permission requires permission name");
19230                    return;
19231                }
19232                permissionNames = new ArraySet<>();
19233                while (opti < args.length) {
19234                    permissionNames.add(args[opti]);
19235                    opti++;
19236                }
19237                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19238                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19239            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19240                dumpState.setDump(DumpState.DUMP_PREFERRED);
19241            } else if ("preferred-xml".equals(cmd)) {
19242                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19243                if (opti < args.length && "--full".equals(args[opti])) {
19244                    fullPreferred = true;
19245                    opti++;
19246                }
19247            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19248                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19249            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19250                dumpState.setDump(DumpState.DUMP_PACKAGES);
19251            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19252                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19253            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19254                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19255            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19256                dumpState.setDump(DumpState.DUMP_MESSAGES);
19257            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19258                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19259            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19260                    || "intent-filter-verifiers".equals(cmd)) {
19261                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19262            } else if ("version".equals(cmd)) {
19263                dumpState.setDump(DumpState.DUMP_VERSION);
19264            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19265                dumpState.setDump(DumpState.DUMP_KEYSETS);
19266            } else if ("installs".equals(cmd)) {
19267                dumpState.setDump(DumpState.DUMP_INSTALLS);
19268            } else if ("frozen".equals(cmd)) {
19269                dumpState.setDump(DumpState.DUMP_FROZEN);
19270            } else if ("dexopt".equals(cmd)) {
19271                dumpState.setDump(DumpState.DUMP_DEXOPT);
19272            } else if ("compiler-stats".equals(cmd)) {
19273                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19274            } else if ("write".equals(cmd)) {
19275                synchronized (mPackages) {
19276                    mSettings.writeLPr();
19277                    pw.println("Settings written.");
19278                    return;
19279                }
19280            }
19281        }
19282
19283        if (checkin) {
19284            pw.println("vers,1");
19285        }
19286
19287        // reader
19288        synchronized (mPackages) {
19289            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19290                if (!checkin) {
19291                    if (dumpState.onTitlePrinted())
19292                        pw.println();
19293                    pw.println("Database versions:");
19294                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19295                }
19296            }
19297
19298            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19299                if (!checkin) {
19300                    if (dumpState.onTitlePrinted())
19301                        pw.println();
19302                    pw.println("Verifiers:");
19303                    pw.print("  Required: ");
19304                    pw.print(mRequiredVerifierPackage);
19305                    pw.print(" (uid=");
19306                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19307                            UserHandle.USER_SYSTEM));
19308                    pw.println(")");
19309                } else if (mRequiredVerifierPackage != null) {
19310                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19311                    pw.print(",");
19312                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19313                            UserHandle.USER_SYSTEM));
19314                }
19315            }
19316
19317            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19318                    packageName == null) {
19319                if (mIntentFilterVerifierComponent != null) {
19320                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19321                    if (!checkin) {
19322                        if (dumpState.onTitlePrinted())
19323                            pw.println();
19324                        pw.println("Intent Filter Verifier:");
19325                        pw.print("  Using: ");
19326                        pw.print(verifierPackageName);
19327                        pw.print(" (uid=");
19328                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19329                                UserHandle.USER_SYSTEM));
19330                        pw.println(")");
19331                    } else if (verifierPackageName != null) {
19332                        pw.print("ifv,"); pw.print(verifierPackageName);
19333                        pw.print(",");
19334                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19335                                UserHandle.USER_SYSTEM));
19336                    }
19337                } else {
19338                    pw.println();
19339                    pw.println("No Intent Filter Verifier available!");
19340                }
19341            }
19342
19343            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19344                boolean printedHeader = false;
19345                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19346                while (it.hasNext()) {
19347                    String name = it.next();
19348                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19349                    if (!checkin) {
19350                        if (!printedHeader) {
19351                            if (dumpState.onTitlePrinted())
19352                                pw.println();
19353                            pw.println("Libraries:");
19354                            printedHeader = true;
19355                        }
19356                        pw.print("  ");
19357                    } else {
19358                        pw.print("lib,");
19359                    }
19360                    pw.print(name);
19361                    if (!checkin) {
19362                        pw.print(" -> ");
19363                    }
19364                    if (ent.path != null) {
19365                        if (!checkin) {
19366                            pw.print("(jar) ");
19367                            pw.print(ent.path);
19368                        } else {
19369                            pw.print(",jar,");
19370                            pw.print(ent.path);
19371                        }
19372                    } else {
19373                        if (!checkin) {
19374                            pw.print("(apk) ");
19375                            pw.print(ent.apk);
19376                        } else {
19377                            pw.print(",apk,");
19378                            pw.print(ent.apk);
19379                        }
19380                    }
19381                    pw.println();
19382                }
19383            }
19384
19385            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19386                if (dumpState.onTitlePrinted())
19387                    pw.println();
19388                if (!checkin) {
19389                    pw.println("Features:");
19390                }
19391
19392                for (FeatureInfo feat : mAvailableFeatures.values()) {
19393                    if (checkin) {
19394                        pw.print("feat,");
19395                        pw.print(feat.name);
19396                        pw.print(",");
19397                        pw.println(feat.version);
19398                    } else {
19399                        pw.print("  ");
19400                        pw.print(feat.name);
19401                        if (feat.version > 0) {
19402                            pw.print(" version=");
19403                            pw.print(feat.version);
19404                        }
19405                        pw.println();
19406                    }
19407                }
19408            }
19409
19410            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19411                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19412                        : "Activity Resolver Table:", "  ", packageName,
19413                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19414                    dumpState.setTitlePrinted(true);
19415                }
19416            }
19417            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19418                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19419                        : "Receiver Resolver Table:", "  ", packageName,
19420                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19421                    dumpState.setTitlePrinted(true);
19422                }
19423            }
19424            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19425                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19426                        : "Service Resolver Table:", "  ", packageName,
19427                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19428                    dumpState.setTitlePrinted(true);
19429                }
19430            }
19431            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19432                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19433                        : "Provider Resolver Table:", "  ", packageName,
19434                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19435                    dumpState.setTitlePrinted(true);
19436                }
19437            }
19438
19439            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19440                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19441                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19442                    int user = mSettings.mPreferredActivities.keyAt(i);
19443                    if (pir.dump(pw,
19444                            dumpState.getTitlePrinted()
19445                                ? "\nPreferred Activities User " + user + ":"
19446                                : "Preferred Activities User " + user + ":", "  ",
19447                            packageName, true, false)) {
19448                        dumpState.setTitlePrinted(true);
19449                    }
19450                }
19451            }
19452
19453            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19454                pw.flush();
19455                FileOutputStream fout = new FileOutputStream(fd);
19456                BufferedOutputStream str = new BufferedOutputStream(fout);
19457                XmlSerializer serializer = new FastXmlSerializer();
19458                try {
19459                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19460                    serializer.startDocument(null, true);
19461                    serializer.setFeature(
19462                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19463                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19464                    serializer.endDocument();
19465                    serializer.flush();
19466                } catch (IllegalArgumentException e) {
19467                    pw.println("Failed writing: " + e);
19468                } catch (IllegalStateException e) {
19469                    pw.println("Failed writing: " + e);
19470                } catch (IOException e) {
19471                    pw.println("Failed writing: " + e);
19472                }
19473            }
19474
19475            if (!checkin
19476                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19477                    && packageName == null) {
19478                pw.println();
19479                int count = mSettings.mPackages.size();
19480                if (count == 0) {
19481                    pw.println("No applications!");
19482                    pw.println();
19483                } else {
19484                    final String prefix = "  ";
19485                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19486                    if (allPackageSettings.size() == 0) {
19487                        pw.println("No domain preferred apps!");
19488                        pw.println();
19489                    } else {
19490                        pw.println("App verification status:");
19491                        pw.println();
19492                        count = 0;
19493                        for (PackageSetting ps : allPackageSettings) {
19494                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19495                            if (ivi == null || ivi.getPackageName() == null) continue;
19496                            pw.println(prefix + "Package: " + ivi.getPackageName());
19497                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19498                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19499                            pw.println();
19500                            count++;
19501                        }
19502                        if (count == 0) {
19503                            pw.println(prefix + "No app verification established.");
19504                            pw.println();
19505                        }
19506                        for (int userId : sUserManager.getUserIds()) {
19507                            pw.println("App linkages for user " + userId + ":");
19508                            pw.println();
19509                            count = 0;
19510                            for (PackageSetting ps : allPackageSettings) {
19511                                final long status = ps.getDomainVerificationStatusForUser(userId);
19512                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19513                                    continue;
19514                                }
19515                                pw.println(prefix + "Package: " + ps.name);
19516                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19517                                String statusStr = IntentFilterVerificationInfo.
19518                                        getStatusStringFromValue(status);
19519                                pw.println(prefix + "Status:  " + statusStr);
19520                                pw.println();
19521                                count++;
19522                            }
19523                            if (count == 0) {
19524                                pw.println(prefix + "No configured app linkages.");
19525                                pw.println();
19526                            }
19527                        }
19528                    }
19529                }
19530            }
19531
19532            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19533                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19534                if (packageName == null && permissionNames == null) {
19535                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19536                        if (iperm == 0) {
19537                            if (dumpState.onTitlePrinted())
19538                                pw.println();
19539                            pw.println("AppOp Permissions:");
19540                        }
19541                        pw.print("  AppOp Permission ");
19542                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19543                        pw.println(":");
19544                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19545                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19546                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19547                        }
19548                    }
19549                }
19550            }
19551
19552            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19553                boolean printedSomething = false;
19554                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19555                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19556                        continue;
19557                    }
19558                    if (!printedSomething) {
19559                        if (dumpState.onTitlePrinted())
19560                            pw.println();
19561                        pw.println("Registered ContentProviders:");
19562                        printedSomething = true;
19563                    }
19564                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19565                    pw.print("    "); pw.println(p.toString());
19566                }
19567                printedSomething = false;
19568                for (Map.Entry<String, PackageParser.Provider> entry :
19569                        mProvidersByAuthority.entrySet()) {
19570                    PackageParser.Provider p = entry.getValue();
19571                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19572                        continue;
19573                    }
19574                    if (!printedSomething) {
19575                        if (dumpState.onTitlePrinted())
19576                            pw.println();
19577                        pw.println("ContentProvider Authorities:");
19578                        printedSomething = true;
19579                    }
19580                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19581                    pw.print("    "); pw.println(p.toString());
19582                    if (p.info != null && p.info.applicationInfo != null) {
19583                        final String appInfo = p.info.applicationInfo.toString();
19584                        pw.print("      applicationInfo="); pw.println(appInfo);
19585                    }
19586                }
19587            }
19588
19589            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19590                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19591            }
19592
19593            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19594                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19595            }
19596
19597            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19598                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19599            }
19600
19601            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19602                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19603            }
19604
19605            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19606                // XXX should handle packageName != null by dumping only install data that
19607                // the given package is involved with.
19608                if (dumpState.onTitlePrinted()) pw.println();
19609                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19610            }
19611
19612            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19613                // XXX should handle packageName != null by dumping only install data that
19614                // the given package is involved with.
19615                if (dumpState.onTitlePrinted()) pw.println();
19616
19617                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19618                ipw.println();
19619                ipw.println("Frozen packages:");
19620                ipw.increaseIndent();
19621                if (mFrozenPackages.size() == 0) {
19622                    ipw.println("(none)");
19623                } else {
19624                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19625                        ipw.println(mFrozenPackages.valueAt(i));
19626                    }
19627                }
19628                ipw.decreaseIndent();
19629            }
19630
19631            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19632                if (dumpState.onTitlePrinted()) pw.println();
19633                dumpDexoptStateLPr(pw, packageName);
19634            }
19635
19636            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19637                if (dumpState.onTitlePrinted()) pw.println();
19638                dumpCompilerStatsLPr(pw, packageName);
19639            }
19640
19641            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19642                if (dumpState.onTitlePrinted()) pw.println();
19643                mSettings.dumpReadMessagesLPr(pw, dumpState);
19644
19645                pw.println();
19646                pw.println("Package warning messages:");
19647                BufferedReader in = null;
19648                String line = null;
19649                try {
19650                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19651                    while ((line = in.readLine()) != null) {
19652                        if (line.contains("ignored: updated version")) continue;
19653                        pw.println(line);
19654                    }
19655                } catch (IOException ignored) {
19656                } finally {
19657                    IoUtils.closeQuietly(in);
19658                }
19659            }
19660
19661            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19662                BufferedReader in = null;
19663                String line = null;
19664                try {
19665                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19666                    while ((line = in.readLine()) != null) {
19667                        if (line.contains("ignored: updated version")) continue;
19668                        pw.print("msg,");
19669                        pw.println(line);
19670                    }
19671                } catch (IOException ignored) {
19672                } finally {
19673                    IoUtils.closeQuietly(in);
19674                }
19675            }
19676        }
19677    }
19678
19679    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19680        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19681        ipw.println();
19682        ipw.println("Dexopt state:");
19683        ipw.increaseIndent();
19684        Collection<PackageParser.Package> packages = null;
19685        if (packageName != null) {
19686            PackageParser.Package targetPackage = mPackages.get(packageName);
19687            if (targetPackage != null) {
19688                packages = Collections.singletonList(targetPackage);
19689            } else {
19690                ipw.println("Unable to find package: " + packageName);
19691                return;
19692            }
19693        } else {
19694            packages = mPackages.values();
19695        }
19696
19697        for (PackageParser.Package pkg : packages) {
19698            ipw.println("[" + pkg.packageName + "]");
19699            ipw.increaseIndent();
19700            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19701            ipw.decreaseIndent();
19702        }
19703    }
19704
19705    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19706        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19707        ipw.println();
19708        ipw.println("Compiler stats:");
19709        ipw.increaseIndent();
19710        Collection<PackageParser.Package> packages = null;
19711        if (packageName != null) {
19712            PackageParser.Package targetPackage = mPackages.get(packageName);
19713            if (targetPackage != null) {
19714                packages = Collections.singletonList(targetPackage);
19715            } else {
19716                ipw.println("Unable to find package: " + packageName);
19717                return;
19718            }
19719        } else {
19720            packages = mPackages.values();
19721        }
19722
19723        for (PackageParser.Package pkg : packages) {
19724            ipw.println("[" + pkg.packageName + "]");
19725            ipw.increaseIndent();
19726
19727            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19728            if (stats == null) {
19729                ipw.println("(No recorded stats)");
19730            } else {
19731                stats.dump(ipw);
19732            }
19733            ipw.decreaseIndent();
19734        }
19735    }
19736
19737    private String dumpDomainString(String packageName) {
19738        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19739                .getList();
19740        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19741
19742        ArraySet<String> result = new ArraySet<>();
19743        if (iviList.size() > 0) {
19744            for (IntentFilterVerificationInfo ivi : iviList) {
19745                for (String host : ivi.getDomains()) {
19746                    result.add(host);
19747                }
19748            }
19749        }
19750        if (filters != null && filters.size() > 0) {
19751            for (IntentFilter filter : filters) {
19752                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19753                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19754                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19755                    result.addAll(filter.getHostsList());
19756                }
19757            }
19758        }
19759
19760        StringBuilder sb = new StringBuilder(result.size() * 16);
19761        for (String domain : result) {
19762            if (sb.length() > 0) sb.append(" ");
19763            sb.append(domain);
19764        }
19765        return sb.toString();
19766    }
19767
19768    // ------- apps on sdcard specific code -------
19769    static final boolean DEBUG_SD_INSTALL = false;
19770
19771    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19772
19773    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19774
19775    private boolean mMediaMounted = false;
19776
19777    static String getEncryptKey() {
19778        try {
19779            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19780                    SD_ENCRYPTION_KEYSTORE_NAME);
19781            if (sdEncKey == null) {
19782                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19783                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19784                if (sdEncKey == null) {
19785                    Slog.e(TAG, "Failed to create encryption keys");
19786                    return null;
19787                }
19788            }
19789            return sdEncKey;
19790        } catch (NoSuchAlgorithmException nsae) {
19791            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19792            return null;
19793        } catch (IOException ioe) {
19794            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19795            return null;
19796        }
19797    }
19798
19799    /*
19800     * Update media status on PackageManager.
19801     */
19802    @Override
19803    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19804        int callingUid = Binder.getCallingUid();
19805        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19806            throw new SecurityException("Media status can only be updated by the system");
19807        }
19808        // reader; this apparently protects mMediaMounted, but should probably
19809        // be a different lock in that case.
19810        synchronized (mPackages) {
19811            Log.i(TAG, "Updating external media status from "
19812                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19813                    + (mediaStatus ? "mounted" : "unmounted"));
19814            if (DEBUG_SD_INSTALL)
19815                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19816                        + ", mMediaMounted=" + mMediaMounted);
19817            if (mediaStatus == mMediaMounted) {
19818                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19819                        : 0, -1);
19820                mHandler.sendMessage(msg);
19821                return;
19822            }
19823            mMediaMounted = mediaStatus;
19824        }
19825        // Queue up an async operation since the package installation may take a
19826        // little while.
19827        mHandler.post(new Runnable() {
19828            public void run() {
19829                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19830            }
19831        });
19832    }
19833
19834    /**
19835     * Called by StorageManagerService when the initial ASECs to scan are available.
19836     * Should block until all the ASEC containers are finished being scanned.
19837     */
19838    public void scanAvailableAsecs() {
19839        updateExternalMediaStatusInner(true, false, false);
19840    }
19841
19842    /*
19843     * Collect information of applications on external media, map them against
19844     * existing containers and update information based on current mount status.
19845     * Please note that we always have to report status if reportStatus has been
19846     * set to true especially when unloading packages.
19847     */
19848    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19849            boolean externalStorage) {
19850        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19851        int[] uidArr = EmptyArray.INT;
19852
19853        final String[] list = PackageHelper.getSecureContainerList();
19854        if (ArrayUtils.isEmpty(list)) {
19855            Log.i(TAG, "No secure containers found");
19856        } else {
19857            // Process list of secure containers and categorize them
19858            // as active or stale based on their package internal state.
19859
19860            // reader
19861            synchronized (mPackages) {
19862                for (String cid : list) {
19863                    // Leave stages untouched for now; installer service owns them
19864                    if (PackageInstallerService.isStageName(cid)) continue;
19865
19866                    if (DEBUG_SD_INSTALL)
19867                        Log.i(TAG, "Processing container " + cid);
19868                    String pkgName = getAsecPackageName(cid);
19869                    if (pkgName == null) {
19870                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19871                        continue;
19872                    }
19873                    if (DEBUG_SD_INSTALL)
19874                        Log.i(TAG, "Looking for pkg : " + pkgName);
19875
19876                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19877                    if (ps == null) {
19878                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19879                        continue;
19880                    }
19881
19882                    /*
19883                     * Skip packages that are not external if we're unmounting
19884                     * external storage.
19885                     */
19886                    if (externalStorage && !isMounted && !isExternal(ps)) {
19887                        continue;
19888                    }
19889
19890                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19891                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19892                    // The package status is changed only if the code path
19893                    // matches between settings and the container id.
19894                    if (ps.codePathString != null
19895                            && ps.codePathString.startsWith(args.getCodePath())) {
19896                        if (DEBUG_SD_INSTALL) {
19897                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19898                                    + " at code path: " + ps.codePathString);
19899                        }
19900
19901                        // We do have a valid package installed on sdcard
19902                        processCids.put(args, ps.codePathString);
19903                        final int uid = ps.appId;
19904                        if (uid != -1) {
19905                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19906                        }
19907                    } else {
19908                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19909                                + ps.codePathString);
19910                    }
19911                }
19912            }
19913
19914            Arrays.sort(uidArr);
19915        }
19916
19917        // Process packages with valid entries.
19918        if (isMounted) {
19919            if (DEBUG_SD_INSTALL)
19920                Log.i(TAG, "Loading packages");
19921            loadMediaPackages(processCids, uidArr, externalStorage);
19922            startCleaningPackages();
19923            mInstallerService.onSecureContainersAvailable();
19924        } else {
19925            if (DEBUG_SD_INSTALL)
19926                Log.i(TAG, "Unloading packages");
19927            unloadMediaPackages(processCids, uidArr, reportStatus);
19928        }
19929    }
19930
19931    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19932            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19933        final int size = infos.size();
19934        final String[] packageNames = new String[size];
19935        final int[] packageUids = new int[size];
19936        for (int i = 0; i < size; i++) {
19937            final ApplicationInfo info = infos.get(i);
19938            packageNames[i] = info.packageName;
19939            packageUids[i] = info.uid;
19940        }
19941        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19942                finishedReceiver);
19943    }
19944
19945    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19946            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19947        sendResourcesChangedBroadcast(mediaStatus, replacing,
19948                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19949    }
19950
19951    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19952            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19953        int size = pkgList.length;
19954        if (size > 0) {
19955            // Send broadcasts here
19956            Bundle extras = new Bundle();
19957            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19958            if (uidArr != null) {
19959                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19960            }
19961            if (replacing) {
19962                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19963            }
19964            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19965                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19966            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19967        }
19968    }
19969
19970   /*
19971     * Look at potentially valid container ids from processCids If package
19972     * information doesn't match the one on record or package scanning fails,
19973     * the cid is added to list of removeCids. We currently don't delete stale
19974     * containers.
19975     */
19976    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19977            boolean externalStorage) {
19978        ArrayList<String> pkgList = new ArrayList<String>();
19979        Set<AsecInstallArgs> keys = processCids.keySet();
19980
19981        for (AsecInstallArgs args : keys) {
19982            String codePath = processCids.get(args);
19983            if (DEBUG_SD_INSTALL)
19984                Log.i(TAG, "Loading container : " + args.cid);
19985            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19986            try {
19987                // Make sure there are no container errors first.
19988                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19989                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19990                            + " when installing from sdcard");
19991                    continue;
19992                }
19993                // Check code path here.
19994                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19995                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19996                            + " does not match one in settings " + codePath);
19997                    continue;
19998                }
19999                // Parse package
20000                int parseFlags = mDefParseFlags;
20001                if (args.isExternalAsec()) {
20002                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20003                }
20004                if (args.isFwdLocked()) {
20005                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20006                }
20007
20008                synchronized (mInstallLock) {
20009                    PackageParser.Package pkg = null;
20010                    try {
20011                        // Sadly we don't know the package name yet to freeze it
20012                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20013                                SCAN_IGNORE_FROZEN, 0, null);
20014                    } catch (PackageManagerException e) {
20015                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20016                    }
20017                    // Scan the package
20018                    if (pkg != null) {
20019                        /*
20020                         * TODO why is the lock being held? doPostInstall is
20021                         * called in other places without the lock. This needs
20022                         * to be straightened out.
20023                         */
20024                        // writer
20025                        synchronized (mPackages) {
20026                            retCode = PackageManager.INSTALL_SUCCEEDED;
20027                            pkgList.add(pkg.packageName);
20028                            // Post process args
20029                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20030                                    pkg.applicationInfo.uid);
20031                        }
20032                    } else {
20033                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20034                    }
20035                }
20036
20037            } finally {
20038                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20039                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20040                }
20041            }
20042        }
20043        // writer
20044        synchronized (mPackages) {
20045            // If the platform SDK has changed since the last time we booted,
20046            // we need to re-grant app permission to catch any new ones that
20047            // appear. This is really a hack, and means that apps can in some
20048            // cases get permissions that the user didn't initially explicitly
20049            // allow... it would be nice to have some better way to handle
20050            // this situation.
20051            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20052                    : mSettings.getInternalVersion();
20053            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20054                    : StorageManager.UUID_PRIVATE_INTERNAL;
20055
20056            int updateFlags = UPDATE_PERMISSIONS_ALL;
20057            if (ver.sdkVersion != mSdkVersion) {
20058                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20059                        + mSdkVersion + "; regranting permissions for external");
20060                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20061            }
20062            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20063
20064            // Yay, everything is now upgraded
20065            ver.forceCurrent();
20066
20067            // can downgrade to reader
20068            // Persist settings
20069            mSettings.writeLPr();
20070        }
20071        // Send a broadcast to let everyone know we are done processing
20072        if (pkgList.size() > 0) {
20073            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20074        }
20075    }
20076
20077   /*
20078     * Utility method to unload a list of specified containers
20079     */
20080    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
20081        // Just unmount all valid containers.
20082        for (AsecInstallArgs arg : cidArgs) {
20083            synchronized (mInstallLock) {
20084                arg.doPostDeleteLI(false);
20085           }
20086       }
20087   }
20088
20089    /*
20090     * Unload packages mounted on external media. This involves deleting package
20091     * data from internal structures, sending broadcasts about disabled packages,
20092     * gc'ing to free up references, unmounting all secure containers
20093     * corresponding to packages on external media, and posting a
20094     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
20095     * that we always have to post this message if status has been requested no
20096     * matter what.
20097     */
20098    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
20099            final boolean reportStatus) {
20100        if (DEBUG_SD_INSTALL)
20101            Log.i(TAG, "unloading media packages");
20102        ArrayList<String> pkgList = new ArrayList<String>();
20103        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
20104        final Set<AsecInstallArgs> keys = processCids.keySet();
20105        for (AsecInstallArgs args : keys) {
20106            String pkgName = args.getPackageName();
20107            if (DEBUG_SD_INSTALL)
20108                Log.i(TAG, "Trying to unload pkg : " + pkgName);
20109            // Delete package internally
20110            PackageRemovedInfo outInfo = new PackageRemovedInfo();
20111            synchronized (mInstallLock) {
20112                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20113                final boolean res;
20114                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
20115                        "unloadMediaPackages")) {
20116                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
20117                            null);
20118                }
20119                if (res) {
20120                    pkgList.add(pkgName);
20121                } else {
20122                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
20123                    failedList.add(args);
20124                }
20125            }
20126        }
20127
20128        // reader
20129        synchronized (mPackages) {
20130            // We didn't update the settings after removing each package;
20131            // write them now for all packages.
20132            mSettings.writeLPr();
20133        }
20134
20135        // We have to absolutely send UPDATED_MEDIA_STATUS only
20136        // after confirming that all the receivers processed the ordered
20137        // broadcast when packages get disabled, force a gc to clean things up.
20138        // and unload all the containers.
20139        if (pkgList.size() > 0) {
20140            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
20141                    new IIntentReceiver.Stub() {
20142                public void performReceive(Intent intent, int resultCode, String data,
20143                        Bundle extras, boolean ordered, boolean sticky,
20144                        int sendingUser) throws RemoteException {
20145                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
20146                            reportStatus ? 1 : 0, 1, keys);
20147                    mHandler.sendMessage(msg);
20148                }
20149            });
20150        } else {
20151            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
20152                    keys);
20153            mHandler.sendMessage(msg);
20154        }
20155    }
20156
20157    private void loadPrivatePackages(final VolumeInfo vol) {
20158        mHandler.post(new Runnable() {
20159            @Override
20160            public void run() {
20161                loadPrivatePackagesInner(vol);
20162            }
20163        });
20164    }
20165
20166    private void loadPrivatePackagesInner(VolumeInfo vol) {
20167        final String volumeUuid = vol.fsUuid;
20168        if (TextUtils.isEmpty(volumeUuid)) {
20169            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20170            return;
20171        }
20172
20173        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20174        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20175        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20176
20177        final VersionInfo ver;
20178        final List<PackageSetting> packages;
20179        synchronized (mPackages) {
20180            ver = mSettings.findOrCreateVersion(volumeUuid);
20181            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20182        }
20183
20184        for (PackageSetting ps : packages) {
20185            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20186            synchronized (mInstallLock) {
20187                final PackageParser.Package pkg;
20188                try {
20189                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20190                    loaded.add(pkg.applicationInfo);
20191
20192                } catch (PackageManagerException e) {
20193                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20194                }
20195
20196                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20197                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20198                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20199                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20200                }
20201            }
20202        }
20203
20204        // Reconcile app data for all started/unlocked users
20205        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20206        final UserManager um = mContext.getSystemService(UserManager.class);
20207        UserManagerInternal umInternal = getUserManagerInternal();
20208        for (UserInfo user : um.getUsers()) {
20209            final int flags;
20210            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20211                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20212            } else if (umInternal.isUserRunning(user.id)) {
20213                flags = StorageManager.FLAG_STORAGE_DE;
20214            } else {
20215                continue;
20216            }
20217
20218            try {
20219                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20220                synchronized (mInstallLock) {
20221                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20222                }
20223            } catch (IllegalStateException e) {
20224                // Device was probably ejected, and we'll process that event momentarily
20225                Slog.w(TAG, "Failed to prepare storage: " + e);
20226            }
20227        }
20228
20229        synchronized (mPackages) {
20230            int updateFlags = UPDATE_PERMISSIONS_ALL;
20231            if (ver.sdkVersion != mSdkVersion) {
20232                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20233                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20234                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20235            }
20236            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20237
20238            // Yay, everything is now upgraded
20239            ver.forceCurrent();
20240
20241            mSettings.writeLPr();
20242        }
20243
20244        for (PackageFreezer freezer : freezers) {
20245            freezer.close();
20246        }
20247
20248        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20249        sendResourcesChangedBroadcast(true, false, loaded, null);
20250    }
20251
20252    private void unloadPrivatePackages(final VolumeInfo vol) {
20253        mHandler.post(new Runnable() {
20254            @Override
20255            public void run() {
20256                unloadPrivatePackagesInner(vol);
20257            }
20258        });
20259    }
20260
20261    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20262        final String volumeUuid = vol.fsUuid;
20263        if (TextUtils.isEmpty(volumeUuid)) {
20264            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20265            return;
20266        }
20267
20268        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20269        synchronized (mInstallLock) {
20270        synchronized (mPackages) {
20271            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20272            for (PackageSetting ps : packages) {
20273                if (ps.pkg == null) continue;
20274
20275                final ApplicationInfo info = ps.pkg.applicationInfo;
20276                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20277                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20278
20279                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20280                        "unloadPrivatePackagesInner")) {
20281                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20282                            false, null)) {
20283                        unloaded.add(info);
20284                    } else {
20285                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20286                    }
20287                }
20288
20289                // Try very hard to release any references to this package
20290                // so we don't risk the system server being killed due to
20291                // open FDs
20292                AttributeCache.instance().removePackage(ps.name);
20293            }
20294
20295            mSettings.writeLPr();
20296        }
20297        }
20298
20299        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20300        sendResourcesChangedBroadcast(false, false, unloaded, null);
20301
20302        // Try very hard to release any references to this path so we don't risk
20303        // the system server being killed due to open FDs
20304        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20305
20306        for (int i = 0; i < 3; i++) {
20307            System.gc();
20308            System.runFinalization();
20309        }
20310    }
20311
20312    /**
20313     * Prepare storage areas for given user on all mounted devices.
20314     */
20315    void prepareUserData(int userId, int userSerial, int flags) {
20316        synchronized (mInstallLock) {
20317            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20318            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20319                final String volumeUuid = vol.getFsUuid();
20320                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20321            }
20322        }
20323    }
20324
20325    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20326            boolean allowRecover) {
20327        // Prepare storage and verify that serial numbers are consistent; if
20328        // there's a mismatch we need to destroy to avoid leaking data
20329        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20330        try {
20331            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20332
20333            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20334                UserManagerService.enforceSerialNumber(
20335                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20336                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20337                    UserManagerService.enforceSerialNumber(
20338                            Environment.getDataSystemDeDirectory(userId), userSerial);
20339                }
20340            }
20341            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20342                UserManagerService.enforceSerialNumber(
20343                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20344                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20345                    UserManagerService.enforceSerialNumber(
20346                            Environment.getDataSystemCeDirectory(userId), userSerial);
20347                }
20348            }
20349
20350            synchronized (mInstallLock) {
20351                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20352            }
20353        } catch (Exception e) {
20354            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20355                    + " because we failed to prepare: " + e);
20356            destroyUserDataLI(volumeUuid, userId,
20357                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20358
20359            if (allowRecover) {
20360                // Try one last time; if we fail again we're really in trouble
20361                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20362            }
20363        }
20364    }
20365
20366    /**
20367     * Destroy storage areas for given user on all mounted devices.
20368     */
20369    void destroyUserData(int userId, int flags) {
20370        synchronized (mInstallLock) {
20371            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20372            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20373                final String volumeUuid = vol.getFsUuid();
20374                destroyUserDataLI(volumeUuid, userId, flags);
20375            }
20376        }
20377    }
20378
20379    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20380        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20381        try {
20382            // Clean up app data, profile data, and media data
20383            mInstaller.destroyUserData(volumeUuid, userId, flags);
20384
20385            // Clean up system data
20386            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20387                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20388                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20389                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20390                }
20391                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20392                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20393                }
20394            }
20395
20396            // Data with special labels is now gone, so finish the job
20397            storage.destroyUserStorage(volumeUuid, userId, flags);
20398
20399        } catch (Exception e) {
20400            logCriticalInfo(Log.WARN,
20401                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20402        }
20403    }
20404
20405    /**
20406     * Examine all users present on given mounted volume, and destroy data
20407     * belonging to users that are no longer valid, or whose user ID has been
20408     * recycled.
20409     */
20410    private void reconcileUsers(String volumeUuid) {
20411        final List<File> files = new ArrayList<>();
20412        Collections.addAll(files, FileUtils
20413                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20414        Collections.addAll(files, FileUtils
20415                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20416        Collections.addAll(files, FileUtils
20417                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20418        Collections.addAll(files, FileUtils
20419                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20420        for (File file : files) {
20421            if (!file.isDirectory()) continue;
20422
20423            final int userId;
20424            final UserInfo info;
20425            try {
20426                userId = Integer.parseInt(file.getName());
20427                info = sUserManager.getUserInfo(userId);
20428            } catch (NumberFormatException e) {
20429                Slog.w(TAG, "Invalid user directory " + file);
20430                continue;
20431            }
20432
20433            boolean destroyUser = false;
20434            if (info == null) {
20435                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20436                        + " because no matching user was found");
20437                destroyUser = true;
20438            } else if (!mOnlyCore) {
20439                try {
20440                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20441                } catch (IOException e) {
20442                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20443                            + " because we failed to enforce serial number: " + e);
20444                    destroyUser = true;
20445                }
20446            }
20447
20448            if (destroyUser) {
20449                synchronized (mInstallLock) {
20450                    destroyUserDataLI(volumeUuid, userId,
20451                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20452                }
20453            }
20454        }
20455    }
20456
20457    private void assertPackageKnown(String volumeUuid, String packageName)
20458            throws PackageManagerException {
20459        synchronized (mPackages) {
20460            // Normalize package name to handle renamed packages
20461            packageName = normalizePackageNameLPr(packageName);
20462
20463            final PackageSetting ps = mSettings.mPackages.get(packageName);
20464            if (ps == null) {
20465                throw new PackageManagerException("Package " + packageName + " is unknown");
20466            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20467                throw new PackageManagerException(
20468                        "Package " + packageName + " found on unknown volume " + volumeUuid
20469                                + "; expected volume " + ps.volumeUuid);
20470            }
20471        }
20472    }
20473
20474    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20475            throws PackageManagerException {
20476        synchronized (mPackages) {
20477            // Normalize package name to handle renamed packages
20478            packageName = normalizePackageNameLPr(packageName);
20479
20480            final PackageSetting ps = mSettings.mPackages.get(packageName);
20481            if (ps == null) {
20482                throw new PackageManagerException("Package " + packageName + " is unknown");
20483            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20484                throw new PackageManagerException(
20485                        "Package " + packageName + " found on unknown volume " + volumeUuid
20486                                + "; expected volume " + ps.volumeUuid);
20487            } else if (!ps.getInstalled(userId)) {
20488                throw new PackageManagerException(
20489                        "Package " + packageName + " not installed for user " + userId);
20490            }
20491        }
20492    }
20493
20494    /**
20495     * Examine all apps present on given mounted volume, and destroy apps that
20496     * aren't expected, either due to uninstallation or reinstallation on
20497     * another volume.
20498     */
20499    private void reconcileApps(String volumeUuid) {
20500        final File[] files = FileUtils
20501                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20502        for (File file : files) {
20503            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20504                    && !PackageInstallerService.isStageName(file.getName());
20505            if (!isPackage) {
20506                // Ignore entries which are not packages
20507                continue;
20508            }
20509
20510            try {
20511                final PackageLite pkg = PackageParser.parsePackageLite(file,
20512                        PackageParser.PARSE_MUST_BE_APK);
20513                assertPackageKnown(volumeUuid, pkg.packageName);
20514
20515            } catch (PackageParserException | PackageManagerException e) {
20516                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20517                synchronized (mInstallLock) {
20518                    removeCodePathLI(file);
20519                }
20520            }
20521        }
20522    }
20523
20524    /**
20525     * Reconcile all app data for the given user.
20526     * <p>
20527     * Verifies that directories exist and that ownership and labeling is
20528     * correct for all installed apps on all mounted volumes.
20529     */
20530    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20531        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20532        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20533            final String volumeUuid = vol.getFsUuid();
20534            synchronized (mInstallLock) {
20535                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20536            }
20537        }
20538    }
20539
20540    /**
20541     * Reconcile all app data on given mounted volume.
20542     * <p>
20543     * Destroys app data that isn't expected, either due to uninstallation or
20544     * reinstallation on another volume.
20545     * <p>
20546     * Verifies that directories exist and that ownership and labeling is
20547     * correct for all installed apps.
20548     */
20549    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20550            boolean migrateAppData) {
20551        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20552                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20553
20554        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20555        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20556
20557        // First look for stale data that doesn't belong, and check if things
20558        // have changed since we did our last restorecon
20559        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20560            if (StorageManager.isFileEncryptedNativeOrEmulated()
20561                    && !StorageManager.isUserKeyUnlocked(userId)) {
20562                throw new RuntimeException(
20563                        "Yikes, someone asked us to reconcile CE storage while " + userId
20564                                + " was still locked; this would have caused massive data loss!");
20565            }
20566
20567            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20568            for (File file : files) {
20569                final String packageName = file.getName();
20570                try {
20571                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20572                } catch (PackageManagerException e) {
20573                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20574                    try {
20575                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20576                                StorageManager.FLAG_STORAGE_CE, 0);
20577                    } catch (InstallerException e2) {
20578                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20579                    }
20580                }
20581            }
20582        }
20583        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20584            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20585            for (File file : files) {
20586                final String packageName = file.getName();
20587                try {
20588                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20589                } catch (PackageManagerException e) {
20590                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20591                    try {
20592                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20593                                StorageManager.FLAG_STORAGE_DE, 0);
20594                    } catch (InstallerException e2) {
20595                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20596                    }
20597                }
20598            }
20599        }
20600
20601        // Ensure that data directories are ready to roll for all packages
20602        // installed for this volume and user
20603        final List<PackageSetting> packages;
20604        synchronized (mPackages) {
20605            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20606        }
20607        int preparedCount = 0;
20608        for (PackageSetting ps : packages) {
20609            final String packageName = ps.name;
20610            if (ps.pkg == null) {
20611                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20612                // TODO: might be due to legacy ASEC apps; we should circle back
20613                // and reconcile again once they're scanned
20614                continue;
20615            }
20616
20617            if (ps.getInstalled(userId)) {
20618                prepareAppDataLIF(ps.pkg, userId, flags);
20619
20620                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20621                    // We may have just shuffled around app data directories, so
20622                    // prepare them one more time
20623                    prepareAppDataLIF(ps.pkg, userId, flags);
20624                }
20625
20626                preparedCount++;
20627            }
20628        }
20629
20630        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20631    }
20632
20633    /**
20634     * Prepare app data for the given app just after it was installed or
20635     * upgraded. This method carefully only touches users that it's installed
20636     * for, and it forces a restorecon to handle any seinfo changes.
20637     * <p>
20638     * Verifies that directories exist and that ownership and labeling is
20639     * correct for all installed apps. If there is an ownership mismatch, it
20640     * will try recovering system apps by wiping data; third-party app data is
20641     * left intact.
20642     * <p>
20643     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20644     */
20645    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20646        final PackageSetting ps;
20647        synchronized (mPackages) {
20648            ps = mSettings.mPackages.get(pkg.packageName);
20649            mSettings.writeKernelMappingLPr(ps);
20650        }
20651
20652        final UserManager um = mContext.getSystemService(UserManager.class);
20653        UserManagerInternal umInternal = getUserManagerInternal();
20654        for (UserInfo user : um.getUsers()) {
20655            final int flags;
20656            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20657                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20658            } else if (umInternal.isUserRunning(user.id)) {
20659                flags = StorageManager.FLAG_STORAGE_DE;
20660            } else {
20661                continue;
20662            }
20663
20664            if (ps.getInstalled(user.id)) {
20665                // TODO: when user data is locked, mark that we're still dirty
20666                prepareAppDataLIF(pkg, user.id, flags);
20667            }
20668        }
20669    }
20670
20671    /**
20672     * Prepare app data for the given app.
20673     * <p>
20674     * Verifies that directories exist and that ownership and labeling is
20675     * correct for all installed apps. If there is an ownership mismatch, this
20676     * will try recovering system apps by wiping data; third-party app data is
20677     * left intact.
20678     */
20679    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20680        if (pkg == null) {
20681            Slog.wtf(TAG, "Package was null!", new Throwable());
20682            return;
20683        }
20684        prepareAppDataLeafLIF(pkg, userId, flags);
20685        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20686        for (int i = 0; i < childCount; i++) {
20687            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20688        }
20689    }
20690
20691    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20692        if (DEBUG_APP_DATA) {
20693            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20694                    + Integer.toHexString(flags));
20695        }
20696
20697        final String volumeUuid = pkg.volumeUuid;
20698        final String packageName = pkg.packageName;
20699        final ApplicationInfo app = pkg.applicationInfo;
20700        final int appId = UserHandle.getAppId(app.uid);
20701
20702        Preconditions.checkNotNull(app.seinfo);
20703
20704        long ceDataInode = -1;
20705        try {
20706            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20707                    appId, app.seinfo, app.targetSdkVersion);
20708        } catch (InstallerException e) {
20709            if (app.isSystemApp()) {
20710                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20711                        + ", but trying to recover: " + e);
20712                destroyAppDataLeafLIF(pkg, userId, flags);
20713                try {
20714                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20715                            appId, app.seinfo, app.targetSdkVersion);
20716                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20717                } catch (InstallerException e2) {
20718                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20719                }
20720            } else {
20721                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20722            }
20723        }
20724
20725        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20726            // TODO: mark this structure as dirty so we persist it!
20727            synchronized (mPackages) {
20728                final PackageSetting ps = mSettings.mPackages.get(packageName);
20729                if (ps != null) {
20730                    ps.setCeDataInode(ceDataInode, userId);
20731                }
20732            }
20733        }
20734
20735        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20736    }
20737
20738    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20739        if (pkg == null) {
20740            Slog.wtf(TAG, "Package was null!", new Throwable());
20741            return;
20742        }
20743        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20744        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20745        for (int i = 0; i < childCount; i++) {
20746            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20747        }
20748    }
20749
20750    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20751        final String volumeUuid = pkg.volumeUuid;
20752        final String packageName = pkg.packageName;
20753        final ApplicationInfo app = pkg.applicationInfo;
20754
20755        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20756            // Create a native library symlink only if we have native libraries
20757            // and if the native libraries are 32 bit libraries. We do not provide
20758            // this symlink for 64 bit libraries.
20759            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20760                final String nativeLibPath = app.nativeLibraryDir;
20761                try {
20762                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20763                            nativeLibPath, userId);
20764                } catch (InstallerException e) {
20765                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20766                }
20767            }
20768        }
20769    }
20770
20771    /**
20772     * For system apps on non-FBE devices, this method migrates any existing
20773     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20774     * requested by the app.
20775     */
20776    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20777        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20778                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20779            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20780                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20781            try {
20782                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20783                        storageTarget);
20784            } catch (InstallerException e) {
20785                logCriticalInfo(Log.WARN,
20786                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20787            }
20788            return true;
20789        } else {
20790            return false;
20791        }
20792    }
20793
20794    public PackageFreezer freezePackage(String packageName, String killReason) {
20795        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20796    }
20797
20798    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20799        return new PackageFreezer(packageName, userId, killReason);
20800    }
20801
20802    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20803            String killReason) {
20804        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20805    }
20806
20807    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20808            String killReason) {
20809        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20810            return new PackageFreezer();
20811        } else {
20812            return freezePackage(packageName, userId, killReason);
20813        }
20814    }
20815
20816    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20817            String killReason) {
20818        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20819    }
20820
20821    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20822            String killReason) {
20823        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20824            return new PackageFreezer();
20825        } else {
20826            return freezePackage(packageName, userId, killReason);
20827        }
20828    }
20829
20830    /**
20831     * Class that freezes and kills the given package upon creation, and
20832     * unfreezes it upon closing. This is typically used when doing surgery on
20833     * app code/data to prevent the app from running while you're working.
20834     */
20835    private class PackageFreezer implements AutoCloseable {
20836        private final String mPackageName;
20837        private final PackageFreezer[] mChildren;
20838
20839        private final boolean mWeFroze;
20840
20841        private final AtomicBoolean mClosed = new AtomicBoolean();
20842        private final CloseGuard mCloseGuard = CloseGuard.get();
20843
20844        /**
20845         * Create and return a stub freezer that doesn't actually do anything,
20846         * typically used when someone requested
20847         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20848         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20849         */
20850        public PackageFreezer() {
20851            mPackageName = null;
20852            mChildren = null;
20853            mWeFroze = false;
20854            mCloseGuard.open("close");
20855        }
20856
20857        public PackageFreezer(String packageName, int userId, String killReason) {
20858            synchronized (mPackages) {
20859                mPackageName = packageName;
20860                mWeFroze = mFrozenPackages.add(mPackageName);
20861
20862                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20863                if (ps != null) {
20864                    killApplication(ps.name, ps.appId, userId, killReason);
20865                }
20866
20867                final PackageParser.Package p = mPackages.get(packageName);
20868                if (p != null && p.childPackages != null) {
20869                    final int N = p.childPackages.size();
20870                    mChildren = new PackageFreezer[N];
20871                    for (int i = 0; i < N; i++) {
20872                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20873                                userId, killReason);
20874                    }
20875                } else {
20876                    mChildren = null;
20877                }
20878            }
20879            mCloseGuard.open("close");
20880        }
20881
20882        @Override
20883        protected void finalize() throws Throwable {
20884            try {
20885                mCloseGuard.warnIfOpen();
20886                close();
20887            } finally {
20888                super.finalize();
20889            }
20890        }
20891
20892        @Override
20893        public void close() {
20894            mCloseGuard.close();
20895            if (mClosed.compareAndSet(false, true)) {
20896                synchronized (mPackages) {
20897                    if (mWeFroze) {
20898                        mFrozenPackages.remove(mPackageName);
20899                    }
20900
20901                    if (mChildren != null) {
20902                        for (PackageFreezer freezer : mChildren) {
20903                            freezer.close();
20904                        }
20905                    }
20906                }
20907            }
20908        }
20909    }
20910
20911    /**
20912     * Verify that given package is currently frozen.
20913     */
20914    private void checkPackageFrozen(String packageName) {
20915        synchronized (mPackages) {
20916            if (!mFrozenPackages.contains(packageName)) {
20917                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20918            }
20919        }
20920    }
20921
20922    @Override
20923    public int movePackage(final String packageName, final String volumeUuid) {
20924        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20925
20926        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20927        final int moveId = mNextMoveId.getAndIncrement();
20928        mHandler.post(new Runnable() {
20929            @Override
20930            public void run() {
20931                try {
20932                    movePackageInternal(packageName, volumeUuid, moveId, user);
20933                } catch (PackageManagerException e) {
20934                    Slog.w(TAG, "Failed to move " + packageName, e);
20935                    mMoveCallbacks.notifyStatusChanged(moveId,
20936                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20937                }
20938            }
20939        });
20940        return moveId;
20941    }
20942
20943    private void movePackageInternal(final String packageName, final String volumeUuid,
20944            final int moveId, UserHandle user) throws PackageManagerException {
20945        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20946        final PackageManager pm = mContext.getPackageManager();
20947
20948        final boolean currentAsec;
20949        final String currentVolumeUuid;
20950        final File codeFile;
20951        final String installerPackageName;
20952        final String packageAbiOverride;
20953        final int appId;
20954        final String seinfo;
20955        final String label;
20956        final int targetSdkVersion;
20957        final PackageFreezer freezer;
20958        final int[] installedUserIds;
20959
20960        // reader
20961        synchronized (mPackages) {
20962            final PackageParser.Package pkg = mPackages.get(packageName);
20963            final PackageSetting ps = mSettings.mPackages.get(packageName);
20964            if (pkg == null || ps == null) {
20965                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20966            }
20967
20968            if (pkg.applicationInfo.isSystemApp()) {
20969                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20970                        "Cannot move system application");
20971            }
20972
20973            if (pkg.applicationInfo.isExternalAsec()) {
20974                currentAsec = true;
20975                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20976            } else if (pkg.applicationInfo.isForwardLocked()) {
20977                currentAsec = true;
20978                currentVolumeUuid = "forward_locked";
20979            } else {
20980                currentAsec = false;
20981                currentVolumeUuid = ps.volumeUuid;
20982
20983                final File probe = new File(pkg.codePath);
20984                final File probeOat = new File(probe, "oat");
20985                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20986                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20987                            "Move only supported for modern cluster style installs");
20988                }
20989            }
20990
20991            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20992                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20993                        "Package already moved to " + volumeUuid);
20994            }
20995            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20996                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20997                        "Device admin cannot be moved");
20998            }
20999
21000            if (mFrozenPackages.contains(packageName)) {
21001                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21002                        "Failed to move already frozen package");
21003            }
21004
21005            codeFile = new File(pkg.codePath);
21006            installerPackageName = ps.installerPackageName;
21007            packageAbiOverride = ps.cpuAbiOverrideString;
21008            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21009            seinfo = pkg.applicationInfo.seinfo;
21010            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21011            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21012            freezer = freezePackage(packageName, "movePackageInternal");
21013            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21014        }
21015
21016        final Bundle extras = new Bundle();
21017        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21018        extras.putString(Intent.EXTRA_TITLE, label);
21019        mMoveCallbacks.notifyCreated(moveId, extras);
21020
21021        int installFlags;
21022        final boolean moveCompleteApp;
21023        final File measurePath;
21024
21025        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21026            installFlags = INSTALL_INTERNAL;
21027            moveCompleteApp = !currentAsec;
21028            measurePath = Environment.getDataAppDirectory(volumeUuid);
21029        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21030            installFlags = INSTALL_EXTERNAL;
21031            moveCompleteApp = false;
21032            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21033        } else {
21034            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21035            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21036                    || !volume.isMountedWritable()) {
21037                freezer.close();
21038                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21039                        "Move location not mounted private volume");
21040            }
21041
21042            Preconditions.checkState(!currentAsec);
21043
21044            installFlags = INSTALL_INTERNAL;
21045            moveCompleteApp = true;
21046            measurePath = Environment.getDataAppDirectory(volumeUuid);
21047        }
21048
21049        final PackageStats stats = new PackageStats(null, -1);
21050        synchronized (mInstaller) {
21051            for (int userId : installedUserIds) {
21052                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21053                    freezer.close();
21054                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21055                            "Failed to measure package size");
21056                }
21057            }
21058        }
21059
21060        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21061                + stats.dataSize);
21062
21063        final long startFreeBytes = measurePath.getFreeSpace();
21064        final long sizeBytes;
21065        if (moveCompleteApp) {
21066            sizeBytes = stats.codeSize + stats.dataSize;
21067        } else {
21068            sizeBytes = stats.codeSize;
21069        }
21070
21071        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21072            freezer.close();
21073            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21074                    "Not enough free space to move");
21075        }
21076
21077        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21078
21079        final CountDownLatch installedLatch = new CountDownLatch(1);
21080        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21081            @Override
21082            public void onUserActionRequired(Intent intent) throws RemoteException {
21083                throw new IllegalStateException();
21084            }
21085
21086            @Override
21087            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21088                    Bundle extras) throws RemoteException {
21089                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21090                        + PackageManager.installStatusToString(returnCode, msg));
21091
21092                installedLatch.countDown();
21093                freezer.close();
21094
21095                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21096                switch (status) {
21097                    case PackageInstaller.STATUS_SUCCESS:
21098                        mMoveCallbacks.notifyStatusChanged(moveId,
21099                                PackageManager.MOVE_SUCCEEDED);
21100                        break;
21101                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21102                        mMoveCallbacks.notifyStatusChanged(moveId,
21103                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21104                        break;
21105                    default:
21106                        mMoveCallbacks.notifyStatusChanged(moveId,
21107                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21108                        break;
21109                }
21110            }
21111        };
21112
21113        final MoveInfo move;
21114        if (moveCompleteApp) {
21115            // Kick off a thread to report progress estimates
21116            new Thread() {
21117                @Override
21118                public void run() {
21119                    while (true) {
21120                        try {
21121                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21122                                break;
21123                            }
21124                        } catch (InterruptedException ignored) {
21125                        }
21126
21127                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
21128                        final int progress = 10 + (int) MathUtils.constrain(
21129                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21130                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21131                    }
21132                }
21133            }.start();
21134
21135            final String dataAppName = codeFile.getName();
21136            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21137                    dataAppName, appId, seinfo, targetSdkVersion);
21138        } else {
21139            move = null;
21140        }
21141
21142        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21143
21144        final Message msg = mHandler.obtainMessage(INIT_COPY);
21145        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21146        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21147                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21148                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21149                PackageManager.INSTALL_REASON_UNKNOWN);
21150        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21151        msg.obj = params;
21152
21153        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21154                System.identityHashCode(msg.obj));
21155        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21156                System.identityHashCode(msg.obj));
21157
21158        mHandler.sendMessage(msg);
21159    }
21160
21161    @Override
21162    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21163        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21164
21165        final int realMoveId = mNextMoveId.getAndIncrement();
21166        final Bundle extras = new Bundle();
21167        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21168        mMoveCallbacks.notifyCreated(realMoveId, extras);
21169
21170        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21171            @Override
21172            public void onCreated(int moveId, Bundle extras) {
21173                // Ignored
21174            }
21175
21176            @Override
21177            public void onStatusChanged(int moveId, int status, long estMillis) {
21178                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21179            }
21180        };
21181
21182        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21183        storage.setPrimaryStorageUuid(volumeUuid, callback);
21184        return realMoveId;
21185    }
21186
21187    @Override
21188    public int getMoveStatus(int moveId) {
21189        mContext.enforceCallingOrSelfPermission(
21190                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21191        return mMoveCallbacks.mLastStatus.get(moveId);
21192    }
21193
21194    @Override
21195    public void registerMoveCallback(IPackageMoveObserver callback) {
21196        mContext.enforceCallingOrSelfPermission(
21197                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21198        mMoveCallbacks.register(callback);
21199    }
21200
21201    @Override
21202    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21203        mContext.enforceCallingOrSelfPermission(
21204                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21205        mMoveCallbacks.unregister(callback);
21206    }
21207
21208    @Override
21209    public boolean setInstallLocation(int loc) {
21210        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21211                null);
21212        if (getInstallLocation() == loc) {
21213            return true;
21214        }
21215        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21216                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21217            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21218                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21219            return true;
21220        }
21221        return false;
21222   }
21223
21224    @Override
21225    public int getInstallLocation() {
21226        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21227                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21228                PackageHelper.APP_INSTALL_AUTO);
21229    }
21230
21231    /** Called by UserManagerService */
21232    void cleanUpUser(UserManagerService userManager, int userHandle) {
21233        synchronized (mPackages) {
21234            mDirtyUsers.remove(userHandle);
21235            mUserNeedsBadging.delete(userHandle);
21236            mSettings.removeUserLPw(userHandle);
21237            mPendingBroadcasts.remove(userHandle);
21238            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21239            removeUnusedPackagesLPw(userManager, userHandle);
21240        }
21241    }
21242
21243    /**
21244     * We're removing userHandle and would like to remove any downloaded packages
21245     * that are no longer in use by any other user.
21246     * @param userHandle the user being removed
21247     */
21248    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21249        final boolean DEBUG_CLEAN_APKS = false;
21250        int [] users = userManager.getUserIds();
21251        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21252        while (psit.hasNext()) {
21253            PackageSetting ps = psit.next();
21254            if (ps.pkg == null) {
21255                continue;
21256            }
21257            final String packageName = ps.pkg.packageName;
21258            // Skip over if system app
21259            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21260                continue;
21261            }
21262            if (DEBUG_CLEAN_APKS) {
21263                Slog.i(TAG, "Checking package " + packageName);
21264            }
21265            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21266            if (keep) {
21267                if (DEBUG_CLEAN_APKS) {
21268                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21269                }
21270            } else {
21271                for (int i = 0; i < users.length; i++) {
21272                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21273                        keep = true;
21274                        if (DEBUG_CLEAN_APKS) {
21275                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21276                                    + users[i]);
21277                        }
21278                        break;
21279                    }
21280                }
21281            }
21282            if (!keep) {
21283                if (DEBUG_CLEAN_APKS) {
21284                    Slog.i(TAG, "  Removing package " + packageName);
21285                }
21286                mHandler.post(new Runnable() {
21287                    public void run() {
21288                        deletePackageX(packageName, userHandle, 0);
21289                    } //end run
21290                });
21291            }
21292        }
21293    }
21294
21295    /** Called by UserManagerService */
21296    void createNewUser(int userId, String[] disallowedPackages) {
21297        synchronized (mInstallLock) {
21298            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21299        }
21300        synchronized (mPackages) {
21301            scheduleWritePackageRestrictionsLocked(userId);
21302            scheduleWritePackageListLocked(userId);
21303            applyFactoryDefaultBrowserLPw(userId);
21304            primeDomainVerificationsLPw(userId);
21305        }
21306    }
21307
21308    void onNewUserCreated(final int userId) {
21309        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21310        // If permission review for legacy apps is required, we represent
21311        // dagerous permissions for such apps as always granted runtime
21312        // permissions to keep per user flag state whether review is needed.
21313        // Hence, if a new user is added we have to propagate dangerous
21314        // permission grants for these legacy apps.
21315        if (mPermissionReviewRequired) {
21316            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21317                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21318        }
21319    }
21320
21321    @Override
21322    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21323        mContext.enforceCallingOrSelfPermission(
21324                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21325                "Only package verification agents can read the verifier device identity");
21326
21327        synchronized (mPackages) {
21328            return mSettings.getVerifierDeviceIdentityLPw();
21329        }
21330    }
21331
21332    @Override
21333    public void setPermissionEnforced(String permission, boolean enforced) {
21334        // TODO: Now that we no longer change GID for storage, this should to away.
21335        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21336                "setPermissionEnforced");
21337        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21338            synchronized (mPackages) {
21339                if (mSettings.mReadExternalStorageEnforced == null
21340                        || mSettings.mReadExternalStorageEnforced != enforced) {
21341                    mSettings.mReadExternalStorageEnforced = enforced;
21342                    mSettings.writeLPr();
21343                }
21344            }
21345            // kill any non-foreground processes so we restart them and
21346            // grant/revoke the GID.
21347            final IActivityManager am = ActivityManager.getService();
21348            if (am != null) {
21349                final long token = Binder.clearCallingIdentity();
21350                try {
21351                    am.killProcessesBelowForeground("setPermissionEnforcement");
21352                } catch (RemoteException e) {
21353                } finally {
21354                    Binder.restoreCallingIdentity(token);
21355                }
21356            }
21357        } else {
21358            throw new IllegalArgumentException("No selective enforcement for " + permission);
21359        }
21360    }
21361
21362    @Override
21363    @Deprecated
21364    public boolean isPermissionEnforced(String permission) {
21365        return true;
21366    }
21367
21368    @Override
21369    public boolean isStorageLow() {
21370        final long token = Binder.clearCallingIdentity();
21371        try {
21372            final DeviceStorageMonitorInternal
21373                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21374            if (dsm != null) {
21375                return dsm.isMemoryLow();
21376            } else {
21377                return false;
21378            }
21379        } finally {
21380            Binder.restoreCallingIdentity(token);
21381        }
21382    }
21383
21384    @Override
21385    public IPackageInstaller getPackageInstaller() {
21386        return mInstallerService;
21387    }
21388
21389    private boolean userNeedsBadging(int userId) {
21390        int index = mUserNeedsBadging.indexOfKey(userId);
21391        if (index < 0) {
21392            final UserInfo userInfo;
21393            final long token = Binder.clearCallingIdentity();
21394            try {
21395                userInfo = sUserManager.getUserInfo(userId);
21396            } finally {
21397                Binder.restoreCallingIdentity(token);
21398            }
21399            final boolean b;
21400            if (userInfo != null && userInfo.isManagedProfile()) {
21401                b = true;
21402            } else {
21403                b = false;
21404            }
21405            mUserNeedsBadging.put(userId, b);
21406            return b;
21407        }
21408        return mUserNeedsBadging.valueAt(index);
21409    }
21410
21411    @Override
21412    public KeySet getKeySetByAlias(String packageName, String alias) {
21413        if (packageName == null || alias == null) {
21414            return null;
21415        }
21416        synchronized(mPackages) {
21417            final PackageParser.Package pkg = mPackages.get(packageName);
21418            if (pkg == null) {
21419                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21420                throw new IllegalArgumentException("Unknown package: " + packageName);
21421            }
21422            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21423            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21424        }
21425    }
21426
21427    @Override
21428    public KeySet getSigningKeySet(String packageName) {
21429        if (packageName == null) {
21430            return null;
21431        }
21432        synchronized(mPackages) {
21433            final PackageParser.Package pkg = mPackages.get(packageName);
21434            if (pkg == null) {
21435                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21436                throw new IllegalArgumentException("Unknown package: " + packageName);
21437            }
21438            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21439                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21440                throw new SecurityException("May not access signing KeySet of other apps.");
21441            }
21442            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21443            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21444        }
21445    }
21446
21447    @Override
21448    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21449        if (packageName == null || ks == null) {
21450            return false;
21451        }
21452        synchronized(mPackages) {
21453            final PackageParser.Package pkg = mPackages.get(packageName);
21454            if (pkg == null) {
21455                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21456                throw new IllegalArgumentException("Unknown package: " + packageName);
21457            }
21458            IBinder ksh = ks.getToken();
21459            if (ksh instanceof KeySetHandle) {
21460                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21461                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21462            }
21463            return false;
21464        }
21465    }
21466
21467    @Override
21468    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21469        if (packageName == null || ks == null) {
21470            return false;
21471        }
21472        synchronized(mPackages) {
21473            final PackageParser.Package pkg = mPackages.get(packageName);
21474            if (pkg == null) {
21475                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21476                throw new IllegalArgumentException("Unknown package: " + packageName);
21477            }
21478            IBinder ksh = ks.getToken();
21479            if (ksh instanceof KeySetHandle) {
21480                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21481                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21482            }
21483            return false;
21484        }
21485    }
21486
21487    private void deletePackageIfUnusedLPr(final String packageName) {
21488        PackageSetting ps = mSettings.mPackages.get(packageName);
21489        if (ps == null) {
21490            return;
21491        }
21492        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21493            // TODO Implement atomic delete if package is unused
21494            // It is currently possible that the package will be deleted even if it is installed
21495            // after this method returns.
21496            mHandler.post(new Runnable() {
21497                public void run() {
21498                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21499                }
21500            });
21501        }
21502    }
21503
21504    /**
21505     * Check and throw if the given before/after packages would be considered a
21506     * downgrade.
21507     */
21508    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21509            throws PackageManagerException {
21510        if (after.versionCode < before.mVersionCode) {
21511            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21512                    "Update version code " + after.versionCode + " is older than current "
21513                    + before.mVersionCode);
21514        } else if (after.versionCode == before.mVersionCode) {
21515            if (after.baseRevisionCode < before.baseRevisionCode) {
21516                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21517                        "Update base revision code " + after.baseRevisionCode
21518                        + " is older than current " + before.baseRevisionCode);
21519            }
21520
21521            if (!ArrayUtils.isEmpty(after.splitNames)) {
21522                for (int i = 0; i < after.splitNames.length; i++) {
21523                    final String splitName = after.splitNames[i];
21524                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21525                    if (j != -1) {
21526                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21527                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21528                                    "Update split " + splitName + " revision code "
21529                                    + after.splitRevisionCodes[i] + " is older than current "
21530                                    + before.splitRevisionCodes[j]);
21531                        }
21532                    }
21533                }
21534            }
21535        }
21536    }
21537
21538    private static class MoveCallbacks extends Handler {
21539        private static final int MSG_CREATED = 1;
21540        private static final int MSG_STATUS_CHANGED = 2;
21541
21542        private final RemoteCallbackList<IPackageMoveObserver>
21543                mCallbacks = new RemoteCallbackList<>();
21544
21545        private final SparseIntArray mLastStatus = new SparseIntArray();
21546
21547        public MoveCallbacks(Looper looper) {
21548            super(looper);
21549        }
21550
21551        public void register(IPackageMoveObserver callback) {
21552            mCallbacks.register(callback);
21553        }
21554
21555        public void unregister(IPackageMoveObserver callback) {
21556            mCallbacks.unregister(callback);
21557        }
21558
21559        @Override
21560        public void handleMessage(Message msg) {
21561            final SomeArgs args = (SomeArgs) msg.obj;
21562            final int n = mCallbacks.beginBroadcast();
21563            for (int i = 0; i < n; i++) {
21564                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21565                try {
21566                    invokeCallback(callback, msg.what, args);
21567                } catch (RemoteException ignored) {
21568                }
21569            }
21570            mCallbacks.finishBroadcast();
21571            args.recycle();
21572        }
21573
21574        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21575                throws RemoteException {
21576            switch (what) {
21577                case MSG_CREATED: {
21578                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21579                    break;
21580                }
21581                case MSG_STATUS_CHANGED: {
21582                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21583                    break;
21584                }
21585            }
21586        }
21587
21588        private void notifyCreated(int moveId, Bundle extras) {
21589            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21590
21591            final SomeArgs args = SomeArgs.obtain();
21592            args.argi1 = moveId;
21593            args.arg2 = extras;
21594            obtainMessage(MSG_CREATED, args).sendToTarget();
21595        }
21596
21597        private void notifyStatusChanged(int moveId, int status) {
21598            notifyStatusChanged(moveId, status, -1);
21599        }
21600
21601        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21602            Slog.v(TAG, "Move " + moveId + " status " + status);
21603
21604            final SomeArgs args = SomeArgs.obtain();
21605            args.argi1 = moveId;
21606            args.argi2 = status;
21607            args.arg3 = estMillis;
21608            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21609
21610            synchronized (mLastStatus) {
21611                mLastStatus.put(moveId, status);
21612            }
21613        }
21614    }
21615
21616    private final static class OnPermissionChangeListeners extends Handler {
21617        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21618
21619        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21620                new RemoteCallbackList<>();
21621
21622        public OnPermissionChangeListeners(Looper looper) {
21623            super(looper);
21624        }
21625
21626        @Override
21627        public void handleMessage(Message msg) {
21628            switch (msg.what) {
21629                case MSG_ON_PERMISSIONS_CHANGED: {
21630                    final int uid = msg.arg1;
21631                    handleOnPermissionsChanged(uid);
21632                } break;
21633            }
21634        }
21635
21636        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21637            mPermissionListeners.register(listener);
21638
21639        }
21640
21641        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21642            mPermissionListeners.unregister(listener);
21643        }
21644
21645        public void onPermissionsChanged(int uid) {
21646            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21647                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21648            }
21649        }
21650
21651        private void handleOnPermissionsChanged(int uid) {
21652            final int count = mPermissionListeners.beginBroadcast();
21653            try {
21654                for (int i = 0; i < count; i++) {
21655                    IOnPermissionsChangeListener callback = mPermissionListeners
21656                            .getBroadcastItem(i);
21657                    try {
21658                        callback.onPermissionsChanged(uid);
21659                    } catch (RemoteException e) {
21660                        Log.e(TAG, "Permission listener is dead", e);
21661                    }
21662                }
21663            } finally {
21664                mPermissionListeners.finishBroadcast();
21665            }
21666        }
21667    }
21668
21669    private class PackageManagerInternalImpl extends PackageManagerInternal {
21670        @Override
21671        public void setLocationPackagesProvider(PackagesProvider provider) {
21672            synchronized (mPackages) {
21673                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21674            }
21675        }
21676
21677        @Override
21678        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21679            synchronized (mPackages) {
21680                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21681            }
21682        }
21683
21684        @Override
21685        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21686            synchronized (mPackages) {
21687                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21688            }
21689        }
21690
21691        @Override
21692        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21693            synchronized (mPackages) {
21694                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21695            }
21696        }
21697
21698        @Override
21699        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21700            synchronized (mPackages) {
21701                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21702            }
21703        }
21704
21705        @Override
21706        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21707            synchronized (mPackages) {
21708                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21709            }
21710        }
21711
21712        @Override
21713        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21714            synchronized (mPackages) {
21715                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21716                        packageName, userId);
21717            }
21718        }
21719
21720        @Override
21721        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21722            synchronized (mPackages) {
21723                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21724                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21725                        packageName, userId);
21726            }
21727        }
21728
21729        @Override
21730        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21731            synchronized (mPackages) {
21732                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21733                        packageName, userId);
21734            }
21735        }
21736
21737        @Override
21738        public void setKeepUninstalledPackages(final List<String> packageList) {
21739            Preconditions.checkNotNull(packageList);
21740            List<String> removedFromList = null;
21741            synchronized (mPackages) {
21742                if (mKeepUninstalledPackages != null) {
21743                    final int packagesCount = mKeepUninstalledPackages.size();
21744                    for (int i = 0; i < packagesCount; i++) {
21745                        String oldPackage = mKeepUninstalledPackages.get(i);
21746                        if (packageList != null && packageList.contains(oldPackage)) {
21747                            continue;
21748                        }
21749                        if (removedFromList == null) {
21750                            removedFromList = new ArrayList<>();
21751                        }
21752                        removedFromList.add(oldPackage);
21753                    }
21754                }
21755                mKeepUninstalledPackages = new ArrayList<>(packageList);
21756                if (removedFromList != null) {
21757                    final int removedCount = removedFromList.size();
21758                    for (int i = 0; i < removedCount; i++) {
21759                        deletePackageIfUnusedLPr(removedFromList.get(i));
21760                    }
21761                }
21762            }
21763        }
21764
21765        @Override
21766        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21767            synchronized (mPackages) {
21768                // If we do not support permission review, done.
21769                if (!mPermissionReviewRequired) {
21770                    return false;
21771                }
21772
21773                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21774                if (packageSetting == null) {
21775                    return false;
21776                }
21777
21778                // Permission review applies only to apps not supporting the new permission model.
21779                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21780                    return false;
21781                }
21782
21783                // Legacy apps have the permission and get user consent on launch.
21784                PermissionsState permissionsState = packageSetting.getPermissionsState();
21785                return permissionsState.isPermissionReviewRequired(userId);
21786            }
21787        }
21788
21789        @Override
21790        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21791            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21792        }
21793
21794        @Override
21795        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21796                int userId) {
21797            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21798        }
21799
21800        @Override
21801        public void setDeviceAndProfileOwnerPackages(
21802                int deviceOwnerUserId, String deviceOwnerPackage,
21803                SparseArray<String> profileOwnerPackages) {
21804            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21805                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21806        }
21807
21808        @Override
21809        public boolean isPackageDataProtected(int userId, String packageName) {
21810            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21811        }
21812
21813        @Override
21814        public boolean isPackageEphemeral(int userId, String packageName) {
21815            synchronized (mPackages) {
21816                PackageParser.Package p = mPackages.get(packageName);
21817                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21818            }
21819        }
21820
21821        @Override
21822        public boolean wasPackageEverLaunched(String packageName, int userId) {
21823            synchronized (mPackages) {
21824                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21825            }
21826        }
21827
21828        @Override
21829        public void grantRuntimePermission(String packageName, String name, int userId,
21830                boolean overridePolicy) {
21831            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21832                    overridePolicy);
21833        }
21834
21835        @Override
21836        public void revokeRuntimePermission(String packageName, String name, int userId,
21837                boolean overridePolicy) {
21838            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21839                    overridePolicy);
21840        }
21841
21842        @Override
21843        public String getNameForUid(int uid) {
21844            return PackageManagerService.this.getNameForUid(uid);
21845        }
21846
21847        @Override
21848        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21849                Intent origIntent, String resolvedType, Intent launchIntent,
21850                String callingPackage, int userId) {
21851            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21852                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21853        }
21854
21855        public String getSetupWizardPackageName() {
21856            return mSetupWizardPackage;
21857        }
21858    }
21859
21860    @Override
21861    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21862        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21863        synchronized (mPackages) {
21864            final long identity = Binder.clearCallingIdentity();
21865            try {
21866                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21867                        packageNames, userId);
21868            } finally {
21869                Binder.restoreCallingIdentity(identity);
21870            }
21871        }
21872    }
21873
21874    private static void enforceSystemOrPhoneCaller(String tag) {
21875        int callingUid = Binder.getCallingUid();
21876        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21877            throw new SecurityException(
21878                    "Cannot call " + tag + " from UID " + callingUid);
21879        }
21880    }
21881
21882    boolean isHistoricalPackageUsageAvailable() {
21883        return mPackageUsage.isHistoricalPackageUsageAvailable();
21884    }
21885
21886    /**
21887     * Return a <b>copy</b> of the collection of packages known to the package manager.
21888     * @return A copy of the values of mPackages.
21889     */
21890    Collection<PackageParser.Package> getPackages() {
21891        synchronized (mPackages) {
21892            return new ArrayList<>(mPackages.values());
21893        }
21894    }
21895
21896    /**
21897     * Logs process start information (including base APK hash) to the security log.
21898     * @hide
21899     */
21900    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21901            String apkFile, int pid) {
21902        if (!SecurityLog.isLoggingEnabled()) {
21903            return;
21904        }
21905        Bundle data = new Bundle();
21906        data.putLong("startTimestamp", System.currentTimeMillis());
21907        data.putString("processName", processName);
21908        data.putInt("uid", uid);
21909        data.putString("seinfo", seinfo);
21910        data.putString("apkFile", apkFile);
21911        data.putInt("pid", pid);
21912        Message msg = mProcessLoggingHandler.obtainMessage(
21913                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21914        msg.setData(data);
21915        mProcessLoggingHandler.sendMessage(msg);
21916    }
21917
21918    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21919        return mCompilerStats.getPackageStats(pkgName);
21920    }
21921
21922    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21923        return getOrCreateCompilerPackageStats(pkg.packageName);
21924    }
21925
21926    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21927        return mCompilerStats.getOrCreatePackageStats(pkgName);
21928    }
21929
21930    public void deleteCompilerPackageStats(String pkgName) {
21931        mCompilerStats.deletePackageStats(pkgName);
21932    }
21933
21934    @Override
21935    public int getInstallReason(String packageName, int userId) {
21936        enforceCrossUserPermission(Binder.getCallingUid(), userId,
21937                true /* requireFullPermission */, false /* checkShell */,
21938                "get install reason");
21939        synchronized (mPackages) {
21940            final PackageSetting ps = mSettings.mPackages.get(packageName);
21941            if (ps != null) {
21942                return ps.getInstallReason(userId);
21943            }
21944        }
21945        return PackageManager.INSTALL_REASON_UNKNOWN;
21946    }
21947}
21948