PackageManagerService.java revision fe0253b34ec4fdb6afceb11193f29029b524866a
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            ps.categoryHint = categoryHint;
13040            scheduleWriteSettingsLocked();
13041        }
13042    }
13043
13044    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13045        // Queue up an async operation since the package installation may take a little while.
13046        mHandler.post(new Runnable() {
13047            public void run() {
13048                mHandler.removeCallbacks(this);
13049                 // Result object to be returned
13050                PackageInstalledInfo res = new PackageInstalledInfo();
13051                res.setReturnCode(currentStatus);
13052                res.uid = -1;
13053                res.pkg = null;
13054                res.removedInfo = null;
13055                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13056                    args.doPreInstall(res.returnCode);
13057                    synchronized (mInstallLock) {
13058                        installPackageTracedLI(args, res);
13059                    }
13060                    args.doPostInstall(res.returnCode, res.uid);
13061                }
13062
13063                // A restore should be performed at this point if (a) the install
13064                // succeeded, (b) the operation is not an update, and (c) the new
13065                // package has not opted out of backup participation.
13066                final boolean update = res.removedInfo != null
13067                        && res.removedInfo.removedPackage != null;
13068                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13069                boolean doRestore = !update
13070                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13071
13072                // Set up the post-install work request bookkeeping.  This will be used
13073                // and cleaned up by the post-install event handling regardless of whether
13074                // there's a restore pass performed.  Token values are >= 1.
13075                int token;
13076                if (mNextInstallToken < 0) mNextInstallToken = 1;
13077                token = mNextInstallToken++;
13078
13079                PostInstallData data = new PostInstallData(args, res);
13080                mRunningInstalls.put(token, data);
13081                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13082
13083                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13084                    // Pass responsibility to the Backup Manager.  It will perform a
13085                    // restore if appropriate, then pass responsibility back to the
13086                    // Package Manager to run the post-install observer callbacks
13087                    // and broadcasts.
13088                    IBackupManager bm = IBackupManager.Stub.asInterface(
13089                            ServiceManager.getService(Context.BACKUP_SERVICE));
13090                    if (bm != null) {
13091                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13092                                + " to BM for possible restore");
13093                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13094                        try {
13095                            // TODO: http://b/22388012
13096                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13097                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13098                            } else {
13099                                doRestore = false;
13100                            }
13101                        } catch (RemoteException e) {
13102                            // can't happen; the backup manager is local
13103                        } catch (Exception e) {
13104                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13105                            doRestore = false;
13106                        }
13107                    } else {
13108                        Slog.e(TAG, "Backup Manager not found!");
13109                        doRestore = false;
13110                    }
13111                }
13112
13113                if (!doRestore) {
13114                    // No restore possible, or the Backup Manager was mysteriously not
13115                    // available -- just fire the post-install work request directly.
13116                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13117
13118                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13119
13120                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13121                    mHandler.sendMessage(msg);
13122                }
13123            }
13124        });
13125    }
13126
13127    /**
13128     * Callback from PackageSettings whenever an app is first transitioned out of the
13129     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13130     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13131     * here whether the app is the target of an ongoing install, and only send the
13132     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13133     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13134     * handling.
13135     */
13136    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13137        // Serialize this with the rest of the install-process message chain.  In the
13138        // restore-at-install case, this Runnable will necessarily run before the
13139        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13140        // are coherent.  In the non-restore case, the app has already completed install
13141        // and been launched through some other means, so it is not in a problematic
13142        // state for observers to see the FIRST_LAUNCH signal.
13143        mHandler.post(new Runnable() {
13144            @Override
13145            public void run() {
13146                for (int i = 0; i < mRunningInstalls.size(); i++) {
13147                    final PostInstallData data = mRunningInstalls.valueAt(i);
13148                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13149                        continue;
13150                    }
13151                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13152                        // right package; but is it for the right user?
13153                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13154                            if (userId == data.res.newUsers[uIndex]) {
13155                                if (DEBUG_BACKUP) {
13156                                    Slog.i(TAG, "Package " + pkgName
13157                                            + " being restored so deferring FIRST_LAUNCH");
13158                                }
13159                                return;
13160                            }
13161                        }
13162                    }
13163                }
13164                // didn't find it, so not being restored
13165                if (DEBUG_BACKUP) {
13166                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13167                }
13168                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13169            }
13170        });
13171    }
13172
13173    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13174        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13175                installerPkg, null, userIds);
13176    }
13177
13178    private abstract class HandlerParams {
13179        private static final int MAX_RETRIES = 4;
13180
13181        /**
13182         * Number of times startCopy() has been attempted and had a non-fatal
13183         * error.
13184         */
13185        private int mRetries = 0;
13186
13187        /** User handle for the user requesting the information or installation. */
13188        private final UserHandle mUser;
13189        String traceMethod;
13190        int traceCookie;
13191
13192        HandlerParams(UserHandle user) {
13193            mUser = user;
13194        }
13195
13196        UserHandle getUser() {
13197            return mUser;
13198        }
13199
13200        HandlerParams setTraceMethod(String traceMethod) {
13201            this.traceMethod = traceMethod;
13202            return this;
13203        }
13204
13205        HandlerParams setTraceCookie(int traceCookie) {
13206            this.traceCookie = traceCookie;
13207            return this;
13208        }
13209
13210        final boolean startCopy() {
13211            boolean res;
13212            try {
13213                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13214
13215                if (++mRetries > MAX_RETRIES) {
13216                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13217                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13218                    handleServiceError();
13219                    return false;
13220                } else {
13221                    handleStartCopy();
13222                    res = true;
13223                }
13224            } catch (RemoteException e) {
13225                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13226                mHandler.sendEmptyMessage(MCS_RECONNECT);
13227                res = false;
13228            }
13229            handleReturnCode();
13230            return res;
13231        }
13232
13233        final void serviceError() {
13234            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13235            handleServiceError();
13236            handleReturnCode();
13237        }
13238
13239        abstract void handleStartCopy() throws RemoteException;
13240        abstract void handleServiceError();
13241        abstract void handleReturnCode();
13242    }
13243
13244    class MeasureParams extends HandlerParams {
13245        private final PackageStats mStats;
13246        private boolean mSuccess;
13247
13248        private final IPackageStatsObserver mObserver;
13249
13250        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13251            super(new UserHandle(stats.userHandle));
13252            mObserver = observer;
13253            mStats = stats;
13254        }
13255
13256        @Override
13257        public String toString() {
13258            return "MeasureParams{"
13259                + Integer.toHexString(System.identityHashCode(this))
13260                + " " + mStats.packageName + "}";
13261        }
13262
13263        @Override
13264        void handleStartCopy() throws RemoteException {
13265            synchronized (mInstallLock) {
13266                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13267            }
13268
13269            if (mSuccess) {
13270                boolean mounted = false;
13271                try {
13272                    final String status = Environment.getExternalStorageState();
13273                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13274                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13275                } catch (Exception e) {
13276                }
13277
13278                if (mounted) {
13279                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13280
13281                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13282                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13283
13284                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13285                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13286
13287                    // Always subtract cache size, since it's a subdirectory
13288                    mStats.externalDataSize -= mStats.externalCacheSize;
13289
13290                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13291                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13292
13293                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13294                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13295                }
13296            }
13297        }
13298
13299        @Override
13300        void handleReturnCode() {
13301            if (mObserver != null) {
13302                try {
13303                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13304                } catch (RemoteException e) {
13305                    Slog.i(TAG, "Observer no longer exists.");
13306                }
13307            }
13308        }
13309
13310        @Override
13311        void handleServiceError() {
13312            Slog.e(TAG, "Could not measure application " + mStats.packageName
13313                            + " external storage");
13314        }
13315    }
13316
13317    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13318            throws RemoteException {
13319        long result = 0;
13320        for (File path : paths) {
13321            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13322        }
13323        return result;
13324    }
13325
13326    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13327        for (File path : paths) {
13328            try {
13329                mcs.clearDirectory(path.getAbsolutePath());
13330            } catch (RemoteException e) {
13331            }
13332        }
13333    }
13334
13335    static class OriginInfo {
13336        /**
13337         * Location where install is coming from, before it has been
13338         * copied/renamed into place. This could be a single monolithic APK
13339         * file, or a cluster directory. This location may be untrusted.
13340         */
13341        final File file;
13342        final String cid;
13343
13344        /**
13345         * Flag indicating that {@link #file} or {@link #cid} has already been
13346         * staged, meaning downstream users don't need to defensively copy the
13347         * contents.
13348         */
13349        final boolean staged;
13350
13351        /**
13352         * Flag indicating that {@link #file} or {@link #cid} is an already
13353         * installed app that is being moved.
13354         */
13355        final boolean existing;
13356
13357        final String resolvedPath;
13358        final File resolvedFile;
13359
13360        static OriginInfo fromNothing() {
13361            return new OriginInfo(null, null, false, false);
13362        }
13363
13364        static OriginInfo fromUntrustedFile(File file) {
13365            return new OriginInfo(file, null, false, false);
13366        }
13367
13368        static OriginInfo fromExistingFile(File file) {
13369            return new OriginInfo(file, null, false, true);
13370        }
13371
13372        static OriginInfo fromStagedFile(File file) {
13373            return new OriginInfo(file, null, true, false);
13374        }
13375
13376        static OriginInfo fromStagedContainer(String cid) {
13377            return new OriginInfo(null, cid, true, false);
13378        }
13379
13380        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13381            this.file = file;
13382            this.cid = cid;
13383            this.staged = staged;
13384            this.existing = existing;
13385
13386            if (cid != null) {
13387                resolvedPath = PackageHelper.getSdDir(cid);
13388                resolvedFile = new File(resolvedPath);
13389            } else if (file != null) {
13390                resolvedPath = file.getAbsolutePath();
13391                resolvedFile = file;
13392            } else {
13393                resolvedPath = null;
13394                resolvedFile = null;
13395            }
13396        }
13397    }
13398
13399    static class MoveInfo {
13400        final int moveId;
13401        final String fromUuid;
13402        final String toUuid;
13403        final String packageName;
13404        final String dataAppName;
13405        final int appId;
13406        final String seinfo;
13407        final int targetSdkVersion;
13408
13409        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13410                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13411            this.moveId = moveId;
13412            this.fromUuid = fromUuid;
13413            this.toUuid = toUuid;
13414            this.packageName = packageName;
13415            this.dataAppName = dataAppName;
13416            this.appId = appId;
13417            this.seinfo = seinfo;
13418            this.targetSdkVersion = targetSdkVersion;
13419        }
13420    }
13421
13422    static class VerificationInfo {
13423        /** A constant used to indicate that a uid value is not present. */
13424        public static final int NO_UID = -1;
13425
13426        /** URI referencing where the package was downloaded from. */
13427        final Uri originatingUri;
13428
13429        /** HTTP referrer URI associated with the originatingURI. */
13430        final Uri referrer;
13431
13432        /** UID of the application that the install request originated from. */
13433        final int originatingUid;
13434
13435        /** UID of application requesting the install */
13436        final int installerUid;
13437
13438        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13439            this.originatingUri = originatingUri;
13440            this.referrer = referrer;
13441            this.originatingUid = originatingUid;
13442            this.installerUid = installerUid;
13443        }
13444    }
13445
13446    class InstallParams extends HandlerParams {
13447        final OriginInfo origin;
13448        final MoveInfo move;
13449        final IPackageInstallObserver2 observer;
13450        int installFlags;
13451        final String installerPackageName;
13452        final String volumeUuid;
13453        private InstallArgs mArgs;
13454        private int mRet;
13455        final String packageAbiOverride;
13456        final String[] grantedRuntimePermissions;
13457        final VerificationInfo verificationInfo;
13458        final Certificate[][] certificates;
13459        final int installReason;
13460
13461        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13462                int installFlags, String installerPackageName, String volumeUuid,
13463                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13464                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
13465            super(user);
13466            this.origin = origin;
13467            this.move = move;
13468            this.observer = observer;
13469            this.installFlags = installFlags;
13470            this.installerPackageName = installerPackageName;
13471            this.volumeUuid = volumeUuid;
13472            this.verificationInfo = verificationInfo;
13473            this.packageAbiOverride = packageAbiOverride;
13474            this.grantedRuntimePermissions = grantedPermissions;
13475            this.certificates = certificates;
13476            this.installReason = installReason;
13477        }
13478
13479        @Override
13480        public String toString() {
13481            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13482                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13483        }
13484
13485        private int installLocationPolicy(PackageInfoLite pkgLite) {
13486            String packageName = pkgLite.packageName;
13487            int installLocation = pkgLite.installLocation;
13488            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13489            // reader
13490            synchronized (mPackages) {
13491                // Currently installed package which the new package is attempting to replace or
13492                // null if no such package is installed.
13493                PackageParser.Package installedPkg = mPackages.get(packageName);
13494                // Package which currently owns the data which the new package will own if installed.
13495                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13496                // will be null whereas dataOwnerPkg will contain information about the package
13497                // which was uninstalled while keeping its data.
13498                PackageParser.Package dataOwnerPkg = installedPkg;
13499                if (dataOwnerPkg  == null) {
13500                    PackageSetting ps = mSettings.mPackages.get(packageName);
13501                    if (ps != null) {
13502                        dataOwnerPkg = ps.pkg;
13503                    }
13504                }
13505
13506                if (dataOwnerPkg != null) {
13507                    // If installed, the package will get access to data left on the device by its
13508                    // predecessor. As a security measure, this is permited only if this is not a
13509                    // version downgrade or if the predecessor package is marked as debuggable and
13510                    // a downgrade is explicitly requested.
13511                    //
13512                    // On debuggable platform builds, downgrades are permitted even for
13513                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13514                    // not offer security guarantees and thus it's OK to disable some security
13515                    // mechanisms to make debugging/testing easier on those builds. However, even on
13516                    // debuggable builds downgrades of packages are permitted only if requested via
13517                    // installFlags. This is because we aim to keep the behavior of debuggable
13518                    // platform builds as close as possible to the behavior of non-debuggable
13519                    // platform builds.
13520                    final boolean downgradeRequested =
13521                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13522                    final boolean packageDebuggable =
13523                                (dataOwnerPkg.applicationInfo.flags
13524                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13525                    final boolean downgradePermitted =
13526                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13527                    if (!downgradePermitted) {
13528                        try {
13529                            checkDowngrade(dataOwnerPkg, pkgLite);
13530                        } catch (PackageManagerException e) {
13531                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13532                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13533                        }
13534                    }
13535                }
13536
13537                if (installedPkg != null) {
13538                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13539                        // Check for updated system application.
13540                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13541                            if (onSd) {
13542                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13543                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13544                            }
13545                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13546                        } else {
13547                            if (onSd) {
13548                                // Install flag overrides everything.
13549                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13550                            }
13551                            // If current upgrade specifies particular preference
13552                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13553                                // Application explicitly specified internal.
13554                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13555                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13556                                // App explictly prefers external. Let policy decide
13557                            } else {
13558                                // Prefer previous location
13559                                if (isExternal(installedPkg)) {
13560                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13561                                }
13562                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13563                            }
13564                        }
13565                    } else {
13566                        // Invalid install. Return error code
13567                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13568                    }
13569                }
13570            }
13571            // All the special cases have been taken care of.
13572            // Return result based on recommended install location.
13573            if (onSd) {
13574                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13575            }
13576            return pkgLite.recommendedInstallLocation;
13577        }
13578
13579        /*
13580         * Invoke remote method to get package information and install
13581         * location values. Override install location based on default
13582         * policy if needed and then create install arguments based
13583         * on the install location.
13584         */
13585        public void handleStartCopy() throws RemoteException {
13586            int ret = PackageManager.INSTALL_SUCCEEDED;
13587
13588            // If we're already staged, we've firmly committed to an install location
13589            if (origin.staged) {
13590                if (origin.file != null) {
13591                    installFlags |= PackageManager.INSTALL_INTERNAL;
13592                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13593                } else if (origin.cid != null) {
13594                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13595                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13596                } else {
13597                    throw new IllegalStateException("Invalid stage location");
13598                }
13599            }
13600
13601            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13602            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13603            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13604            PackageInfoLite pkgLite = null;
13605
13606            if (onInt && onSd) {
13607                // Check if both bits are set.
13608                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13609                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13610            } else if (onSd && ephemeral) {
13611                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13612                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13613            } else {
13614                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13615                        packageAbiOverride);
13616
13617                if (DEBUG_EPHEMERAL && ephemeral) {
13618                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13619                }
13620
13621                /*
13622                 * If we have too little free space, try to free cache
13623                 * before giving up.
13624                 */
13625                if (!origin.staged && pkgLite.recommendedInstallLocation
13626                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13627                    // TODO: focus freeing disk space on the target device
13628                    final StorageManager storage = StorageManager.from(mContext);
13629                    final long lowThreshold = storage.getStorageLowBytes(
13630                            Environment.getDataDirectory());
13631
13632                    final long sizeBytes = mContainerService.calculateInstalledSize(
13633                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13634
13635                    try {
13636                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13637                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13638                                installFlags, packageAbiOverride);
13639                    } catch (InstallerException e) {
13640                        Slog.w(TAG, "Failed to free cache", e);
13641                    }
13642
13643                    /*
13644                     * The cache free must have deleted the file we
13645                     * downloaded to install.
13646                     *
13647                     * TODO: fix the "freeCache" call to not delete
13648                     *       the file we care about.
13649                     */
13650                    if (pkgLite.recommendedInstallLocation
13651                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13652                        pkgLite.recommendedInstallLocation
13653                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13654                    }
13655                }
13656            }
13657
13658            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13659                int loc = pkgLite.recommendedInstallLocation;
13660                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13661                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13662                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13663                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13664                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13665                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13666                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13667                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13668                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13669                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13670                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13671                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13672                } else {
13673                    // Override with defaults if needed.
13674                    loc = installLocationPolicy(pkgLite);
13675                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13676                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13677                    } else if (!onSd && !onInt) {
13678                        // Override install location with flags
13679                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13680                            // Set the flag to install on external media.
13681                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13682                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13683                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13684                            if (DEBUG_EPHEMERAL) {
13685                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13686                            }
13687                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13688                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13689                                    |PackageManager.INSTALL_INTERNAL);
13690                        } else {
13691                            // Make sure the flag for installing on external
13692                            // media is unset
13693                            installFlags |= PackageManager.INSTALL_INTERNAL;
13694                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13695                        }
13696                    }
13697                }
13698            }
13699
13700            final InstallArgs args = createInstallArgs(this);
13701            mArgs = args;
13702
13703            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13704                // TODO: http://b/22976637
13705                // Apps installed for "all" users use the device owner to verify the app
13706                UserHandle verifierUser = getUser();
13707                if (verifierUser == UserHandle.ALL) {
13708                    verifierUser = UserHandle.SYSTEM;
13709                }
13710
13711                /*
13712                 * Determine if we have any installed package verifiers. If we
13713                 * do, then we'll defer to them to verify the packages.
13714                 */
13715                final int requiredUid = mRequiredVerifierPackage == null ? -1
13716                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13717                                verifierUser.getIdentifier());
13718                if (!origin.existing && requiredUid != -1
13719                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13720                    final Intent verification = new Intent(
13721                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13722                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13723                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13724                            PACKAGE_MIME_TYPE);
13725                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13726
13727                    // Query all live verifiers based on current user state
13728                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13729                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13730
13731                    if (DEBUG_VERIFY) {
13732                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13733                                + verification.toString() + " with " + pkgLite.verifiers.length
13734                                + " optional verifiers");
13735                    }
13736
13737                    final int verificationId = mPendingVerificationToken++;
13738
13739                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13740
13741                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13742                            installerPackageName);
13743
13744                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13745                            installFlags);
13746
13747                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13748                            pkgLite.packageName);
13749
13750                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13751                            pkgLite.versionCode);
13752
13753                    if (verificationInfo != null) {
13754                        if (verificationInfo.originatingUri != null) {
13755                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13756                                    verificationInfo.originatingUri);
13757                        }
13758                        if (verificationInfo.referrer != null) {
13759                            verification.putExtra(Intent.EXTRA_REFERRER,
13760                                    verificationInfo.referrer);
13761                        }
13762                        if (verificationInfo.originatingUid >= 0) {
13763                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13764                                    verificationInfo.originatingUid);
13765                        }
13766                        if (verificationInfo.installerUid >= 0) {
13767                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13768                                    verificationInfo.installerUid);
13769                        }
13770                    }
13771
13772                    final PackageVerificationState verificationState = new PackageVerificationState(
13773                            requiredUid, args);
13774
13775                    mPendingVerification.append(verificationId, verificationState);
13776
13777                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13778                            receivers, verificationState);
13779
13780                    /*
13781                     * If any sufficient verifiers were listed in the package
13782                     * manifest, attempt to ask them.
13783                     */
13784                    if (sufficientVerifiers != null) {
13785                        final int N = sufficientVerifiers.size();
13786                        if (N == 0) {
13787                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13788                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13789                        } else {
13790                            for (int i = 0; i < N; i++) {
13791                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13792
13793                                final Intent sufficientIntent = new Intent(verification);
13794                                sufficientIntent.setComponent(verifierComponent);
13795                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13796                            }
13797                        }
13798                    }
13799
13800                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13801                            mRequiredVerifierPackage, receivers);
13802                    if (ret == PackageManager.INSTALL_SUCCEEDED
13803                            && mRequiredVerifierPackage != null) {
13804                        Trace.asyncTraceBegin(
13805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13806                        /*
13807                         * Send the intent to the required verification agent,
13808                         * but only start the verification timeout after the
13809                         * target BroadcastReceivers have run.
13810                         */
13811                        verification.setComponent(requiredVerifierComponent);
13812                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13813                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13814                                new BroadcastReceiver() {
13815                                    @Override
13816                                    public void onReceive(Context context, Intent intent) {
13817                                        final Message msg = mHandler
13818                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13819                                        msg.arg1 = verificationId;
13820                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13821                                    }
13822                                }, null, 0, null, null);
13823
13824                        /*
13825                         * We don't want the copy to proceed until verification
13826                         * succeeds, so null out this field.
13827                         */
13828                        mArgs = null;
13829                    }
13830                } else {
13831                    /*
13832                     * No package verification is enabled, so immediately start
13833                     * the remote call to initiate copy using temporary file.
13834                     */
13835                    ret = args.copyApk(mContainerService, true);
13836                }
13837            }
13838
13839            mRet = ret;
13840        }
13841
13842        @Override
13843        void handleReturnCode() {
13844            // If mArgs is null, then MCS couldn't be reached. When it
13845            // reconnects, it will try again to install. At that point, this
13846            // will succeed.
13847            if (mArgs != null) {
13848                processPendingInstall(mArgs, mRet);
13849            }
13850        }
13851
13852        @Override
13853        void handleServiceError() {
13854            mArgs = createInstallArgs(this);
13855            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13856        }
13857
13858        public boolean isForwardLocked() {
13859            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13860        }
13861    }
13862
13863    /**
13864     * Used during creation of InstallArgs
13865     *
13866     * @param installFlags package installation flags
13867     * @return true if should be installed on external storage
13868     */
13869    private static boolean installOnExternalAsec(int installFlags) {
13870        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13871            return false;
13872        }
13873        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13874            return true;
13875        }
13876        return false;
13877    }
13878
13879    /**
13880     * Used during creation of InstallArgs
13881     *
13882     * @param installFlags package installation flags
13883     * @return true if should be installed as forward locked
13884     */
13885    private static boolean installForwardLocked(int installFlags) {
13886        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13887    }
13888
13889    private InstallArgs createInstallArgs(InstallParams params) {
13890        if (params.move != null) {
13891            return new MoveInstallArgs(params);
13892        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13893            return new AsecInstallArgs(params);
13894        } else {
13895            return new FileInstallArgs(params);
13896        }
13897    }
13898
13899    /**
13900     * Create args that describe an existing installed package. Typically used
13901     * when cleaning up old installs, or used as a move source.
13902     */
13903    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13904            String resourcePath, String[] instructionSets) {
13905        final boolean isInAsec;
13906        if (installOnExternalAsec(installFlags)) {
13907            /* Apps on SD card are always in ASEC containers. */
13908            isInAsec = true;
13909        } else if (installForwardLocked(installFlags)
13910                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13911            /*
13912             * Forward-locked apps are only in ASEC containers if they're the
13913             * new style
13914             */
13915            isInAsec = true;
13916        } else {
13917            isInAsec = false;
13918        }
13919
13920        if (isInAsec) {
13921            return new AsecInstallArgs(codePath, instructionSets,
13922                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13923        } else {
13924            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13925        }
13926    }
13927
13928    static abstract class InstallArgs {
13929        /** @see InstallParams#origin */
13930        final OriginInfo origin;
13931        /** @see InstallParams#move */
13932        final MoveInfo move;
13933
13934        final IPackageInstallObserver2 observer;
13935        // Always refers to PackageManager flags only
13936        final int installFlags;
13937        final String installerPackageName;
13938        final String volumeUuid;
13939        final UserHandle user;
13940        final String abiOverride;
13941        final String[] installGrantPermissions;
13942        /** If non-null, drop an async trace when the install completes */
13943        final String traceMethod;
13944        final int traceCookie;
13945        final Certificate[][] certificates;
13946        final int installReason;
13947
13948        // The list of instruction sets supported by this app. This is currently
13949        // only used during the rmdex() phase to clean up resources. We can get rid of this
13950        // if we move dex files under the common app path.
13951        /* nullable */ String[] instructionSets;
13952
13953        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13954                int installFlags, String installerPackageName, String volumeUuid,
13955                UserHandle user, String[] instructionSets,
13956                String abiOverride, String[] installGrantPermissions,
13957                String traceMethod, int traceCookie, Certificate[][] certificates,
13958                int installReason) {
13959            this.origin = origin;
13960            this.move = move;
13961            this.installFlags = installFlags;
13962            this.observer = observer;
13963            this.installerPackageName = installerPackageName;
13964            this.volumeUuid = volumeUuid;
13965            this.user = user;
13966            this.instructionSets = instructionSets;
13967            this.abiOverride = abiOverride;
13968            this.installGrantPermissions = installGrantPermissions;
13969            this.traceMethod = traceMethod;
13970            this.traceCookie = traceCookie;
13971            this.certificates = certificates;
13972            this.installReason = installReason;
13973        }
13974
13975        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13976        abstract int doPreInstall(int status);
13977
13978        /**
13979         * Rename package into final resting place. All paths on the given
13980         * scanned package should be updated to reflect the rename.
13981         */
13982        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13983        abstract int doPostInstall(int status, int uid);
13984
13985        /** @see PackageSettingBase#codePathString */
13986        abstract String getCodePath();
13987        /** @see PackageSettingBase#resourcePathString */
13988        abstract String getResourcePath();
13989
13990        // Need installer lock especially for dex file removal.
13991        abstract void cleanUpResourcesLI();
13992        abstract boolean doPostDeleteLI(boolean delete);
13993
13994        /**
13995         * Called before the source arguments are copied. This is used mostly
13996         * for MoveParams when it needs to read the source file to put it in the
13997         * destination.
13998         */
13999        int doPreCopy() {
14000            return PackageManager.INSTALL_SUCCEEDED;
14001        }
14002
14003        /**
14004         * Called after the source arguments are copied. This is used mostly for
14005         * MoveParams when it needs to read the source file to put it in the
14006         * destination.
14007         */
14008        int doPostCopy(int uid) {
14009            return PackageManager.INSTALL_SUCCEEDED;
14010        }
14011
14012        protected boolean isFwdLocked() {
14013            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14014        }
14015
14016        protected boolean isExternalAsec() {
14017            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14018        }
14019
14020        protected boolean isEphemeral() {
14021            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14022        }
14023
14024        UserHandle getUser() {
14025            return user;
14026        }
14027    }
14028
14029    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14030        if (!allCodePaths.isEmpty()) {
14031            if (instructionSets == null) {
14032                throw new IllegalStateException("instructionSet == null");
14033            }
14034            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14035            for (String codePath : allCodePaths) {
14036                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14037                    try {
14038                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14039                    } catch (InstallerException ignored) {
14040                    }
14041                }
14042            }
14043        }
14044    }
14045
14046    /**
14047     * Logic to handle installation of non-ASEC applications, including copying
14048     * and renaming logic.
14049     */
14050    class FileInstallArgs extends InstallArgs {
14051        private File codeFile;
14052        private File resourceFile;
14053
14054        // Example topology:
14055        // /data/app/com.example/base.apk
14056        // /data/app/com.example/split_foo.apk
14057        // /data/app/com.example/lib/arm/libfoo.so
14058        // /data/app/com.example/lib/arm64/libfoo.so
14059        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14060
14061        /** New install */
14062        FileInstallArgs(InstallParams params) {
14063            super(params.origin, params.move, params.observer, params.installFlags,
14064                    params.installerPackageName, params.volumeUuid,
14065                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14066                    params.grantedRuntimePermissions,
14067                    params.traceMethod, params.traceCookie, params.certificates,
14068                    params.installReason);
14069            if (isFwdLocked()) {
14070                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14071            }
14072        }
14073
14074        /** Existing install */
14075        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14076            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14077                    null, null, null, 0, null /*certificates*/,
14078                    PackageManager.INSTALL_REASON_UNKNOWN);
14079            this.codeFile = (codePath != null) ? new File(codePath) : null;
14080            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14081        }
14082
14083        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14084            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14085            try {
14086                return doCopyApk(imcs, temp);
14087            } finally {
14088                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14089            }
14090        }
14091
14092        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14093            if (origin.staged) {
14094                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14095                codeFile = origin.file;
14096                resourceFile = origin.file;
14097                return PackageManager.INSTALL_SUCCEEDED;
14098            }
14099
14100            try {
14101                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14102                final File tempDir =
14103                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14104                codeFile = tempDir;
14105                resourceFile = tempDir;
14106            } catch (IOException e) {
14107                Slog.w(TAG, "Failed to create copy file: " + e);
14108                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14109            }
14110
14111            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14112                @Override
14113                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14114                    if (!FileUtils.isValidExtFilename(name)) {
14115                        throw new IllegalArgumentException("Invalid filename: " + name);
14116                    }
14117                    try {
14118                        final File file = new File(codeFile, name);
14119                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14120                                O_RDWR | O_CREAT, 0644);
14121                        Os.chmod(file.getAbsolutePath(), 0644);
14122                        return new ParcelFileDescriptor(fd);
14123                    } catch (ErrnoException e) {
14124                        throw new RemoteException("Failed to open: " + e.getMessage());
14125                    }
14126                }
14127            };
14128
14129            int ret = PackageManager.INSTALL_SUCCEEDED;
14130            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14131            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14132                Slog.e(TAG, "Failed to copy package");
14133                return ret;
14134            }
14135
14136            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14137            NativeLibraryHelper.Handle handle = null;
14138            try {
14139                handle = NativeLibraryHelper.Handle.create(codeFile);
14140                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14141                        abiOverride);
14142            } catch (IOException e) {
14143                Slog.e(TAG, "Copying native libraries failed", e);
14144                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14145            } finally {
14146                IoUtils.closeQuietly(handle);
14147            }
14148
14149            return ret;
14150        }
14151
14152        int doPreInstall(int status) {
14153            if (status != PackageManager.INSTALL_SUCCEEDED) {
14154                cleanUp();
14155            }
14156            return status;
14157        }
14158
14159        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14160            if (status != PackageManager.INSTALL_SUCCEEDED) {
14161                cleanUp();
14162                return false;
14163            }
14164
14165            final File targetDir = codeFile.getParentFile();
14166            final File beforeCodeFile = codeFile;
14167            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14168
14169            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14170            try {
14171                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14172            } catch (ErrnoException e) {
14173                Slog.w(TAG, "Failed to rename", e);
14174                return false;
14175            }
14176
14177            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14178                Slog.w(TAG, "Failed to restorecon");
14179                return false;
14180            }
14181
14182            // Reflect the rename internally
14183            codeFile = afterCodeFile;
14184            resourceFile = afterCodeFile;
14185
14186            // Reflect the rename in scanned details
14187            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14188            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14189                    afterCodeFile, pkg.baseCodePath));
14190            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14191                    afterCodeFile, pkg.splitCodePaths));
14192
14193            // Reflect the rename in app info
14194            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14195            pkg.setApplicationInfoCodePath(pkg.codePath);
14196            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14197            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14198            pkg.setApplicationInfoResourcePath(pkg.codePath);
14199            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14200            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14201
14202            return true;
14203        }
14204
14205        int doPostInstall(int status, int uid) {
14206            if (status != PackageManager.INSTALL_SUCCEEDED) {
14207                cleanUp();
14208            }
14209            return status;
14210        }
14211
14212        @Override
14213        String getCodePath() {
14214            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14215        }
14216
14217        @Override
14218        String getResourcePath() {
14219            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14220        }
14221
14222        private boolean cleanUp() {
14223            if (codeFile == null || !codeFile.exists()) {
14224                return false;
14225            }
14226
14227            removeCodePathLI(codeFile);
14228
14229            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14230                resourceFile.delete();
14231            }
14232
14233            return true;
14234        }
14235
14236        void cleanUpResourcesLI() {
14237            // Try enumerating all code paths before deleting
14238            List<String> allCodePaths = Collections.EMPTY_LIST;
14239            if (codeFile != null && codeFile.exists()) {
14240                try {
14241                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14242                    allCodePaths = pkg.getAllCodePaths();
14243                } catch (PackageParserException e) {
14244                    // Ignored; we tried our best
14245                }
14246            }
14247
14248            cleanUp();
14249            removeDexFiles(allCodePaths, instructionSets);
14250        }
14251
14252        boolean doPostDeleteLI(boolean delete) {
14253            // XXX err, shouldn't we respect the delete flag?
14254            cleanUpResourcesLI();
14255            return true;
14256        }
14257    }
14258
14259    private boolean isAsecExternal(String cid) {
14260        final String asecPath = PackageHelper.getSdFilesystem(cid);
14261        return !asecPath.startsWith(mAsecInternalPath);
14262    }
14263
14264    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14265            PackageManagerException {
14266        if (copyRet < 0) {
14267            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14268                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14269                throw new PackageManagerException(copyRet, message);
14270            }
14271        }
14272    }
14273
14274    /**
14275     * Extract the StorageManagerService "container ID" from the full code path of an
14276     * .apk.
14277     */
14278    static String cidFromCodePath(String fullCodePath) {
14279        int eidx = fullCodePath.lastIndexOf("/");
14280        String subStr1 = fullCodePath.substring(0, eidx);
14281        int sidx = subStr1.lastIndexOf("/");
14282        return subStr1.substring(sidx+1, eidx);
14283    }
14284
14285    /**
14286     * Logic to handle installation of ASEC applications, including copying and
14287     * renaming logic.
14288     */
14289    class AsecInstallArgs extends InstallArgs {
14290        static final String RES_FILE_NAME = "pkg.apk";
14291        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14292
14293        String cid;
14294        String packagePath;
14295        String resourcePath;
14296
14297        /** New install */
14298        AsecInstallArgs(InstallParams params) {
14299            super(params.origin, params.move, params.observer, params.installFlags,
14300                    params.installerPackageName, params.volumeUuid,
14301                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14302                    params.grantedRuntimePermissions,
14303                    params.traceMethod, params.traceCookie, params.certificates,
14304                    params.installReason);
14305        }
14306
14307        /** Existing install */
14308        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14309                        boolean isExternal, boolean isForwardLocked) {
14310            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14311                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14312                    instructionSets, null, null, null, 0, null /*certificates*/,
14313                    PackageManager.INSTALL_REASON_UNKNOWN);
14314            // Hackily pretend we're still looking at a full code path
14315            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14316                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14317            }
14318
14319            // Extract cid from fullCodePath
14320            int eidx = fullCodePath.lastIndexOf("/");
14321            String subStr1 = fullCodePath.substring(0, eidx);
14322            int sidx = subStr1.lastIndexOf("/");
14323            cid = subStr1.substring(sidx+1, eidx);
14324            setMountPath(subStr1);
14325        }
14326
14327        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14328            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14329                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14330                    instructionSets, null, null, null, 0, null /*certificates*/,
14331                    PackageManager.INSTALL_REASON_UNKNOWN);
14332            this.cid = cid;
14333            setMountPath(PackageHelper.getSdDir(cid));
14334        }
14335
14336        void createCopyFile() {
14337            cid = mInstallerService.allocateExternalStageCidLegacy();
14338        }
14339
14340        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14341            if (origin.staged && origin.cid != null) {
14342                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14343                cid = origin.cid;
14344                setMountPath(PackageHelper.getSdDir(cid));
14345                return PackageManager.INSTALL_SUCCEEDED;
14346            }
14347
14348            if (temp) {
14349                createCopyFile();
14350            } else {
14351                /*
14352                 * Pre-emptively destroy the container since it's destroyed if
14353                 * copying fails due to it existing anyway.
14354                 */
14355                PackageHelper.destroySdDir(cid);
14356            }
14357
14358            final String newMountPath = imcs.copyPackageToContainer(
14359                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14360                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14361
14362            if (newMountPath != null) {
14363                setMountPath(newMountPath);
14364                return PackageManager.INSTALL_SUCCEEDED;
14365            } else {
14366                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14367            }
14368        }
14369
14370        @Override
14371        String getCodePath() {
14372            return packagePath;
14373        }
14374
14375        @Override
14376        String getResourcePath() {
14377            return resourcePath;
14378        }
14379
14380        int doPreInstall(int status) {
14381            if (status != PackageManager.INSTALL_SUCCEEDED) {
14382                // Destroy container
14383                PackageHelper.destroySdDir(cid);
14384            } else {
14385                boolean mounted = PackageHelper.isContainerMounted(cid);
14386                if (!mounted) {
14387                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14388                            Process.SYSTEM_UID);
14389                    if (newMountPath != null) {
14390                        setMountPath(newMountPath);
14391                    } else {
14392                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14393                    }
14394                }
14395            }
14396            return status;
14397        }
14398
14399        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14400            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14401            String newMountPath = null;
14402            if (PackageHelper.isContainerMounted(cid)) {
14403                // Unmount the container
14404                if (!PackageHelper.unMountSdDir(cid)) {
14405                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14406                    return false;
14407                }
14408            }
14409            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14410                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14411                        " which might be stale. Will try to clean up.");
14412                // Clean up the stale container and proceed to recreate.
14413                if (!PackageHelper.destroySdDir(newCacheId)) {
14414                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14415                    return false;
14416                }
14417                // Successfully cleaned up stale container. Try to rename again.
14418                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14419                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14420                            + " inspite of cleaning it up.");
14421                    return false;
14422                }
14423            }
14424            if (!PackageHelper.isContainerMounted(newCacheId)) {
14425                Slog.w(TAG, "Mounting container " + newCacheId);
14426                newMountPath = PackageHelper.mountSdDir(newCacheId,
14427                        getEncryptKey(), Process.SYSTEM_UID);
14428            } else {
14429                newMountPath = PackageHelper.getSdDir(newCacheId);
14430            }
14431            if (newMountPath == null) {
14432                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14433                return false;
14434            }
14435            Log.i(TAG, "Succesfully renamed " + cid +
14436                    " to " + newCacheId +
14437                    " at new path: " + newMountPath);
14438            cid = newCacheId;
14439
14440            final File beforeCodeFile = new File(packagePath);
14441            setMountPath(newMountPath);
14442            final File afterCodeFile = new File(packagePath);
14443
14444            // Reflect the rename in scanned details
14445            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14446            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14447                    afterCodeFile, pkg.baseCodePath));
14448            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14449                    afterCodeFile, pkg.splitCodePaths));
14450
14451            // Reflect the rename in app info
14452            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14453            pkg.setApplicationInfoCodePath(pkg.codePath);
14454            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14455            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14456            pkg.setApplicationInfoResourcePath(pkg.codePath);
14457            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14458            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14459
14460            return true;
14461        }
14462
14463        private void setMountPath(String mountPath) {
14464            final File mountFile = new File(mountPath);
14465
14466            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14467            if (monolithicFile.exists()) {
14468                packagePath = monolithicFile.getAbsolutePath();
14469                if (isFwdLocked()) {
14470                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14471                } else {
14472                    resourcePath = packagePath;
14473                }
14474            } else {
14475                packagePath = mountFile.getAbsolutePath();
14476                resourcePath = packagePath;
14477            }
14478        }
14479
14480        int doPostInstall(int status, int uid) {
14481            if (status != PackageManager.INSTALL_SUCCEEDED) {
14482                cleanUp();
14483            } else {
14484                final int groupOwner;
14485                final String protectedFile;
14486                if (isFwdLocked()) {
14487                    groupOwner = UserHandle.getSharedAppGid(uid);
14488                    protectedFile = RES_FILE_NAME;
14489                } else {
14490                    groupOwner = -1;
14491                    protectedFile = null;
14492                }
14493
14494                if (uid < Process.FIRST_APPLICATION_UID
14495                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14496                    Slog.e(TAG, "Failed to finalize " + cid);
14497                    PackageHelper.destroySdDir(cid);
14498                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14499                }
14500
14501                boolean mounted = PackageHelper.isContainerMounted(cid);
14502                if (!mounted) {
14503                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14504                }
14505            }
14506            return status;
14507        }
14508
14509        private void cleanUp() {
14510            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14511
14512            // Destroy secure container
14513            PackageHelper.destroySdDir(cid);
14514        }
14515
14516        private List<String> getAllCodePaths() {
14517            final File codeFile = new File(getCodePath());
14518            if (codeFile != null && codeFile.exists()) {
14519                try {
14520                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14521                    return pkg.getAllCodePaths();
14522                } catch (PackageParserException e) {
14523                    // Ignored; we tried our best
14524                }
14525            }
14526            return Collections.EMPTY_LIST;
14527        }
14528
14529        void cleanUpResourcesLI() {
14530            // Enumerate all code paths before deleting
14531            cleanUpResourcesLI(getAllCodePaths());
14532        }
14533
14534        private void cleanUpResourcesLI(List<String> allCodePaths) {
14535            cleanUp();
14536            removeDexFiles(allCodePaths, instructionSets);
14537        }
14538
14539        String getPackageName() {
14540            return getAsecPackageName(cid);
14541        }
14542
14543        boolean doPostDeleteLI(boolean delete) {
14544            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14545            final List<String> allCodePaths = getAllCodePaths();
14546            boolean mounted = PackageHelper.isContainerMounted(cid);
14547            if (mounted) {
14548                // Unmount first
14549                if (PackageHelper.unMountSdDir(cid)) {
14550                    mounted = false;
14551                }
14552            }
14553            if (!mounted && delete) {
14554                cleanUpResourcesLI(allCodePaths);
14555            }
14556            return !mounted;
14557        }
14558
14559        @Override
14560        int doPreCopy() {
14561            if (isFwdLocked()) {
14562                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14563                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14564                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14565                }
14566            }
14567
14568            return PackageManager.INSTALL_SUCCEEDED;
14569        }
14570
14571        @Override
14572        int doPostCopy(int uid) {
14573            if (isFwdLocked()) {
14574                if (uid < Process.FIRST_APPLICATION_UID
14575                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14576                                RES_FILE_NAME)) {
14577                    Slog.e(TAG, "Failed to finalize " + cid);
14578                    PackageHelper.destroySdDir(cid);
14579                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14580                }
14581            }
14582
14583            return PackageManager.INSTALL_SUCCEEDED;
14584        }
14585    }
14586
14587    /**
14588     * Logic to handle movement of existing installed applications.
14589     */
14590    class MoveInstallArgs extends InstallArgs {
14591        private File codeFile;
14592        private File resourceFile;
14593
14594        /** New install */
14595        MoveInstallArgs(InstallParams params) {
14596            super(params.origin, params.move, params.observer, params.installFlags,
14597                    params.installerPackageName, params.volumeUuid,
14598                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14599                    params.grantedRuntimePermissions,
14600                    params.traceMethod, params.traceCookie, params.certificates,
14601                    params.installReason);
14602        }
14603
14604        int copyApk(IMediaContainerService imcs, boolean temp) {
14605            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14606                    + move.fromUuid + " to " + move.toUuid);
14607            synchronized (mInstaller) {
14608                try {
14609                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14610                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14611                } catch (InstallerException e) {
14612                    Slog.w(TAG, "Failed to move app", e);
14613                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14614                }
14615            }
14616
14617            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14618            resourceFile = codeFile;
14619            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14620
14621            return PackageManager.INSTALL_SUCCEEDED;
14622        }
14623
14624        int doPreInstall(int status) {
14625            if (status != PackageManager.INSTALL_SUCCEEDED) {
14626                cleanUp(move.toUuid);
14627            }
14628            return status;
14629        }
14630
14631        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14632            if (status != PackageManager.INSTALL_SUCCEEDED) {
14633                cleanUp(move.toUuid);
14634                return false;
14635            }
14636
14637            // Reflect the move in app info
14638            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14639            pkg.setApplicationInfoCodePath(pkg.codePath);
14640            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14641            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14642            pkg.setApplicationInfoResourcePath(pkg.codePath);
14643            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14644            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14645
14646            return true;
14647        }
14648
14649        int doPostInstall(int status, int uid) {
14650            if (status == PackageManager.INSTALL_SUCCEEDED) {
14651                cleanUp(move.fromUuid);
14652            } else {
14653                cleanUp(move.toUuid);
14654            }
14655            return status;
14656        }
14657
14658        @Override
14659        String getCodePath() {
14660            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14661        }
14662
14663        @Override
14664        String getResourcePath() {
14665            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14666        }
14667
14668        private boolean cleanUp(String volumeUuid) {
14669            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14670                    move.dataAppName);
14671            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14672            final int[] userIds = sUserManager.getUserIds();
14673            synchronized (mInstallLock) {
14674                // Clean up both app data and code
14675                // All package moves are frozen until finished
14676                for (int userId : userIds) {
14677                    try {
14678                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14679                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14680                    } catch (InstallerException e) {
14681                        Slog.w(TAG, String.valueOf(e));
14682                    }
14683                }
14684                removeCodePathLI(codeFile);
14685            }
14686            return true;
14687        }
14688
14689        void cleanUpResourcesLI() {
14690            throw new UnsupportedOperationException();
14691        }
14692
14693        boolean doPostDeleteLI(boolean delete) {
14694            throw new UnsupportedOperationException();
14695        }
14696    }
14697
14698    static String getAsecPackageName(String packageCid) {
14699        int idx = packageCid.lastIndexOf("-");
14700        if (idx == -1) {
14701            return packageCid;
14702        }
14703        return packageCid.substring(0, idx);
14704    }
14705
14706    // Utility method used to create code paths based on package name and available index.
14707    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14708        String idxStr = "";
14709        int idx = 1;
14710        // Fall back to default value of idx=1 if prefix is not
14711        // part of oldCodePath
14712        if (oldCodePath != null) {
14713            String subStr = oldCodePath;
14714            // Drop the suffix right away
14715            if (suffix != null && subStr.endsWith(suffix)) {
14716                subStr = subStr.substring(0, subStr.length() - suffix.length());
14717            }
14718            // If oldCodePath already contains prefix find out the
14719            // ending index to either increment or decrement.
14720            int sidx = subStr.lastIndexOf(prefix);
14721            if (sidx != -1) {
14722                subStr = subStr.substring(sidx + prefix.length());
14723                if (subStr != null) {
14724                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14725                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14726                    }
14727                    try {
14728                        idx = Integer.parseInt(subStr);
14729                        if (idx <= 1) {
14730                            idx++;
14731                        } else {
14732                            idx--;
14733                        }
14734                    } catch(NumberFormatException e) {
14735                    }
14736                }
14737            }
14738        }
14739        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14740        return prefix + idxStr;
14741    }
14742
14743    private File getNextCodePath(File targetDir, String packageName) {
14744        File result;
14745        SecureRandom random = new SecureRandom();
14746        byte[] bytes = new byte[16];
14747        do {
14748            random.nextBytes(bytes);
14749            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14750            result = new File(targetDir, packageName + "-" + suffix);
14751        } while (result.exists());
14752        return result;
14753    }
14754
14755    // Utility method that returns the relative package path with respect
14756    // to the installation directory. Like say for /data/data/com.test-1.apk
14757    // string com.test-1 is returned.
14758    static String deriveCodePathName(String codePath) {
14759        if (codePath == null) {
14760            return null;
14761        }
14762        final File codeFile = new File(codePath);
14763        final String name = codeFile.getName();
14764        if (codeFile.isDirectory()) {
14765            return name;
14766        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14767            final int lastDot = name.lastIndexOf('.');
14768            return name.substring(0, lastDot);
14769        } else {
14770            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14771            return null;
14772        }
14773    }
14774
14775    static class PackageInstalledInfo {
14776        String name;
14777        int uid;
14778        // The set of users that originally had this package installed.
14779        int[] origUsers;
14780        // The set of users that now have this package installed.
14781        int[] newUsers;
14782        PackageParser.Package pkg;
14783        int returnCode;
14784        String returnMsg;
14785        PackageRemovedInfo removedInfo;
14786        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14787
14788        public void setError(int code, String msg) {
14789            setReturnCode(code);
14790            setReturnMessage(msg);
14791            Slog.w(TAG, msg);
14792        }
14793
14794        public void setError(String msg, PackageParserException e) {
14795            setReturnCode(e.error);
14796            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14797            Slog.w(TAG, msg, e);
14798        }
14799
14800        public void setError(String msg, PackageManagerException e) {
14801            returnCode = e.error;
14802            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14803            Slog.w(TAG, msg, e);
14804        }
14805
14806        public void setReturnCode(int returnCode) {
14807            this.returnCode = returnCode;
14808            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14809            for (int i = 0; i < childCount; i++) {
14810                addedChildPackages.valueAt(i).returnCode = returnCode;
14811            }
14812        }
14813
14814        private void setReturnMessage(String returnMsg) {
14815            this.returnMsg = returnMsg;
14816            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14817            for (int i = 0; i < childCount; i++) {
14818                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14819            }
14820        }
14821
14822        // In some error cases we want to convey more info back to the observer
14823        String origPackage;
14824        String origPermission;
14825    }
14826
14827    /*
14828     * Install a non-existing package.
14829     */
14830    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14831            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14832            PackageInstalledInfo res, int installReason) {
14833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14834
14835        // Remember this for later, in case we need to rollback this install
14836        String pkgName = pkg.packageName;
14837
14838        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14839
14840        synchronized(mPackages) {
14841            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14842            if (renamedPackage != null) {
14843                // A package with the same name is already installed, though
14844                // it has been renamed to an older name.  The package we
14845                // are trying to install should be installed as an update to
14846                // the existing one, but that has not been requested, so bail.
14847                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14848                        + " without first uninstalling package running as "
14849                        + renamedPackage);
14850                return;
14851            }
14852            if (mPackages.containsKey(pkgName)) {
14853                // Don't allow installation over an existing package with the same name.
14854                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14855                        + " without first uninstalling.");
14856                return;
14857            }
14858        }
14859
14860        try {
14861            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14862                    System.currentTimeMillis(), user);
14863
14864            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
14865
14866            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14867                prepareAppDataAfterInstallLIF(newPackage);
14868
14869            } else {
14870                // Remove package from internal structures, but keep around any
14871                // data that might have already existed
14872                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14873                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14874            }
14875        } catch (PackageManagerException e) {
14876            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14877        }
14878
14879        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14880    }
14881
14882    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14883        // Can't rotate keys during boot or if sharedUser.
14884        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14885                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14886            return false;
14887        }
14888        // app is using upgradeKeySets; make sure all are valid
14889        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14890        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14891        for (int i = 0; i < upgradeKeySets.length; i++) {
14892            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14893                Slog.wtf(TAG, "Package "
14894                         + (oldPs.name != null ? oldPs.name : "<null>")
14895                         + " contains upgrade-key-set reference to unknown key-set: "
14896                         + upgradeKeySets[i]
14897                         + " reverting to signatures check.");
14898                return false;
14899            }
14900        }
14901        return true;
14902    }
14903
14904    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14905        // Upgrade keysets are being used.  Determine if new package has a superset of the
14906        // required keys.
14907        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14908        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14909        for (int i = 0; i < upgradeKeySets.length; i++) {
14910            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14911            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14912                return true;
14913            }
14914        }
14915        return false;
14916    }
14917
14918    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14919        try (DigestInputStream digestStream =
14920                new DigestInputStream(new FileInputStream(file), digest)) {
14921            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14922        }
14923    }
14924
14925    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14926            UserHandle user, String installerPackageName, PackageInstalledInfo res,
14927            int installReason) {
14928        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14929
14930        final PackageParser.Package oldPackage;
14931        final String pkgName = pkg.packageName;
14932        final int[] allUsers;
14933        final int[] installedUsers;
14934
14935        synchronized(mPackages) {
14936            oldPackage = mPackages.get(pkgName);
14937            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14938
14939            // don't allow upgrade to target a release SDK from a pre-release SDK
14940            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14941                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14942            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14943                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14944            if (oldTargetsPreRelease
14945                    && !newTargetsPreRelease
14946                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14947                Slog.w(TAG, "Can't install package targeting released sdk");
14948                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14949                return;
14950            }
14951
14952            // don't allow an upgrade from full to ephemeral
14953            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14954            if (isEphemeral && !oldIsEphemeral) {
14955                // can't downgrade from full to ephemeral
14956                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14957                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14958                return;
14959            }
14960
14961            // verify signatures are valid
14962            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14963            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14964                if (!checkUpgradeKeySetLP(ps, pkg)) {
14965                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14966                            "New package not signed by keys specified by upgrade-keysets: "
14967                                    + pkgName);
14968                    return;
14969                }
14970            } else {
14971                // default to original signature matching
14972                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14973                        != PackageManager.SIGNATURE_MATCH) {
14974                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14975                            "New package has a different signature: " + pkgName);
14976                    return;
14977                }
14978            }
14979
14980            // don't allow a system upgrade unless the upgrade hash matches
14981            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14982                byte[] digestBytes = null;
14983                try {
14984                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14985                    updateDigest(digest, new File(pkg.baseCodePath));
14986                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14987                        for (String path : pkg.splitCodePaths) {
14988                            updateDigest(digest, new File(path));
14989                        }
14990                    }
14991                    digestBytes = digest.digest();
14992                } catch (NoSuchAlgorithmException | IOException e) {
14993                    res.setError(INSTALL_FAILED_INVALID_APK,
14994                            "Could not compute hash: " + pkgName);
14995                    return;
14996                }
14997                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14998                    res.setError(INSTALL_FAILED_INVALID_APK,
14999                            "New package fails restrict-update check: " + pkgName);
15000                    return;
15001                }
15002                // retain upgrade restriction
15003                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15004            }
15005
15006            // Check for shared user id changes
15007            String invalidPackageName =
15008                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15009            if (invalidPackageName != null) {
15010                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15011                        "Package " + invalidPackageName + " tried to change user "
15012                                + oldPackage.mSharedUserId);
15013                return;
15014            }
15015
15016            // In case of rollback, remember per-user/profile install state
15017            allUsers = sUserManager.getUserIds();
15018            installedUsers = ps.queryInstalledUsers(allUsers, true);
15019        }
15020
15021        // Update what is removed
15022        res.removedInfo = new PackageRemovedInfo();
15023        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15024        res.removedInfo.removedPackage = oldPackage.packageName;
15025        res.removedInfo.isUpdate = true;
15026        res.removedInfo.origUsers = installedUsers;
15027        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15028        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15029        for (int i = 0; i < installedUsers.length; i++) {
15030            final int userId = installedUsers[i];
15031            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15032        }
15033
15034        final int childCount = (oldPackage.childPackages != null)
15035                ? oldPackage.childPackages.size() : 0;
15036        for (int i = 0; i < childCount; i++) {
15037            boolean childPackageUpdated = false;
15038            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15039            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15040            if (res.addedChildPackages != null) {
15041                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15042                if (childRes != null) {
15043                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15044                    childRes.removedInfo.removedPackage = childPkg.packageName;
15045                    childRes.removedInfo.isUpdate = true;
15046                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15047                    childPackageUpdated = true;
15048                }
15049            }
15050            if (!childPackageUpdated) {
15051                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15052                childRemovedRes.removedPackage = childPkg.packageName;
15053                childRemovedRes.isUpdate = false;
15054                childRemovedRes.dataRemoved = true;
15055                synchronized (mPackages) {
15056                    if (childPs != null) {
15057                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15058                    }
15059                }
15060                if (res.removedInfo.removedChildPackages == null) {
15061                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15062                }
15063                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15064            }
15065        }
15066
15067        boolean sysPkg = (isSystemApp(oldPackage));
15068        if (sysPkg) {
15069            // Set the system/privileged flags as needed
15070            final boolean privileged =
15071                    (oldPackage.applicationInfo.privateFlags
15072                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15073            final int systemPolicyFlags = policyFlags
15074                    | PackageParser.PARSE_IS_SYSTEM
15075                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15076
15077            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15078                    user, allUsers, installerPackageName, res, installReason);
15079        } else {
15080            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15081                    user, allUsers, installerPackageName, res, installReason);
15082        }
15083    }
15084
15085    public List<String> getPreviousCodePaths(String packageName) {
15086        final PackageSetting ps = mSettings.mPackages.get(packageName);
15087        final List<String> result = new ArrayList<String>();
15088        if (ps != null && ps.oldCodePaths != null) {
15089            result.addAll(ps.oldCodePaths);
15090        }
15091        return result;
15092    }
15093
15094    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15095            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15096            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15097            int installReason) {
15098        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15099                + deletedPackage);
15100
15101        String pkgName = deletedPackage.packageName;
15102        boolean deletedPkg = true;
15103        boolean addedPkg = false;
15104        boolean updatedSettings = false;
15105        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15106        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15107                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15108
15109        final long origUpdateTime = (pkg.mExtras != null)
15110                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15111
15112        // First delete the existing package while retaining the data directory
15113        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15114                res.removedInfo, true, pkg)) {
15115            // If the existing package wasn't successfully deleted
15116            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15117            deletedPkg = false;
15118        } else {
15119            // Successfully deleted the old package; proceed with replace.
15120
15121            // If deleted package lived in a container, give users a chance to
15122            // relinquish resources before killing.
15123            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15124                if (DEBUG_INSTALL) {
15125                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15126                }
15127                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15128                final ArrayList<String> pkgList = new ArrayList<String>(1);
15129                pkgList.add(deletedPackage.applicationInfo.packageName);
15130                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15131            }
15132
15133            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15134                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15135            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15136
15137            try {
15138                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15139                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15140                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15141                        installReason);
15142
15143                // Update the in-memory copy of the previous code paths.
15144                PackageSetting ps = mSettings.mPackages.get(pkgName);
15145                if (!killApp) {
15146                    if (ps.oldCodePaths == null) {
15147                        ps.oldCodePaths = new ArraySet<>();
15148                    }
15149                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15150                    if (deletedPackage.splitCodePaths != null) {
15151                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15152                    }
15153                } else {
15154                    ps.oldCodePaths = null;
15155                }
15156                if (ps.childPackageNames != null) {
15157                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15158                        final String childPkgName = ps.childPackageNames.get(i);
15159                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15160                        childPs.oldCodePaths = ps.oldCodePaths;
15161                    }
15162                }
15163                prepareAppDataAfterInstallLIF(newPackage);
15164                addedPkg = true;
15165            } catch (PackageManagerException e) {
15166                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15167            }
15168        }
15169
15170        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15171            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15172
15173            // Revert all internal state mutations and added folders for the failed install
15174            if (addedPkg) {
15175                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15176                        res.removedInfo, true, null);
15177            }
15178
15179            // Restore the old package
15180            if (deletedPkg) {
15181                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15182                File restoreFile = new File(deletedPackage.codePath);
15183                // Parse old package
15184                boolean oldExternal = isExternal(deletedPackage);
15185                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15186                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15187                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15188                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15189                try {
15190                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15191                            null);
15192                } catch (PackageManagerException e) {
15193                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15194                            + e.getMessage());
15195                    return;
15196                }
15197
15198                synchronized (mPackages) {
15199                    // Ensure the installer package name up to date
15200                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15201
15202                    // Update permissions for restored package
15203                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15204
15205                    mSettings.writeLPr();
15206                }
15207
15208                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15209            }
15210        } else {
15211            synchronized (mPackages) {
15212                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15213                if (ps != null) {
15214                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15215                    if (res.removedInfo.removedChildPackages != null) {
15216                        final int childCount = res.removedInfo.removedChildPackages.size();
15217                        // Iterate in reverse as we may modify the collection
15218                        for (int i = childCount - 1; i >= 0; i--) {
15219                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15220                            if (res.addedChildPackages.containsKey(childPackageName)) {
15221                                res.removedInfo.removedChildPackages.removeAt(i);
15222                            } else {
15223                                PackageRemovedInfo childInfo = res.removedInfo
15224                                        .removedChildPackages.valueAt(i);
15225                                childInfo.removedForAllUsers = mPackages.get(
15226                                        childInfo.removedPackage) == null;
15227                            }
15228                        }
15229                    }
15230                }
15231            }
15232        }
15233    }
15234
15235    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15236            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15237            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15238            int installReason) {
15239        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15240                + ", old=" + deletedPackage);
15241
15242        final boolean disabledSystem;
15243
15244        // Remove existing system package
15245        removePackageLI(deletedPackage, true);
15246
15247        synchronized (mPackages) {
15248            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15249        }
15250        if (!disabledSystem) {
15251            // We didn't need to disable the .apk as a current system package,
15252            // which means we are replacing another update that is already
15253            // installed.  We need to make sure to delete the older one's .apk.
15254            res.removedInfo.args = createInstallArgsForExisting(0,
15255                    deletedPackage.applicationInfo.getCodePath(),
15256                    deletedPackage.applicationInfo.getResourcePath(),
15257                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15258        } else {
15259            res.removedInfo.args = null;
15260        }
15261
15262        // Successfully disabled the old package. Now proceed with re-installation
15263        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15264                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15265        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15266
15267        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15268        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15269                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15270
15271        PackageParser.Package newPackage = null;
15272        try {
15273            // Add the package to the internal data structures
15274            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15275
15276            // Set the update and install times
15277            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15278            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15279                    System.currentTimeMillis());
15280
15281            // Update the package dynamic state if succeeded
15282            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15283                // Now that the install succeeded make sure we remove data
15284                // directories for any child package the update removed.
15285                final int deletedChildCount = (deletedPackage.childPackages != null)
15286                        ? deletedPackage.childPackages.size() : 0;
15287                final int newChildCount = (newPackage.childPackages != null)
15288                        ? newPackage.childPackages.size() : 0;
15289                for (int i = 0; i < deletedChildCount; i++) {
15290                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15291                    boolean childPackageDeleted = true;
15292                    for (int j = 0; j < newChildCount; j++) {
15293                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15294                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15295                            childPackageDeleted = false;
15296                            break;
15297                        }
15298                    }
15299                    if (childPackageDeleted) {
15300                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15301                                deletedChildPkg.packageName);
15302                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15303                            PackageRemovedInfo removedChildRes = res.removedInfo
15304                                    .removedChildPackages.get(deletedChildPkg.packageName);
15305                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15306                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15307                        }
15308                    }
15309                }
15310
15311                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15312                        installReason);
15313                prepareAppDataAfterInstallLIF(newPackage);
15314            }
15315        } catch (PackageManagerException e) {
15316            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15317            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15318        }
15319
15320        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15321            // Re installation failed. Restore old information
15322            // Remove new pkg information
15323            if (newPackage != null) {
15324                removeInstalledPackageLI(newPackage, true);
15325            }
15326            // Add back the old system package
15327            try {
15328                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15329            } catch (PackageManagerException e) {
15330                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15331            }
15332
15333            synchronized (mPackages) {
15334                if (disabledSystem) {
15335                    enableSystemPackageLPw(deletedPackage);
15336                }
15337
15338                // Ensure the installer package name up to date
15339                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15340
15341                // Update permissions for restored package
15342                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15343
15344                mSettings.writeLPr();
15345            }
15346
15347            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15348                    + " after failed upgrade");
15349        }
15350    }
15351
15352    /**
15353     * Checks whether the parent or any of the child packages have a change shared
15354     * user. For a package to be a valid update the shred users of the parent and
15355     * the children should match. We may later support changing child shared users.
15356     * @param oldPkg The updated package.
15357     * @param newPkg The update package.
15358     * @return The shared user that change between the versions.
15359     */
15360    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15361            PackageParser.Package newPkg) {
15362        // Check parent shared user
15363        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15364            return newPkg.packageName;
15365        }
15366        // Check child shared users
15367        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15368        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15369        for (int i = 0; i < newChildCount; i++) {
15370            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15371            // If this child was present, did it have the same shared user?
15372            for (int j = 0; j < oldChildCount; j++) {
15373                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15374                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15375                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15376                    return newChildPkg.packageName;
15377                }
15378            }
15379        }
15380        return null;
15381    }
15382
15383    private void removeNativeBinariesLI(PackageSetting ps) {
15384        // Remove the lib path for the parent package
15385        if (ps != null) {
15386            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15387            // Remove the lib path for the child packages
15388            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15389            for (int i = 0; i < childCount; i++) {
15390                PackageSetting childPs = null;
15391                synchronized (mPackages) {
15392                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15393                }
15394                if (childPs != null) {
15395                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15396                            .legacyNativeLibraryPathString);
15397                }
15398            }
15399        }
15400    }
15401
15402    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15403        // Enable the parent package
15404        mSettings.enableSystemPackageLPw(pkg.packageName);
15405        // Enable the child packages
15406        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15407        for (int i = 0; i < childCount; i++) {
15408            PackageParser.Package childPkg = pkg.childPackages.get(i);
15409            mSettings.enableSystemPackageLPw(childPkg.packageName);
15410        }
15411    }
15412
15413    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15414            PackageParser.Package newPkg) {
15415        // Disable the parent package (parent always replaced)
15416        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15417        // Disable the child packages
15418        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15419        for (int i = 0; i < childCount; i++) {
15420            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15421            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15422            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15423        }
15424        return disabled;
15425    }
15426
15427    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15428            String installerPackageName) {
15429        // Enable the parent package
15430        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15431        // Enable the child packages
15432        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15433        for (int i = 0; i < childCount; i++) {
15434            PackageParser.Package childPkg = pkg.childPackages.get(i);
15435            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15436        }
15437    }
15438
15439    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15440        // Collect all used permissions in the UID
15441        ArraySet<String> usedPermissions = new ArraySet<>();
15442        final int packageCount = su.packages.size();
15443        for (int i = 0; i < packageCount; i++) {
15444            PackageSetting ps = su.packages.valueAt(i);
15445            if (ps.pkg == null) {
15446                continue;
15447            }
15448            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15449            for (int j = 0; j < requestedPermCount; j++) {
15450                String permission = ps.pkg.requestedPermissions.get(j);
15451                BasePermission bp = mSettings.mPermissions.get(permission);
15452                if (bp != null) {
15453                    usedPermissions.add(permission);
15454                }
15455            }
15456        }
15457
15458        PermissionsState permissionsState = su.getPermissionsState();
15459        // Prune install permissions
15460        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15461        final int installPermCount = installPermStates.size();
15462        for (int i = installPermCount - 1; i >= 0;  i--) {
15463            PermissionState permissionState = installPermStates.get(i);
15464            if (!usedPermissions.contains(permissionState.getName())) {
15465                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15466                if (bp != null) {
15467                    permissionsState.revokeInstallPermission(bp);
15468                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15469                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15470                }
15471            }
15472        }
15473
15474        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15475
15476        // Prune runtime permissions
15477        for (int userId : allUserIds) {
15478            List<PermissionState> runtimePermStates = permissionsState
15479                    .getRuntimePermissionStates(userId);
15480            final int runtimePermCount = runtimePermStates.size();
15481            for (int i = runtimePermCount - 1; i >= 0; i--) {
15482                PermissionState permissionState = runtimePermStates.get(i);
15483                if (!usedPermissions.contains(permissionState.getName())) {
15484                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15485                    if (bp != null) {
15486                        permissionsState.revokeRuntimePermission(bp, userId);
15487                        permissionsState.updatePermissionFlags(bp, userId,
15488                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15489                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15490                                runtimePermissionChangedUserIds, userId);
15491                    }
15492                }
15493            }
15494        }
15495
15496        return runtimePermissionChangedUserIds;
15497    }
15498
15499    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15500            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15501        // Update the parent package setting
15502        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15503                res, user, installReason);
15504        // Update the child packages setting
15505        final int childCount = (newPackage.childPackages != null)
15506                ? newPackage.childPackages.size() : 0;
15507        for (int i = 0; i < childCount; i++) {
15508            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15509            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15510            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15511                    childRes.origUsers, childRes, user, installReason);
15512        }
15513    }
15514
15515    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15516            String installerPackageName, int[] allUsers, int[] installedForUsers,
15517            PackageInstalledInfo res, UserHandle user, int installReason) {
15518        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15519
15520        String pkgName = newPackage.packageName;
15521        synchronized (mPackages) {
15522            //write settings. the installStatus will be incomplete at this stage.
15523            //note that the new package setting would have already been
15524            //added to mPackages. It hasn't been persisted yet.
15525            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15526            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15527            mSettings.writeLPr();
15528            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15529        }
15530
15531        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15532        synchronized (mPackages) {
15533            updatePermissionsLPw(newPackage.packageName, newPackage,
15534                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15535                            ? UPDATE_PERMISSIONS_ALL : 0));
15536            // For system-bundled packages, we assume that installing an upgraded version
15537            // of the package implies that the user actually wants to run that new code,
15538            // so we enable the package.
15539            PackageSetting ps = mSettings.mPackages.get(pkgName);
15540            final int userId = user.getIdentifier();
15541            if (ps != null) {
15542                if (isSystemApp(newPackage)) {
15543                    if (DEBUG_INSTALL) {
15544                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15545                    }
15546                    // Enable system package for requested users
15547                    if (res.origUsers != null) {
15548                        for (int origUserId : res.origUsers) {
15549                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15550                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15551                                        origUserId, installerPackageName);
15552                            }
15553                        }
15554                    }
15555                    // Also convey the prior install/uninstall state
15556                    if (allUsers != null && installedForUsers != null) {
15557                        for (int currentUserId : allUsers) {
15558                            final boolean installed = ArrayUtils.contains(
15559                                    installedForUsers, currentUserId);
15560                            if (DEBUG_INSTALL) {
15561                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15562                            }
15563                            ps.setInstalled(installed, currentUserId);
15564                        }
15565                        // these install state changes will be persisted in the
15566                        // upcoming call to mSettings.writeLPr().
15567                    }
15568                }
15569                // It's implied that when a user requests installation, they want the app to be
15570                // installed and enabled.
15571                if (userId != UserHandle.USER_ALL) {
15572                    ps.setInstalled(true, userId);
15573                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15574                }
15575
15576                // When replacing an existing package, preserve the original install reason for all
15577                // users that had the package installed before.
15578                final Set<Integer> previousUserIds = new ArraySet<>();
15579                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
15580                    final int installReasonCount = res.removedInfo.installReasons.size();
15581                    for (int i = 0; i < installReasonCount; i++) {
15582                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
15583                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
15584                        ps.setInstallReason(previousInstallReason, previousUserId);
15585                        previousUserIds.add(previousUserId);
15586                    }
15587                }
15588
15589                // Set install reason for users that are having the package newly installed.
15590                if (userId == UserHandle.USER_ALL) {
15591                    for (int currentUserId : sUserManager.getUserIds()) {
15592                        if (!previousUserIds.contains(currentUserId)) {
15593                            ps.setInstallReason(installReason, currentUserId);
15594                        }
15595                    }
15596                } else if (!previousUserIds.contains(userId)) {
15597                    ps.setInstallReason(installReason, userId);
15598                }
15599            }
15600            res.name = pkgName;
15601            res.uid = newPackage.applicationInfo.uid;
15602            res.pkg = newPackage;
15603            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15604            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15605            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15606            //to update install status
15607            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15608            mSettings.writeLPr();
15609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15610        }
15611
15612        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15613    }
15614
15615    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15616        try {
15617            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15618            installPackageLI(args, res);
15619        } finally {
15620            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15621        }
15622    }
15623
15624    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15625        final int installFlags = args.installFlags;
15626        final String installerPackageName = args.installerPackageName;
15627        final String volumeUuid = args.volumeUuid;
15628        final File tmpPackageFile = new File(args.getCodePath());
15629        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15630        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15631                || (args.volumeUuid != null));
15632        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15633        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15634        boolean replace = false;
15635        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15636        if (args.move != null) {
15637            // moving a complete application; perform an initial scan on the new install location
15638            scanFlags |= SCAN_INITIAL;
15639        }
15640        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15641            scanFlags |= SCAN_DONT_KILL_APP;
15642        }
15643
15644        // Result object to be returned
15645        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15646
15647        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15648
15649        // Sanity check
15650        if (ephemeral && (forwardLocked || onExternal)) {
15651            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15652                    + " external=" + onExternal);
15653            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15654            return;
15655        }
15656
15657        // Retrieve PackageSettings and parse package
15658        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15659                | PackageParser.PARSE_ENFORCE_CODE
15660                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15661                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15662                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15663                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15664        PackageParser pp = new PackageParser();
15665        pp.setSeparateProcesses(mSeparateProcesses);
15666        pp.setDisplayMetrics(mMetrics);
15667
15668        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15669        final PackageParser.Package pkg;
15670        try {
15671            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15672        } catch (PackageParserException e) {
15673            res.setError("Failed parse during installPackageLI", e);
15674            return;
15675        } finally {
15676            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15677        }
15678
15679        // Ephemeral apps must have target SDK >= O.
15680        // TODO: Update conditional and error message when O gets locked down
15681        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15682            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15683                    "Ephemeral apps must have target SDK version of at least O");
15684            return;
15685        }
15686
15687        // If we are installing a clustered package add results for the children
15688        if (pkg.childPackages != null) {
15689            synchronized (mPackages) {
15690                final int childCount = pkg.childPackages.size();
15691                for (int i = 0; i < childCount; i++) {
15692                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15693                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15694                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15695                    childRes.pkg = childPkg;
15696                    childRes.name = childPkg.packageName;
15697                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15698                    if (childPs != null) {
15699                        childRes.origUsers = childPs.queryInstalledUsers(
15700                                sUserManager.getUserIds(), true);
15701                    }
15702                    if ((mPackages.containsKey(childPkg.packageName))) {
15703                        childRes.removedInfo = new PackageRemovedInfo();
15704                        childRes.removedInfo.removedPackage = childPkg.packageName;
15705                    }
15706                    if (res.addedChildPackages == null) {
15707                        res.addedChildPackages = new ArrayMap<>();
15708                    }
15709                    res.addedChildPackages.put(childPkg.packageName, childRes);
15710                }
15711            }
15712        }
15713
15714        // If package doesn't declare API override, mark that we have an install
15715        // time CPU ABI override.
15716        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15717            pkg.cpuAbiOverride = args.abiOverride;
15718        }
15719
15720        String pkgName = res.name = pkg.packageName;
15721        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15722            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15723                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15724                return;
15725            }
15726        }
15727
15728        try {
15729            // either use what we've been given or parse directly from the APK
15730            if (args.certificates != null) {
15731                try {
15732                    PackageParser.populateCertificates(pkg, args.certificates);
15733                } catch (PackageParserException e) {
15734                    // there was something wrong with the certificates we were given;
15735                    // try to pull them from the APK
15736                    PackageParser.collectCertificates(pkg, parseFlags);
15737                }
15738            } else {
15739                PackageParser.collectCertificates(pkg, parseFlags);
15740            }
15741        } catch (PackageParserException e) {
15742            res.setError("Failed collect during installPackageLI", e);
15743            return;
15744        }
15745
15746        // Get rid of all references to package scan path via parser.
15747        pp = null;
15748        String oldCodePath = null;
15749        boolean systemApp = false;
15750        synchronized (mPackages) {
15751            // Check if installing already existing package
15752            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15753                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15754                if (pkg.mOriginalPackages != null
15755                        && pkg.mOriginalPackages.contains(oldName)
15756                        && mPackages.containsKey(oldName)) {
15757                    // This package is derived from an original package,
15758                    // and this device has been updating from that original
15759                    // name.  We must continue using the original name, so
15760                    // rename the new package here.
15761                    pkg.setPackageName(oldName);
15762                    pkgName = pkg.packageName;
15763                    replace = true;
15764                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15765                            + oldName + " pkgName=" + pkgName);
15766                } else if (mPackages.containsKey(pkgName)) {
15767                    // This package, under its official name, already exists
15768                    // on the device; we should replace it.
15769                    replace = true;
15770                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15771                }
15772
15773                // Child packages are installed through the parent package
15774                if (pkg.parentPackage != null) {
15775                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15776                            "Package " + pkg.packageName + " is child of package "
15777                                    + pkg.parentPackage.parentPackage + ". Child packages "
15778                                    + "can be updated only through the parent package.");
15779                    return;
15780                }
15781
15782                if (replace) {
15783                    // Prevent apps opting out from runtime permissions
15784                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15785                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15786                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15787                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15788                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15789                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15790                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15791                                        + " doesn't support runtime permissions but the old"
15792                                        + " target SDK " + oldTargetSdk + " does.");
15793                        return;
15794                    }
15795
15796                    // Prevent installing of child packages
15797                    if (oldPackage.parentPackage != null) {
15798                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15799                                "Package " + pkg.packageName + " is child of package "
15800                                        + oldPackage.parentPackage + ". Child packages "
15801                                        + "can be updated only through the parent package.");
15802                        return;
15803                    }
15804                }
15805            }
15806
15807            PackageSetting ps = mSettings.mPackages.get(pkgName);
15808            if (ps != null) {
15809                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15810
15811                // Quick sanity check that we're signed correctly if updating;
15812                // we'll check this again later when scanning, but we want to
15813                // bail early here before tripping over redefined permissions.
15814                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15815                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15816                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15817                                + pkg.packageName + " upgrade keys do not match the "
15818                                + "previously installed version");
15819                        return;
15820                    }
15821                } else {
15822                    try {
15823                        verifySignaturesLP(ps, pkg);
15824                    } catch (PackageManagerException e) {
15825                        res.setError(e.error, e.getMessage());
15826                        return;
15827                    }
15828                }
15829
15830                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15831                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15832                    systemApp = (ps.pkg.applicationInfo.flags &
15833                            ApplicationInfo.FLAG_SYSTEM) != 0;
15834                }
15835                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15836            }
15837
15838            // Check whether the newly-scanned package wants to define an already-defined perm
15839            int N = pkg.permissions.size();
15840            for (int i = N-1; i >= 0; i--) {
15841                PackageParser.Permission perm = pkg.permissions.get(i);
15842                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15843                if (bp != null) {
15844                    // If the defining package is signed with our cert, it's okay.  This
15845                    // also includes the "updating the same package" case, of course.
15846                    // "updating same package" could also involve key-rotation.
15847                    final boolean sigsOk;
15848                    if (bp.sourcePackage.equals(pkg.packageName)
15849                            && (bp.packageSetting instanceof PackageSetting)
15850                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15851                                    scanFlags))) {
15852                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15853                    } else {
15854                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15855                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15856                    }
15857                    if (!sigsOk) {
15858                        // If the owning package is the system itself, we log but allow
15859                        // install to proceed; we fail the install on all other permission
15860                        // redefinitions.
15861                        if (!bp.sourcePackage.equals("android")) {
15862                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15863                                    + pkg.packageName + " attempting to redeclare permission "
15864                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15865                            res.origPermission = perm.info.name;
15866                            res.origPackage = bp.sourcePackage;
15867                            return;
15868                        } else {
15869                            Slog.w(TAG, "Package " + pkg.packageName
15870                                    + " attempting to redeclare system permission "
15871                                    + perm.info.name + "; ignoring new declaration");
15872                            pkg.permissions.remove(i);
15873                        }
15874                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
15875                        // Prevent apps to change protection level to dangerous from any other
15876                        // type as this would allow a privilege escalation where an app adds a
15877                        // normal/signature permission in other app's group and later redefines
15878                        // it as dangerous leading to the group auto-grant.
15879                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
15880                                == PermissionInfo.PROTECTION_DANGEROUS) {
15881                            if (bp != null && !bp.isRuntime()) {
15882                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
15883                                        + "non-runtime permission " + perm.info.name
15884                                        + " to runtime; keeping old protection level");
15885                                perm.info.protectionLevel = bp.protectionLevel;
15886                            }
15887                        }
15888                    }
15889                }
15890            }
15891        }
15892
15893        if (systemApp) {
15894            if (onExternal) {
15895                // Abort update; system app can't be replaced with app on sdcard
15896                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15897                        "Cannot install updates to system apps on sdcard");
15898                return;
15899            } else if (ephemeral) {
15900                // Abort update; system app can't be replaced with an ephemeral app
15901                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15902                        "Cannot update a system app with an ephemeral app");
15903                return;
15904            }
15905        }
15906
15907        if (args.move != null) {
15908            // We did an in-place move, so dex is ready to roll
15909            scanFlags |= SCAN_NO_DEX;
15910            scanFlags |= SCAN_MOVE;
15911
15912            synchronized (mPackages) {
15913                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15914                if (ps == null) {
15915                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15916                            "Missing settings for moved package " + pkgName);
15917                }
15918
15919                // We moved the entire application as-is, so bring over the
15920                // previously derived ABI information.
15921                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15922                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15923            }
15924
15925        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15926            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15927            scanFlags |= SCAN_NO_DEX;
15928
15929            try {
15930                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15931                    args.abiOverride : pkg.cpuAbiOverride);
15932                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15933                        true /*extractLibs*/, mAppLib32InstallDir);
15934            } catch (PackageManagerException pme) {
15935                Slog.e(TAG, "Error deriving application ABI", pme);
15936                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15937                return;
15938            }
15939
15940            // Shared libraries for the package need to be updated.
15941            synchronized (mPackages) {
15942                try {
15943                    updateSharedLibrariesLPr(pkg, null);
15944                } catch (PackageManagerException e) {
15945                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15946                }
15947            }
15948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15949            // Do not run PackageDexOptimizer through the local performDexOpt
15950            // method because `pkg` may not be in `mPackages` yet.
15951            //
15952            // Also, don't fail application installs if the dexopt step fails.
15953            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15954                    null /* instructionSets */, false /* checkProfiles */,
15955                    getCompilerFilterForReason(REASON_INSTALL),
15956                    getOrCreateCompilerPackageStats(pkg));
15957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15958
15959            // Notify BackgroundDexOptService that the package has been changed.
15960            // If this is an update of a package which used to fail to compile,
15961            // BDOS will remove it from its blacklist.
15962            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15963        }
15964
15965        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15966            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15967            return;
15968        }
15969
15970        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15971
15972        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15973                "installPackageLI")) {
15974            if (replace) {
15975                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15976                        installerPackageName, res, args.installReason);
15977            } else {
15978                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15979                        args.user, installerPackageName, volumeUuid, res, args.installReason);
15980            }
15981        }
15982        synchronized (mPackages) {
15983            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15984            if (ps != null) {
15985                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15986            }
15987
15988            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15989            for (int i = 0; i < childCount; i++) {
15990                PackageParser.Package childPkg = pkg.childPackages.get(i);
15991                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15992                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15993                if (childPs != null) {
15994                    childRes.newUsers = childPs.queryInstalledUsers(
15995                            sUserManager.getUserIds(), true);
15996                }
15997            }
15998        }
15999    }
16000
16001    private void startIntentFilterVerifications(int userId, boolean replacing,
16002            PackageParser.Package pkg) {
16003        if (mIntentFilterVerifierComponent == null) {
16004            Slog.w(TAG, "No IntentFilter verification will not be done as "
16005                    + "there is no IntentFilterVerifier available!");
16006            return;
16007        }
16008
16009        final int verifierUid = getPackageUid(
16010                mIntentFilterVerifierComponent.getPackageName(),
16011                MATCH_DEBUG_TRIAGED_MISSING,
16012                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16013
16014        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16015        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16016        mHandler.sendMessage(msg);
16017
16018        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16019        for (int i = 0; i < childCount; i++) {
16020            PackageParser.Package childPkg = pkg.childPackages.get(i);
16021            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16022            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16023            mHandler.sendMessage(msg);
16024        }
16025    }
16026
16027    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16028            PackageParser.Package pkg) {
16029        int size = pkg.activities.size();
16030        if (size == 0) {
16031            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16032                    "No activity, so no need to verify any IntentFilter!");
16033            return;
16034        }
16035
16036        final boolean hasDomainURLs = hasDomainURLs(pkg);
16037        if (!hasDomainURLs) {
16038            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16039                    "No domain URLs, so no need to verify any IntentFilter!");
16040            return;
16041        }
16042
16043        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16044                + " if any IntentFilter from the " + size
16045                + " Activities needs verification ...");
16046
16047        int count = 0;
16048        final String packageName = pkg.packageName;
16049
16050        synchronized (mPackages) {
16051            // If this is a new install and we see that we've already run verification for this
16052            // package, we have nothing to do: it means the state was restored from backup.
16053            if (!replacing) {
16054                IntentFilterVerificationInfo ivi =
16055                        mSettings.getIntentFilterVerificationLPr(packageName);
16056                if (ivi != null) {
16057                    if (DEBUG_DOMAIN_VERIFICATION) {
16058                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16059                                + ivi.getStatusString());
16060                    }
16061                    return;
16062                }
16063            }
16064
16065            // If any filters need to be verified, then all need to be.
16066            boolean needToVerify = false;
16067            for (PackageParser.Activity a : pkg.activities) {
16068                for (ActivityIntentInfo filter : a.intents) {
16069                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16070                        if (DEBUG_DOMAIN_VERIFICATION) {
16071                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16072                        }
16073                        needToVerify = true;
16074                        break;
16075                    }
16076                }
16077            }
16078
16079            if (needToVerify) {
16080                final int verificationId = mIntentFilterVerificationToken++;
16081                for (PackageParser.Activity a : pkg.activities) {
16082                    for (ActivityIntentInfo filter : a.intents) {
16083                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16084                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16085                                    "Verification needed for IntentFilter:" + filter.toString());
16086                            mIntentFilterVerifier.addOneIntentFilterVerification(
16087                                    verifierUid, userId, verificationId, filter, packageName);
16088                            count++;
16089                        }
16090                    }
16091                }
16092            }
16093        }
16094
16095        if (count > 0) {
16096            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16097                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16098                    +  " for userId:" + userId);
16099            mIntentFilterVerifier.startVerifications(userId);
16100        } else {
16101            if (DEBUG_DOMAIN_VERIFICATION) {
16102                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16103            }
16104        }
16105    }
16106
16107    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16108        final ComponentName cn  = filter.activity.getComponentName();
16109        final String packageName = cn.getPackageName();
16110
16111        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16112                packageName);
16113        if (ivi == null) {
16114            return true;
16115        }
16116        int status = ivi.getStatus();
16117        switch (status) {
16118            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16119            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16120                return true;
16121
16122            default:
16123                // Nothing to do
16124                return false;
16125        }
16126    }
16127
16128    private static boolean isMultiArch(ApplicationInfo info) {
16129        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16130    }
16131
16132    private static boolean isExternal(PackageParser.Package pkg) {
16133        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16134    }
16135
16136    private static boolean isExternal(PackageSetting ps) {
16137        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16138    }
16139
16140    private static boolean isEphemeral(PackageParser.Package pkg) {
16141        return pkg.applicationInfo.isEphemeralApp();
16142    }
16143
16144    private static boolean isEphemeral(PackageSetting ps) {
16145        return ps.pkg != null && isEphemeral(ps.pkg);
16146    }
16147
16148    private static boolean isSystemApp(PackageParser.Package pkg) {
16149        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16150    }
16151
16152    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16153        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16154    }
16155
16156    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16157        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16158    }
16159
16160    private static boolean isSystemApp(PackageSetting ps) {
16161        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16162    }
16163
16164    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16165        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16166    }
16167
16168    private int packageFlagsToInstallFlags(PackageSetting ps) {
16169        int installFlags = 0;
16170        if (isEphemeral(ps)) {
16171            installFlags |= PackageManager.INSTALL_EPHEMERAL;
16172        }
16173        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16174            // This existing package was an external ASEC install when we have
16175            // the external flag without a UUID
16176            installFlags |= PackageManager.INSTALL_EXTERNAL;
16177        }
16178        if (ps.isForwardLocked()) {
16179            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16180        }
16181        return installFlags;
16182    }
16183
16184    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
16185        if (isExternal(pkg)) {
16186            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16187                return StorageManager.UUID_PRIMARY_PHYSICAL;
16188            } else {
16189                return pkg.volumeUuid;
16190            }
16191        } else {
16192            return StorageManager.UUID_PRIVATE_INTERNAL;
16193        }
16194    }
16195
16196    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16197        if (isExternal(pkg)) {
16198            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16199                return mSettings.getExternalVersion();
16200            } else {
16201                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16202            }
16203        } else {
16204            return mSettings.getInternalVersion();
16205        }
16206    }
16207
16208    private void deleteTempPackageFiles() {
16209        final FilenameFilter filter = new FilenameFilter() {
16210            public boolean accept(File dir, String name) {
16211                return name.startsWith("vmdl") && name.endsWith(".tmp");
16212            }
16213        };
16214        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16215            file.delete();
16216        }
16217    }
16218
16219    @Override
16220    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
16221            int flags) {
16222        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16223                flags);
16224    }
16225
16226    @Override
16227    public void deletePackage(final String packageName,
16228            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16229        mContext.enforceCallingOrSelfPermission(
16230                android.Manifest.permission.DELETE_PACKAGES, null);
16231        Preconditions.checkNotNull(packageName);
16232        Preconditions.checkNotNull(observer);
16233        final int uid = Binder.getCallingUid();
16234        if (!isOrphaned(packageName)
16235                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16236            try {
16237                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16238                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16239                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16240                observer.onUserActionRequired(intent);
16241            } catch (RemoteException re) {
16242            }
16243            return;
16244        }
16245        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16246        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16247        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16248            mContext.enforceCallingOrSelfPermission(
16249                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16250                    "deletePackage for user " + userId);
16251        }
16252
16253        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16254            try {
16255                observer.onPackageDeleted(packageName,
16256                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16257            } catch (RemoteException re) {
16258            }
16259            return;
16260        }
16261
16262        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16263            try {
16264                observer.onPackageDeleted(packageName,
16265                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16266            } catch (RemoteException re) {
16267            }
16268            return;
16269        }
16270
16271        if (DEBUG_REMOVE) {
16272            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16273                    + " deleteAllUsers: " + deleteAllUsers );
16274        }
16275        // Queue up an async operation since the package deletion may take a little while.
16276        mHandler.post(new Runnable() {
16277            public void run() {
16278                mHandler.removeCallbacks(this);
16279                int returnCode;
16280                if (!deleteAllUsers) {
16281                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16282                } else {
16283                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16284                    // If nobody is blocking uninstall, proceed with delete for all users
16285                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16286                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16287                    } else {
16288                        // Otherwise uninstall individually for users with blockUninstalls=false
16289                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16290                        for (int userId : users) {
16291                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16292                                returnCode = deletePackageX(packageName, userId, userFlags);
16293                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16294                                    Slog.w(TAG, "Package delete failed for user " + userId
16295                                            + ", returnCode " + returnCode);
16296                                }
16297                            }
16298                        }
16299                        // The app has only been marked uninstalled for certain users.
16300                        // We still need to report that delete was blocked
16301                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16302                    }
16303                }
16304                try {
16305                    observer.onPackageDeleted(packageName, returnCode, null);
16306                } catch (RemoteException e) {
16307                    Log.i(TAG, "Observer no longer exists.");
16308                } //end catch
16309            } //end run
16310        });
16311    }
16312
16313    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16314        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16315              || callingUid == Process.SYSTEM_UID) {
16316            return true;
16317        }
16318        final int callingUserId = UserHandle.getUserId(callingUid);
16319        // If the caller installed the pkgName, then allow it to silently uninstall.
16320        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16321            return true;
16322        }
16323
16324        // Allow package verifier to silently uninstall.
16325        if (mRequiredVerifierPackage != null &&
16326                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16327            return true;
16328        }
16329
16330        // Allow package uninstaller to silently uninstall.
16331        if (mRequiredUninstallerPackage != null &&
16332                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16333            return true;
16334        }
16335
16336        // Allow storage manager to silently uninstall.
16337        if (mStorageManagerPackage != null &&
16338                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16339            return true;
16340        }
16341        return false;
16342    }
16343
16344    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16345        int[] result = EMPTY_INT_ARRAY;
16346        for (int userId : userIds) {
16347            if (getBlockUninstallForUser(packageName, userId)) {
16348                result = ArrayUtils.appendInt(result, userId);
16349            }
16350        }
16351        return result;
16352    }
16353
16354    @Override
16355    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16356        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16357    }
16358
16359    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16360        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16361                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16362        try {
16363            if (dpm != null) {
16364                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16365                        /* callingUserOnly =*/ false);
16366                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16367                        : deviceOwnerComponentName.getPackageName();
16368                // Does the package contains the device owner?
16369                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16370                // this check is probably not needed, since DO should be registered as a device
16371                // admin on some user too. (Original bug for this: b/17657954)
16372                if (packageName.equals(deviceOwnerPackageName)) {
16373                    return true;
16374                }
16375                // Does it contain a device admin for any user?
16376                int[] users;
16377                if (userId == UserHandle.USER_ALL) {
16378                    users = sUserManager.getUserIds();
16379                } else {
16380                    users = new int[]{userId};
16381                }
16382                for (int i = 0; i < users.length; ++i) {
16383                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16384                        return true;
16385                    }
16386                }
16387            }
16388        } catch (RemoteException e) {
16389        }
16390        return false;
16391    }
16392
16393    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16394        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16395    }
16396
16397    /**
16398     *  This method is an internal method that could be get invoked either
16399     *  to delete an installed package or to clean up a failed installation.
16400     *  After deleting an installed package, a broadcast is sent to notify any
16401     *  listeners that the package has been removed. For cleaning up a failed
16402     *  installation, the broadcast is not necessary since the package's
16403     *  installation wouldn't have sent the initial broadcast either
16404     *  The key steps in deleting a package are
16405     *  deleting the package information in internal structures like mPackages,
16406     *  deleting the packages base directories through installd
16407     *  updating mSettings to reflect current status
16408     *  persisting settings for later use
16409     *  sending a broadcast if necessary
16410     */
16411    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16412        final PackageRemovedInfo info = new PackageRemovedInfo();
16413        final boolean res;
16414
16415        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16416                ? UserHandle.USER_ALL : userId;
16417
16418        if (isPackageDeviceAdmin(packageName, removeUser)) {
16419            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16420            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16421        }
16422
16423        PackageSetting uninstalledPs = null;
16424
16425        // for the uninstall-updates case and restricted profiles, remember the per-
16426        // user handle installed state
16427        int[] allUsers;
16428        synchronized (mPackages) {
16429            uninstalledPs = mSettings.mPackages.get(packageName);
16430            if (uninstalledPs == null) {
16431                Slog.w(TAG, "Not removing non-existent package " + packageName);
16432                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16433            }
16434            allUsers = sUserManager.getUserIds();
16435            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16436        }
16437
16438        final int freezeUser;
16439        if (isUpdatedSystemApp(uninstalledPs)
16440                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16441            // We're downgrading a system app, which will apply to all users, so
16442            // freeze them all during the downgrade
16443            freezeUser = UserHandle.USER_ALL;
16444        } else {
16445            freezeUser = removeUser;
16446        }
16447
16448        synchronized (mInstallLock) {
16449            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16450            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16451                    deleteFlags, "deletePackageX")) {
16452                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16453                        deleteFlags | REMOVE_CHATTY, info, true, null);
16454            }
16455            synchronized (mPackages) {
16456                if (res) {
16457                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16458                }
16459            }
16460        }
16461
16462        if (res) {
16463            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16464            info.sendPackageRemovedBroadcasts(killApp);
16465            info.sendSystemPackageUpdatedBroadcasts();
16466            info.sendSystemPackageAppearedBroadcasts();
16467        }
16468        // Force a gc here.
16469        Runtime.getRuntime().gc();
16470        // Delete the resources here after sending the broadcast to let
16471        // other processes clean up before deleting resources.
16472        if (info.args != null) {
16473            synchronized (mInstallLock) {
16474                info.args.doPostDeleteLI(true);
16475            }
16476        }
16477
16478        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16479    }
16480
16481    class PackageRemovedInfo {
16482        String removedPackage;
16483        int uid = -1;
16484        int removedAppId = -1;
16485        int[] origUsers;
16486        int[] removedUsers = null;
16487        SparseArray<Integer> installReasons;
16488        boolean isRemovedPackageSystemUpdate = false;
16489        boolean isUpdate;
16490        boolean dataRemoved;
16491        boolean removedForAllUsers;
16492        // Clean up resources deleted packages.
16493        InstallArgs args = null;
16494        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16495        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16496
16497        void sendPackageRemovedBroadcasts(boolean killApp) {
16498            sendPackageRemovedBroadcastInternal(killApp);
16499            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16500            for (int i = 0; i < childCount; i++) {
16501                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16502                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16503            }
16504        }
16505
16506        void sendSystemPackageUpdatedBroadcasts() {
16507            if (isRemovedPackageSystemUpdate) {
16508                sendSystemPackageUpdatedBroadcastsInternal();
16509                final int childCount = (removedChildPackages != null)
16510                        ? removedChildPackages.size() : 0;
16511                for (int i = 0; i < childCount; i++) {
16512                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16513                    if (childInfo.isRemovedPackageSystemUpdate) {
16514                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16515                    }
16516                }
16517            }
16518        }
16519
16520        void sendSystemPackageAppearedBroadcasts() {
16521            final int packageCount = (appearedChildPackages != null)
16522                    ? appearedChildPackages.size() : 0;
16523            for (int i = 0; i < packageCount; i++) {
16524                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16525                sendPackageAddedForNewUsers(installedInfo.name, true,
16526                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16527            }
16528        }
16529
16530        private void sendSystemPackageUpdatedBroadcastsInternal() {
16531            Bundle extras = new Bundle(2);
16532            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16533            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16534            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16535                    extras, 0, null, null, null);
16536            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16537                    extras, 0, null, null, null);
16538            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16539                    null, 0, removedPackage, null, null);
16540        }
16541
16542        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16543            Bundle extras = new Bundle(2);
16544            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16545            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16546            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16547            if (isUpdate || isRemovedPackageSystemUpdate) {
16548                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16549            }
16550            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16551            if (removedPackage != null) {
16552                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16553                        extras, 0, null, null, removedUsers);
16554                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16555                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16556                            removedPackage, extras, 0, null, null, removedUsers);
16557                }
16558            }
16559            if (removedAppId >= 0) {
16560                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16561                        removedUsers);
16562            }
16563        }
16564    }
16565
16566    /*
16567     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16568     * flag is not set, the data directory is removed as well.
16569     * make sure this flag is set for partially installed apps. If not its meaningless to
16570     * delete a partially installed application.
16571     */
16572    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16573            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16574        String packageName = ps.name;
16575        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16576        // Retrieve object to delete permissions for shared user later on
16577        final PackageParser.Package deletedPkg;
16578        final PackageSetting deletedPs;
16579        // reader
16580        synchronized (mPackages) {
16581            deletedPkg = mPackages.get(packageName);
16582            deletedPs = mSettings.mPackages.get(packageName);
16583            if (outInfo != null) {
16584                outInfo.removedPackage = packageName;
16585                outInfo.removedUsers = deletedPs != null
16586                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16587                        : null;
16588            }
16589        }
16590
16591        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16592
16593        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16594            final PackageParser.Package resolvedPkg;
16595            if (deletedPkg != null) {
16596                resolvedPkg = deletedPkg;
16597            } else {
16598                // We don't have a parsed package when it lives on an ejected
16599                // adopted storage device, so fake something together
16600                resolvedPkg = new PackageParser.Package(ps.name);
16601                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16602            }
16603            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16604                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16605            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16606            if (outInfo != null) {
16607                outInfo.dataRemoved = true;
16608            }
16609            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16610        }
16611
16612        // writer
16613        synchronized (mPackages) {
16614            if (deletedPs != null) {
16615                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16616                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16617                    clearDefaultBrowserIfNeeded(packageName);
16618                    if (outInfo != null) {
16619                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16620                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16621                    }
16622                    updatePermissionsLPw(deletedPs.name, null, 0);
16623                    if (deletedPs.sharedUser != null) {
16624                        // Remove permissions associated with package. Since runtime
16625                        // permissions are per user we have to kill the removed package
16626                        // or packages running under the shared user of the removed
16627                        // package if revoking the permissions requested only by the removed
16628                        // package is successful and this causes a change in gids.
16629                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16630                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16631                                    userId);
16632                            if (userIdToKill == UserHandle.USER_ALL
16633                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16634                                // If gids changed for this user, kill all affected packages.
16635                                mHandler.post(new Runnable() {
16636                                    @Override
16637                                    public void run() {
16638                                        // This has to happen with no lock held.
16639                                        killApplication(deletedPs.name, deletedPs.appId,
16640                                                KILL_APP_REASON_GIDS_CHANGED);
16641                                    }
16642                                });
16643                                break;
16644                            }
16645                        }
16646                    }
16647                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16648                }
16649                // make sure to preserve per-user disabled state if this removal was just
16650                // a downgrade of a system app to the factory package
16651                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16652                    if (DEBUG_REMOVE) {
16653                        Slog.d(TAG, "Propagating install state across downgrade");
16654                    }
16655                    for (int userId : allUserHandles) {
16656                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16657                        if (DEBUG_REMOVE) {
16658                            Slog.d(TAG, "    user " + userId + " => " + installed);
16659                        }
16660                        ps.setInstalled(installed, userId);
16661                    }
16662                }
16663            }
16664            // can downgrade to reader
16665            if (writeSettings) {
16666                // Save settings now
16667                mSettings.writeLPr();
16668            }
16669        }
16670        if (outInfo != null) {
16671            // A user ID was deleted here. Go through all users and remove it
16672            // from KeyStore.
16673            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16674        }
16675    }
16676
16677    static boolean locationIsPrivileged(File path) {
16678        try {
16679            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16680                    .getCanonicalPath();
16681            return path.getCanonicalPath().startsWith(privilegedAppDir);
16682        } catch (IOException e) {
16683            Slog.e(TAG, "Unable to access code path " + path);
16684        }
16685        return false;
16686    }
16687
16688    /*
16689     * Tries to delete system package.
16690     */
16691    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16692            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16693            boolean writeSettings) {
16694        if (deletedPs.parentPackageName != null) {
16695            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16696            return false;
16697        }
16698
16699        final boolean applyUserRestrictions
16700                = (allUserHandles != null) && (outInfo.origUsers != null);
16701        final PackageSetting disabledPs;
16702        // Confirm if the system package has been updated
16703        // An updated system app can be deleted. This will also have to restore
16704        // the system pkg from system partition
16705        // reader
16706        synchronized (mPackages) {
16707            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16708        }
16709
16710        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16711                + " disabledPs=" + disabledPs);
16712
16713        if (disabledPs == null) {
16714            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16715            return false;
16716        } else if (DEBUG_REMOVE) {
16717            Slog.d(TAG, "Deleting system pkg from data partition");
16718        }
16719
16720        if (DEBUG_REMOVE) {
16721            if (applyUserRestrictions) {
16722                Slog.d(TAG, "Remembering install states:");
16723                for (int userId : allUserHandles) {
16724                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16725                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16726                }
16727            }
16728        }
16729
16730        // Delete the updated package
16731        outInfo.isRemovedPackageSystemUpdate = true;
16732        if (outInfo.removedChildPackages != null) {
16733            final int childCount = (deletedPs.childPackageNames != null)
16734                    ? deletedPs.childPackageNames.size() : 0;
16735            for (int i = 0; i < childCount; i++) {
16736                String childPackageName = deletedPs.childPackageNames.get(i);
16737                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16738                        .contains(childPackageName)) {
16739                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16740                            childPackageName);
16741                    if (childInfo != null) {
16742                        childInfo.isRemovedPackageSystemUpdate = true;
16743                    }
16744                }
16745            }
16746        }
16747
16748        if (disabledPs.versionCode < deletedPs.versionCode) {
16749            // Delete data for downgrades
16750            flags &= ~PackageManager.DELETE_KEEP_DATA;
16751        } else {
16752            // Preserve data by setting flag
16753            flags |= PackageManager.DELETE_KEEP_DATA;
16754        }
16755
16756        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16757                outInfo, writeSettings, disabledPs.pkg);
16758        if (!ret) {
16759            return false;
16760        }
16761
16762        // writer
16763        synchronized (mPackages) {
16764            // Reinstate the old system package
16765            enableSystemPackageLPw(disabledPs.pkg);
16766            // Remove any native libraries from the upgraded package.
16767            removeNativeBinariesLI(deletedPs);
16768        }
16769
16770        // Install the system package
16771        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16772        int parseFlags = mDefParseFlags
16773                | PackageParser.PARSE_MUST_BE_APK
16774                | PackageParser.PARSE_IS_SYSTEM
16775                | PackageParser.PARSE_IS_SYSTEM_DIR;
16776        if (locationIsPrivileged(disabledPs.codePath)) {
16777            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16778        }
16779
16780        final PackageParser.Package newPkg;
16781        try {
16782            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16783                0 /* currentTime */, null);
16784        } catch (PackageManagerException e) {
16785            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16786                    + e.getMessage());
16787            return false;
16788        }
16789        try {
16790            // update shared libraries for the newly re-installed system package
16791            updateSharedLibrariesLPr(newPkg, null);
16792        } catch (PackageManagerException e) {
16793            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16794        }
16795
16796        prepareAppDataAfterInstallLIF(newPkg);
16797
16798        // writer
16799        synchronized (mPackages) {
16800            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16801
16802            // Propagate the permissions state as we do not want to drop on the floor
16803            // runtime permissions. The update permissions method below will take
16804            // care of removing obsolete permissions and grant install permissions.
16805            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16806            updatePermissionsLPw(newPkg.packageName, newPkg,
16807                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16808
16809            if (applyUserRestrictions) {
16810                if (DEBUG_REMOVE) {
16811                    Slog.d(TAG, "Propagating install state across reinstall");
16812                }
16813                for (int userId : allUserHandles) {
16814                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16815                    if (DEBUG_REMOVE) {
16816                        Slog.d(TAG, "    user " + userId + " => " + installed);
16817                    }
16818                    ps.setInstalled(installed, userId);
16819
16820                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16821                }
16822                // Regardless of writeSettings we need to ensure that this restriction
16823                // state propagation is persisted
16824                mSettings.writeAllUsersPackageRestrictionsLPr();
16825            }
16826            // can downgrade to reader here
16827            if (writeSettings) {
16828                mSettings.writeLPr();
16829            }
16830        }
16831        return true;
16832    }
16833
16834    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16835            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16836            PackageRemovedInfo outInfo, boolean writeSettings,
16837            PackageParser.Package replacingPackage) {
16838        synchronized (mPackages) {
16839            if (outInfo != null) {
16840                outInfo.uid = ps.appId;
16841            }
16842
16843            if (outInfo != null && outInfo.removedChildPackages != null) {
16844                final int childCount = (ps.childPackageNames != null)
16845                        ? ps.childPackageNames.size() : 0;
16846                for (int i = 0; i < childCount; i++) {
16847                    String childPackageName = ps.childPackageNames.get(i);
16848                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16849                    if (childPs == null) {
16850                        return false;
16851                    }
16852                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16853                            childPackageName);
16854                    if (childInfo != null) {
16855                        childInfo.uid = childPs.appId;
16856                    }
16857                }
16858            }
16859        }
16860
16861        // Delete package data from internal structures and also remove data if flag is set
16862        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16863
16864        // Delete the child packages data
16865        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16866        for (int i = 0; i < childCount; i++) {
16867            PackageSetting childPs;
16868            synchronized (mPackages) {
16869                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16870            }
16871            if (childPs != null) {
16872                PackageRemovedInfo childOutInfo = (outInfo != null
16873                        && outInfo.removedChildPackages != null)
16874                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16875                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16876                        && (replacingPackage != null
16877                        && !replacingPackage.hasChildPackage(childPs.name))
16878                        ? flags & ~DELETE_KEEP_DATA : flags;
16879                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16880                        deleteFlags, writeSettings);
16881            }
16882        }
16883
16884        // Delete application code and resources only for parent packages
16885        if (ps.parentPackageName == null) {
16886            if (deleteCodeAndResources && (outInfo != null)) {
16887                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16888                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16889                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16890            }
16891        }
16892
16893        return true;
16894    }
16895
16896    @Override
16897    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16898            int userId) {
16899        mContext.enforceCallingOrSelfPermission(
16900                android.Manifest.permission.DELETE_PACKAGES, null);
16901        synchronized (mPackages) {
16902            PackageSetting ps = mSettings.mPackages.get(packageName);
16903            if (ps == null) {
16904                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16905                return false;
16906            }
16907            if (!ps.getInstalled(userId)) {
16908                // Can't block uninstall for an app that is not installed or enabled.
16909                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16910                return false;
16911            }
16912            ps.setBlockUninstall(blockUninstall, userId);
16913            mSettings.writePackageRestrictionsLPr(userId);
16914        }
16915        return true;
16916    }
16917
16918    @Override
16919    public boolean getBlockUninstallForUser(String packageName, int userId) {
16920        synchronized (mPackages) {
16921            PackageSetting ps = mSettings.mPackages.get(packageName);
16922            if (ps == null) {
16923                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16924                return false;
16925            }
16926            return ps.getBlockUninstall(userId);
16927        }
16928    }
16929
16930    @Override
16931    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16932        int callingUid = Binder.getCallingUid();
16933        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16934            throw new SecurityException(
16935                    "setRequiredForSystemUser can only be run by the system or root");
16936        }
16937        synchronized (mPackages) {
16938            PackageSetting ps = mSettings.mPackages.get(packageName);
16939            if (ps == null) {
16940                Log.w(TAG, "Package doesn't exist: " + packageName);
16941                return false;
16942            }
16943            if (systemUserApp) {
16944                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16945            } else {
16946                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16947            }
16948            mSettings.writeLPr();
16949        }
16950        return true;
16951    }
16952
16953    /*
16954     * This method handles package deletion in general
16955     */
16956    private boolean deletePackageLIF(String packageName, UserHandle user,
16957            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16958            PackageRemovedInfo outInfo, boolean writeSettings,
16959            PackageParser.Package replacingPackage) {
16960        if (packageName == null) {
16961            Slog.w(TAG, "Attempt to delete null packageName.");
16962            return false;
16963        }
16964
16965        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16966
16967        PackageSetting ps;
16968
16969        synchronized (mPackages) {
16970            ps = mSettings.mPackages.get(packageName);
16971            if (ps == null) {
16972                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16973                return false;
16974            }
16975
16976            if (ps.parentPackageName != null && (!isSystemApp(ps)
16977                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16978                if (DEBUG_REMOVE) {
16979                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16980                            + ((user == null) ? UserHandle.USER_ALL : user));
16981                }
16982                final int removedUserId = (user != null) ? user.getIdentifier()
16983                        : UserHandle.USER_ALL;
16984                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16985                    return false;
16986                }
16987                markPackageUninstalledForUserLPw(ps, user);
16988                scheduleWritePackageRestrictionsLocked(user);
16989                return true;
16990            }
16991        }
16992
16993        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16994                && user.getIdentifier() != UserHandle.USER_ALL)) {
16995            // The caller is asking that the package only be deleted for a single
16996            // user.  To do this, we just mark its uninstalled state and delete
16997            // its data. If this is a system app, we only allow this to happen if
16998            // they have set the special DELETE_SYSTEM_APP which requests different
16999            // semantics than normal for uninstalling system apps.
17000            markPackageUninstalledForUserLPw(ps, user);
17001
17002            if (!isSystemApp(ps)) {
17003                // Do not uninstall the APK if an app should be cached
17004                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17005                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17006                    // Other user still have this package installed, so all
17007                    // we need to do is clear this user's data and save that
17008                    // it is uninstalled.
17009                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17010                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17011                        return false;
17012                    }
17013                    scheduleWritePackageRestrictionsLocked(user);
17014                    return true;
17015                } else {
17016                    // We need to set it back to 'installed' so the uninstall
17017                    // broadcasts will be sent correctly.
17018                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17019                    ps.setInstalled(true, user.getIdentifier());
17020                }
17021            } else {
17022                // This is a system app, so we assume that the
17023                // other users still have this package installed, so all
17024                // we need to do is clear this user's data and save that
17025                // it is uninstalled.
17026                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17027                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17028                    return false;
17029                }
17030                scheduleWritePackageRestrictionsLocked(user);
17031                return true;
17032            }
17033        }
17034
17035        // If we are deleting a composite package for all users, keep track
17036        // of result for each child.
17037        if (ps.childPackageNames != null && outInfo != null) {
17038            synchronized (mPackages) {
17039                final int childCount = ps.childPackageNames.size();
17040                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17041                for (int i = 0; i < childCount; i++) {
17042                    String childPackageName = ps.childPackageNames.get(i);
17043                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
17044                    childInfo.removedPackage = childPackageName;
17045                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17046                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17047                    if (childPs != null) {
17048                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17049                    }
17050                }
17051            }
17052        }
17053
17054        boolean ret = false;
17055        if (isSystemApp(ps)) {
17056            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17057            // When an updated system application is deleted we delete the existing resources
17058            // as well and fall back to existing code in system partition
17059            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17060        } else {
17061            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17062            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17063                    outInfo, writeSettings, replacingPackage);
17064        }
17065
17066        // Take a note whether we deleted the package for all users
17067        if (outInfo != null) {
17068            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17069            if (outInfo.removedChildPackages != null) {
17070                synchronized (mPackages) {
17071                    final int childCount = outInfo.removedChildPackages.size();
17072                    for (int i = 0; i < childCount; i++) {
17073                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17074                        if (childInfo != null) {
17075                            childInfo.removedForAllUsers = mPackages.get(
17076                                    childInfo.removedPackage) == null;
17077                        }
17078                    }
17079                }
17080            }
17081            // If we uninstalled an update to a system app there may be some
17082            // child packages that appeared as they are declared in the system
17083            // app but were not declared in the update.
17084            if (isSystemApp(ps)) {
17085                synchronized (mPackages) {
17086                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17087                    final int childCount = (updatedPs.childPackageNames != null)
17088                            ? updatedPs.childPackageNames.size() : 0;
17089                    for (int i = 0; i < childCount; i++) {
17090                        String childPackageName = updatedPs.childPackageNames.get(i);
17091                        if (outInfo.removedChildPackages == null
17092                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17093                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17094                            if (childPs == null) {
17095                                continue;
17096                            }
17097                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17098                            installRes.name = childPackageName;
17099                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17100                            installRes.pkg = mPackages.get(childPackageName);
17101                            installRes.uid = childPs.pkg.applicationInfo.uid;
17102                            if (outInfo.appearedChildPackages == null) {
17103                                outInfo.appearedChildPackages = new ArrayMap<>();
17104                            }
17105                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17106                        }
17107                    }
17108                }
17109            }
17110        }
17111
17112        return ret;
17113    }
17114
17115    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17116        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17117                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17118        for (int nextUserId : userIds) {
17119            if (DEBUG_REMOVE) {
17120                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17121            }
17122            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17123                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
17124                    false /*hidden*/, false /*suspended*/, null, null, null,
17125                    false /*blockUninstall*/,
17126                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
17127                    PackageManager.INSTALL_REASON_UNKNOWN);
17128        }
17129    }
17130
17131    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17132            PackageRemovedInfo outInfo) {
17133        final PackageParser.Package pkg;
17134        synchronized (mPackages) {
17135            pkg = mPackages.get(ps.name);
17136        }
17137
17138        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17139                : new int[] {userId};
17140        for (int nextUserId : userIds) {
17141            if (DEBUG_REMOVE) {
17142                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17143                        + nextUserId);
17144            }
17145
17146            destroyAppDataLIF(pkg, userId,
17147                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17148            destroyAppProfilesLIF(pkg, userId);
17149            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
17150            schedulePackageCleaning(ps.name, nextUserId, false);
17151            synchronized (mPackages) {
17152                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
17153                    scheduleWritePackageRestrictionsLocked(nextUserId);
17154                }
17155                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
17156            }
17157        }
17158
17159        if (outInfo != null) {
17160            outInfo.removedPackage = ps.name;
17161            outInfo.removedAppId = ps.appId;
17162            outInfo.removedUsers = userIds;
17163        }
17164
17165        return true;
17166    }
17167
17168    private final class ClearStorageConnection implements ServiceConnection {
17169        IMediaContainerService mContainerService;
17170
17171        @Override
17172        public void onServiceConnected(ComponentName name, IBinder service) {
17173            synchronized (this) {
17174                mContainerService = IMediaContainerService.Stub
17175                        .asInterface(Binder.allowBlocking(service));
17176                notifyAll();
17177            }
17178        }
17179
17180        @Override
17181        public void onServiceDisconnected(ComponentName name) {
17182        }
17183    }
17184
17185    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
17186        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
17187
17188        final boolean mounted;
17189        if (Environment.isExternalStorageEmulated()) {
17190            mounted = true;
17191        } else {
17192            final String status = Environment.getExternalStorageState();
17193
17194            mounted = status.equals(Environment.MEDIA_MOUNTED)
17195                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
17196        }
17197
17198        if (!mounted) {
17199            return;
17200        }
17201
17202        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
17203        int[] users;
17204        if (userId == UserHandle.USER_ALL) {
17205            users = sUserManager.getUserIds();
17206        } else {
17207            users = new int[] { userId };
17208        }
17209        final ClearStorageConnection conn = new ClearStorageConnection();
17210        if (mContext.bindServiceAsUser(
17211                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
17212            try {
17213                for (int curUser : users) {
17214                    long timeout = SystemClock.uptimeMillis() + 5000;
17215                    synchronized (conn) {
17216                        long now;
17217                        while (conn.mContainerService == null &&
17218                                (now = SystemClock.uptimeMillis()) < timeout) {
17219                            try {
17220                                conn.wait(timeout - now);
17221                            } catch (InterruptedException e) {
17222                            }
17223                        }
17224                    }
17225                    if (conn.mContainerService == null) {
17226                        return;
17227                    }
17228
17229                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17230                    clearDirectory(conn.mContainerService,
17231                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17232                    if (allData) {
17233                        clearDirectory(conn.mContainerService,
17234                                userEnv.buildExternalStorageAppDataDirs(packageName));
17235                        clearDirectory(conn.mContainerService,
17236                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17237                    }
17238                }
17239            } finally {
17240                mContext.unbindService(conn);
17241            }
17242        }
17243    }
17244
17245    @Override
17246    public void clearApplicationProfileData(String packageName) {
17247        enforceSystemOrRoot("Only the system can clear all profile data");
17248
17249        final PackageParser.Package pkg;
17250        synchronized (mPackages) {
17251            pkg = mPackages.get(packageName);
17252        }
17253
17254        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17255            synchronized (mInstallLock) {
17256                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17257                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17258                        true /* removeBaseMarker */);
17259            }
17260        }
17261    }
17262
17263    @Override
17264    public void clearApplicationUserData(final String packageName,
17265            final IPackageDataObserver observer, final int userId) {
17266        mContext.enforceCallingOrSelfPermission(
17267                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17268
17269        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17270                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17271
17272        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17273            throw new SecurityException("Cannot clear data for a protected package: "
17274                    + packageName);
17275        }
17276        // Queue up an async operation since the package deletion may take a little while.
17277        mHandler.post(new Runnable() {
17278            public void run() {
17279                mHandler.removeCallbacks(this);
17280                final boolean succeeded;
17281                try (PackageFreezer freezer = freezePackage(packageName,
17282                        "clearApplicationUserData")) {
17283                    synchronized (mInstallLock) {
17284                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17285                    }
17286                    clearExternalStorageDataSync(packageName, userId, true);
17287                }
17288                if (succeeded) {
17289                    // invoke DeviceStorageMonitor's update method to clear any notifications
17290                    DeviceStorageMonitorInternal dsm = LocalServices
17291                            .getService(DeviceStorageMonitorInternal.class);
17292                    if (dsm != null) {
17293                        dsm.checkMemory();
17294                    }
17295                }
17296                if(observer != null) {
17297                    try {
17298                        observer.onRemoveCompleted(packageName, succeeded);
17299                    } catch (RemoteException e) {
17300                        Log.i(TAG, "Observer no longer exists.");
17301                    }
17302                } //end if observer
17303            } //end run
17304        });
17305    }
17306
17307    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17308        if (packageName == null) {
17309            Slog.w(TAG, "Attempt to delete null packageName.");
17310            return false;
17311        }
17312
17313        // Try finding details about the requested package
17314        PackageParser.Package pkg;
17315        synchronized (mPackages) {
17316            pkg = mPackages.get(packageName);
17317            if (pkg == null) {
17318                final PackageSetting ps = mSettings.mPackages.get(packageName);
17319                if (ps != null) {
17320                    pkg = ps.pkg;
17321                }
17322            }
17323
17324            if (pkg == null) {
17325                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17326                return false;
17327            }
17328
17329            PackageSetting ps = (PackageSetting) pkg.mExtras;
17330            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17331        }
17332
17333        clearAppDataLIF(pkg, userId,
17334                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17335
17336        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17337        removeKeystoreDataIfNeeded(userId, appId);
17338
17339        UserManagerInternal umInternal = getUserManagerInternal();
17340        final int flags;
17341        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17342            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17343        } else if (umInternal.isUserRunning(userId)) {
17344            flags = StorageManager.FLAG_STORAGE_DE;
17345        } else {
17346            flags = 0;
17347        }
17348        prepareAppDataContentsLIF(pkg, userId, flags);
17349
17350        return true;
17351    }
17352
17353    /**
17354     * Reverts user permission state changes (permissions and flags) in
17355     * all packages for a given user.
17356     *
17357     * @param userId The device user for which to do a reset.
17358     */
17359    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17360        final int packageCount = mPackages.size();
17361        for (int i = 0; i < packageCount; i++) {
17362            PackageParser.Package pkg = mPackages.valueAt(i);
17363            PackageSetting ps = (PackageSetting) pkg.mExtras;
17364            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17365        }
17366    }
17367
17368    private void resetNetworkPolicies(int userId) {
17369        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17370    }
17371
17372    /**
17373     * Reverts user permission state changes (permissions and flags).
17374     *
17375     * @param ps The package for which to reset.
17376     * @param userId The device user for which to do a reset.
17377     */
17378    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17379            final PackageSetting ps, final int userId) {
17380        if (ps.pkg == null) {
17381            return;
17382        }
17383
17384        // These are flags that can change base on user actions.
17385        final int userSettableMask = FLAG_PERMISSION_USER_SET
17386                | FLAG_PERMISSION_USER_FIXED
17387                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17388                | FLAG_PERMISSION_REVIEW_REQUIRED;
17389
17390        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17391                | FLAG_PERMISSION_POLICY_FIXED;
17392
17393        boolean writeInstallPermissions = false;
17394        boolean writeRuntimePermissions = false;
17395
17396        final int permissionCount = ps.pkg.requestedPermissions.size();
17397        for (int i = 0; i < permissionCount; i++) {
17398            String permission = ps.pkg.requestedPermissions.get(i);
17399
17400            BasePermission bp = mSettings.mPermissions.get(permission);
17401            if (bp == null) {
17402                continue;
17403            }
17404
17405            // If shared user we just reset the state to which only this app contributed.
17406            if (ps.sharedUser != null) {
17407                boolean used = false;
17408                final int packageCount = ps.sharedUser.packages.size();
17409                for (int j = 0; j < packageCount; j++) {
17410                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17411                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17412                            && pkg.pkg.requestedPermissions.contains(permission)) {
17413                        used = true;
17414                        break;
17415                    }
17416                }
17417                if (used) {
17418                    continue;
17419                }
17420            }
17421
17422            PermissionsState permissionsState = ps.getPermissionsState();
17423
17424            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17425
17426            // Always clear the user settable flags.
17427            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17428                    bp.name) != null;
17429            // If permission review is enabled and this is a legacy app, mark the
17430            // permission as requiring a review as this is the initial state.
17431            int flags = 0;
17432            if (mPermissionReviewRequired
17433                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17434                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17435            }
17436            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17437                if (hasInstallState) {
17438                    writeInstallPermissions = true;
17439                } else {
17440                    writeRuntimePermissions = true;
17441                }
17442            }
17443
17444            // Below is only runtime permission handling.
17445            if (!bp.isRuntime()) {
17446                continue;
17447            }
17448
17449            // Never clobber system or policy.
17450            if ((oldFlags & policyOrSystemFlags) != 0) {
17451                continue;
17452            }
17453
17454            // If this permission was granted by default, make sure it is.
17455            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17456                if (permissionsState.grantRuntimePermission(bp, userId)
17457                        != PERMISSION_OPERATION_FAILURE) {
17458                    writeRuntimePermissions = true;
17459                }
17460            // If permission review is enabled the permissions for a legacy apps
17461            // are represented as constantly granted runtime ones, so don't revoke.
17462            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17463                // Otherwise, reset the permission.
17464                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17465                switch (revokeResult) {
17466                    case PERMISSION_OPERATION_SUCCESS:
17467                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17468                        writeRuntimePermissions = true;
17469                        final int appId = ps.appId;
17470                        mHandler.post(new Runnable() {
17471                            @Override
17472                            public void run() {
17473                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17474                            }
17475                        });
17476                    } break;
17477                }
17478            }
17479        }
17480
17481        // Synchronously write as we are taking permissions away.
17482        if (writeRuntimePermissions) {
17483            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17484        }
17485
17486        // Synchronously write as we are taking permissions away.
17487        if (writeInstallPermissions) {
17488            mSettings.writeLPr();
17489        }
17490    }
17491
17492    /**
17493     * Remove entries from the keystore daemon. Will only remove it if the
17494     * {@code appId} is valid.
17495     */
17496    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17497        if (appId < 0) {
17498            return;
17499        }
17500
17501        final KeyStore keyStore = KeyStore.getInstance();
17502        if (keyStore != null) {
17503            if (userId == UserHandle.USER_ALL) {
17504                for (final int individual : sUserManager.getUserIds()) {
17505                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17506                }
17507            } else {
17508                keyStore.clearUid(UserHandle.getUid(userId, appId));
17509            }
17510        } else {
17511            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17512        }
17513    }
17514
17515    @Override
17516    public void deleteApplicationCacheFiles(final String packageName,
17517            final IPackageDataObserver observer) {
17518        final int userId = UserHandle.getCallingUserId();
17519        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17520    }
17521
17522    @Override
17523    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17524            final IPackageDataObserver observer) {
17525        mContext.enforceCallingOrSelfPermission(
17526                android.Manifest.permission.DELETE_CACHE_FILES, null);
17527        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17528                /* requireFullPermission= */ true, /* checkShell= */ false,
17529                "delete application cache files");
17530
17531        final PackageParser.Package pkg;
17532        synchronized (mPackages) {
17533            pkg = mPackages.get(packageName);
17534        }
17535
17536        // Queue up an async operation since the package deletion may take a little while.
17537        mHandler.post(new Runnable() {
17538            public void run() {
17539                synchronized (mInstallLock) {
17540                    final int flags = StorageManager.FLAG_STORAGE_DE
17541                            | StorageManager.FLAG_STORAGE_CE;
17542                    // We're only clearing cache files, so we don't care if the
17543                    // app is unfrozen and still able to run
17544                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17545                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17546                }
17547                clearExternalStorageDataSync(packageName, userId, false);
17548                if (observer != null) {
17549                    try {
17550                        observer.onRemoveCompleted(packageName, true);
17551                    } catch (RemoteException e) {
17552                        Log.i(TAG, "Observer no longer exists.");
17553                    }
17554                }
17555            }
17556        });
17557    }
17558
17559    @Override
17560    public void getPackageSizeInfo(final String packageName, int userHandle,
17561            final IPackageStatsObserver observer) {
17562        mContext.enforceCallingOrSelfPermission(
17563                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17564        if (packageName == null) {
17565            throw new IllegalArgumentException("Attempt to get size of null packageName");
17566        }
17567
17568        PackageStats stats = new PackageStats(packageName, userHandle);
17569
17570        /*
17571         * Queue up an async operation since the package measurement may take a
17572         * little while.
17573         */
17574        Message msg = mHandler.obtainMessage(INIT_COPY);
17575        msg.obj = new MeasureParams(stats, observer);
17576        mHandler.sendMessage(msg);
17577    }
17578
17579    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17580        final PackageSetting ps;
17581        synchronized (mPackages) {
17582            ps = mSettings.mPackages.get(packageName);
17583            if (ps == null) {
17584                Slog.w(TAG, "Failed to find settings for " + packageName);
17585                return false;
17586            }
17587        }
17588
17589        final String[] packageNames = { packageName };
17590        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
17591        final String[] codePaths = { ps.codePathString };
17592
17593        try {
17594            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
17595                    ps.appId, ceDataInodes, codePaths, stats);
17596
17597            // For now, ignore code size of packages on system partition
17598            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17599                stats.codeSize = 0;
17600            }
17601
17602            // External clients expect these to be tracked separately
17603            stats.dataSize -= stats.cacheSize;
17604
17605        } catch (InstallerException e) {
17606            Slog.w(TAG, String.valueOf(e));
17607            return false;
17608        }
17609
17610        return true;
17611    }
17612
17613    private int getUidTargetSdkVersionLockedLPr(int uid) {
17614        Object obj = mSettings.getUserIdLPr(uid);
17615        if (obj instanceof SharedUserSetting) {
17616            final SharedUserSetting sus = (SharedUserSetting) obj;
17617            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17618            final Iterator<PackageSetting> it = sus.packages.iterator();
17619            while (it.hasNext()) {
17620                final PackageSetting ps = it.next();
17621                if (ps.pkg != null) {
17622                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17623                    if (v < vers) vers = v;
17624                }
17625            }
17626            return vers;
17627        } else if (obj instanceof PackageSetting) {
17628            final PackageSetting ps = (PackageSetting) obj;
17629            if (ps.pkg != null) {
17630                return ps.pkg.applicationInfo.targetSdkVersion;
17631            }
17632        }
17633        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17634    }
17635
17636    @Override
17637    public void addPreferredActivity(IntentFilter filter, int match,
17638            ComponentName[] set, ComponentName activity, int userId) {
17639        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17640                "Adding preferred");
17641    }
17642
17643    private void addPreferredActivityInternal(IntentFilter filter, int match,
17644            ComponentName[] set, ComponentName activity, boolean always, int userId,
17645            String opname) {
17646        // writer
17647        int callingUid = Binder.getCallingUid();
17648        enforceCrossUserPermission(callingUid, userId,
17649                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17650        if (filter.countActions() == 0) {
17651            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17652            return;
17653        }
17654        synchronized (mPackages) {
17655            if (mContext.checkCallingOrSelfPermission(
17656                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17657                    != PackageManager.PERMISSION_GRANTED) {
17658                if (getUidTargetSdkVersionLockedLPr(callingUid)
17659                        < Build.VERSION_CODES.FROYO) {
17660                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17661                            + callingUid);
17662                    return;
17663                }
17664                mContext.enforceCallingOrSelfPermission(
17665                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17666            }
17667
17668            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17669            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17670                    + userId + ":");
17671            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17672            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17673            scheduleWritePackageRestrictionsLocked(userId);
17674            postPreferredActivityChangedBroadcast(userId);
17675        }
17676    }
17677
17678    private void postPreferredActivityChangedBroadcast(int userId) {
17679        mHandler.post(() -> {
17680            final IActivityManager am = ActivityManager.getService();
17681            if (am == null) {
17682                return;
17683            }
17684
17685            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17686            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17687            try {
17688                am.broadcastIntent(null, intent, null, null,
17689                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17690                        null, false, false, userId);
17691            } catch (RemoteException e) {
17692            }
17693        });
17694    }
17695
17696    @Override
17697    public void replacePreferredActivity(IntentFilter filter, int match,
17698            ComponentName[] set, ComponentName activity, int userId) {
17699        if (filter.countActions() != 1) {
17700            throw new IllegalArgumentException(
17701                    "replacePreferredActivity expects filter to have only 1 action.");
17702        }
17703        if (filter.countDataAuthorities() != 0
17704                || filter.countDataPaths() != 0
17705                || filter.countDataSchemes() > 1
17706                || filter.countDataTypes() != 0) {
17707            throw new IllegalArgumentException(
17708                    "replacePreferredActivity expects filter to have no data authorities, " +
17709                    "paths, or types; and at most one scheme.");
17710        }
17711
17712        final int callingUid = Binder.getCallingUid();
17713        enforceCrossUserPermission(callingUid, userId,
17714                true /* requireFullPermission */, false /* checkShell */,
17715                "replace preferred activity");
17716        synchronized (mPackages) {
17717            if (mContext.checkCallingOrSelfPermission(
17718                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17719                    != PackageManager.PERMISSION_GRANTED) {
17720                if (getUidTargetSdkVersionLockedLPr(callingUid)
17721                        < Build.VERSION_CODES.FROYO) {
17722                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17723                            + Binder.getCallingUid());
17724                    return;
17725                }
17726                mContext.enforceCallingOrSelfPermission(
17727                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17728            }
17729
17730            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17731            if (pir != null) {
17732                // Get all of the existing entries that exactly match this filter.
17733                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17734                if (existing != null && existing.size() == 1) {
17735                    PreferredActivity cur = existing.get(0);
17736                    if (DEBUG_PREFERRED) {
17737                        Slog.i(TAG, "Checking replace of preferred:");
17738                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17739                        if (!cur.mPref.mAlways) {
17740                            Slog.i(TAG, "  -- CUR; not mAlways!");
17741                        } else {
17742                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17743                            Slog.i(TAG, "  -- CUR: mSet="
17744                                    + Arrays.toString(cur.mPref.mSetComponents));
17745                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17746                            Slog.i(TAG, "  -- NEW: mMatch="
17747                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17748                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17749                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17750                        }
17751                    }
17752                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17753                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17754                            && cur.mPref.sameSet(set)) {
17755                        // Setting the preferred activity to what it happens to be already
17756                        if (DEBUG_PREFERRED) {
17757                            Slog.i(TAG, "Replacing with same preferred activity "
17758                                    + cur.mPref.mShortComponent + " for user "
17759                                    + userId + ":");
17760                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17761                        }
17762                        return;
17763                    }
17764                }
17765
17766                if (existing != null) {
17767                    if (DEBUG_PREFERRED) {
17768                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17769                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17770                    }
17771                    for (int i = 0; i < existing.size(); i++) {
17772                        PreferredActivity pa = existing.get(i);
17773                        if (DEBUG_PREFERRED) {
17774                            Slog.i(TAG, "Removing existing preferred activity "
17775                                    + pa.mPref.mComponent + ":");
17776                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17777                        }
17778                        pir.removeFilter(pa);
17779                    }
17780                }
17781            }
17782            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17783                    "Replacing preferred");
17784        }
17785    }
17786
17787    @Override
17788    public void clearPackagePreferredActivities(String packageName) {
17789        final int uid = Binder.getCallingUid();
17790        // writer
17791        synchronized (mPackages) {
17792            PackageParser.Package pkg = mPackages.get(packageName);
17793            if (pkg == null || pkg.applicationInfo.uid != uid) {
17794                if (mContext.checkCallingOrSelfPermission(
17795                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17796                        != PackageManager.PERMISSION_GRANTED) {
17797                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17798                            < Build.VERSION_CODES.FROYO) {
17799                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17800                                + Binder.getCallingUid());
17801                        return;
17802                    }
17803                    mContext.enforceCallingOrSelfPermission(
17804                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17805                }
17806            }
17807
17808            int user = UserHandle.getCallingUserId();
17809            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17810                scheduleWritePackageRestrictionsLocked(user);
17811            }
17812        }
17813    }
17814
17815    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17816    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17817        ArrayList<PreferredActivity> removed = null;
17818        boolean changed = false;
17819        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17820            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17821            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17822            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17823                continue;
17824            }
17825            Iterator<PreferredActivity> it = pir.filterIterator();
17826            while (it.hasNext()) {
17827                PreferredActivity pa = it.next();
17828                // Mark entry for removal only if it matches the package name
17829                // and the entry is of type "always".
17830                if (packageName == null ||
17831                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17832                                && pa.mPref.mAlways)) {
17833                    if (removed == null) {
17834                        removed = new ArrayList<PreferredActivity>();
17835                    }
17836                    removed.add(pa);
17837                }
17838            }
17839            if (removed != null) {
17840                for (int j=0; j<removed.size(); j++) {
17841                    PreferredActivity pa = removed.get(j);
17842                    pir.removeFilter(pa);
17843                }
17844                changed = true;
17845            }
17846        }
17847        if (changed) {
17848            postPreferredActivityChangedBroadcast(userId);
17849        }
17850        return changed;
17851    }
17852
17853    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17854    private void clearIntentFilterVerificationsLPw(int userId) {
17855        final int packageCount = mPackages.size();
17856        for (int i = 0; i < packageCount; i++) {
17857            PackageParser.Package pkg = mPackages.valueAt(i);
17858            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17859        }
17860    }
17861
17862    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17863    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17864        if (userId == UserHandle.USER_ALL) {
17865            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17866                    sUserManager.getUserIds())) {
17867                for (int oneUserId : sUserManager.getUserIds()) {
17868                    scheduleWritePackageRestrictionsLocked(oneUserId);
17869                }
17870            }
17871        } else {
17872            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17873                scheduleWritePackageRestrictionsLocked(userId);
17874            }
17875        }
17876    }
17877
17878    void clearDefaultBrowserIfNeeded(String packageName) {
17879        for (int oneUserId : sUserManager.getUserIds()) {
17880            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17881            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17882            if (packageName.equals(defaultBrowserPackageName)) {
17883                setDefaultBrowserPackageName(null, oneUserId);
17884            }
17885        }
17886    }
17887
17888    @Override
17889    public void resetApplicationPreferences(int userId) {
17890        mContext.enforceCallingOrSelfPermission(
17891                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17892        final long identity = Binder.clearCallingIdentity();
17893        // writer
17894        try {
17895            synchronized (mPackages) {
17896                clearPackagePreferredActivitiesLPw(null, userId);
17897                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17898                // TODO: We have to reset the default SMS and Phone. This requires
17899                // significant refactoring to keep all default apps in the package
17900                // manager (cleaner but more work) or have the services provide
17901                // callbacks to the package manager to request a default app reset.
17902                applyFactoryDefaultBrowserLPw(userId);
17903                clearIntentFilterVerificationsLPw(userId);
17904                primeDomainVerificationsLPw(userId);
17905                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17906                scheduleWritePackageRestrictionsLocked(userId);
17907            }
17908            resetNetworkPolicies(userId);
17909        } finally {
17910            Binder.restoreCallingIdentity(identity);
17911        }
17912    }
17913
17914    @Override
17915    public int getPreferredActivities(List<IntentFilter> outFilters,
17916            List<ComponentName> outActivities, String packageName) {
17917
17918        int num = 0;
17919        final int userId = UserHandle.getCallingUserId();
17920        // reader
17921        synchronized (mPackages) {
17922            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17923            if (pir != null) {
17924                final Iterator<PreferredActivity> it = pir.filterIterator();
17925                while (it.hasNext()) {
17926                    final PreferredActivity pa = it.next();
17927                    if (packageName == null
17928                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17929                                    && pa.mPref.mAlways)) {
17930                        if (outFilters != null) {
17931                            outFilters.add(new IntentFilter(pa));
17932                        }
17933                        if (outActivities != null) {
17934                            outActivities.add(pa.mPref.mComponent);
17935                        }
17936                    }
17937                }
17938            }
17939        }
17940
17941        return num;
17942    }
17943
17944    @Override
17945    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17946            int userId) {
17947        int callingUid = Binder.getCallingUid();
17948        if (callingUid != Process.SYSTEM_UID) {
17949            throw new SecurityException(
17950                    "addPersistentPreferredActivity can only be run by the system");
17951        }
17952        if (filter.countActions() == 0) {
17953            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17954            return;
17955        }
17956        synchronized (mPackages) {
17957            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17958                    ":");
17959            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17960            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17961                    new PersistentPreferredActivity(filter, activity));
17962            scheduleWritePackageRestrictionsLocked(userId);
17963            postPreferredActivityChangedBroadcast(userId);
17964        }
17965    }
17966
17967    @Override
17968    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17969        int callingUid = Binder.getCallingUid();
17970        if (callingUid != Process.SYSTEM_UID) {
17971            throw new SecurityException(
17972                    "clearPackagePersistentPreferredActivities can only be run by the system");
17973        }
17974        ArrayList<PersistentPreferredActivity> removed = null;
17975        boolean changed = false;
17976        synchronized (mPackages) {
17977            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17978                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17979                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17980                        .valueAt(i);
17981                if (userId != thisUserId) {
17982                    continue;
17983                }
17984                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17985                while (it.hasNext()) {
17986                    PersistentPreferredActivity ppa = it.next();
17987                    // Mark entry for removal only if it matches the package name.
17988                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17989                        if (removed == null) {
17990                            removed = new ArrayList<PersistentPreferredActivity>();
17991                        }
17992                        removed.add(ppa);
17993                    }
17994                }
17995                if (removed != null) {
17996                    for (int j=0; j<removed.size(); j++) {
17997                        PersistentPreferredActivity ppa = removed.get(j);
17998                        ppir.removeFilter(ppa);
17999                    }
18000                    changed = true;
18001                }
18002            }
18003
18004            if (changed) {
18005                scheduleWritePackageRestrictionsLocked(userId);
18006                postPreferredActivityChangedBroadcast(userId);
18007            }
18008        }
18009    }
18010
18011    /**
18012     * Common machinery for picking apart a restored XML blob and passing
18013     * it to a caller-supplied functor to be applied to the running system.
18014     */
18015    private void restoreFromXml(XmlPullParser parser, int userId,
18016            String expectedStartTag, BlobXmlRestorer functor)
18017            throws IOException, XmlPullParserException {
18018        int type;
18019        while ((type = parser.next()) != XmlPullParser.START_TAG
18020                && type != XmlPullParser.END_DOCUMENT) {
18021        }
18022        if (type != XmlPullParser.START_TAG) {
18023            // oops didn't find a start tag?!
18024            if (DEBUG_BACKUP) {
18025                Slog.e(TAG, "Didn't find start tag during restore");
18026            }
18027            return;
18028        }
18029Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18030        // this is supposed to be TAG_PREFERRED_BACKUP
18031        if (!expectedStartTag.equals(parser.getName())) {
18032            if (DEBUG_BACKUP) {
18033                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18034            }
18035            return;
18036        }
18037
18038        // skip interfering stuff, then we're aligned with the backing implementation
18039        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18040Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18041        functor.apply(parser, userId);
18042    }
18043
18044    private interface BlobXmlRestorer {
18045        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18046    }
18047
18048    /**
18049     * Non-Binder method, support for the backup/restore mechanism: write the
18050     * full set of preferred activities in its canonical XML format.  Returns the
18051     * XML output as a byte array, or null if there is none.
18052     */
18053    @Override
18054    public byte[] getPreferredActivityBackup(int userId) {
18055        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18056            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18057        }
18058
18059        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18060        try {
18061            final XmlSerializer serializer = new FastXmlSerializer();
18062            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18063            serializer.startDocument(null, true);
18064            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18065
18066            synchronized (mPackages) {
18067                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18068            }
18069
18070            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18071            serializer.endDocument();
18072            serializer.flush();
18073        } catch (Exception e) {
18074            if (DEBUG_BACKUP) {
18075                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18076            }
18077            return null;
18078        }
18079
18080        return dataStream.toByteArray();
18081    }
18082
18083    @Override
18084    public void restorePreferredActivities(byte[] backup, int userId) {
18085        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18086            throw new SecurityException("Only the system may call restorePreferredActivities()");
18087        }
18088
18089        try {
18090            final XmlPullParser parser = Xml.newPullParser();
18091            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18092            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18093                    new BlobXmlRestorer() {
18094                        @Override
18095                        public void apply(XmlPullParser parser, int userId)
18096                                throws XmlPullParserException, IOException {
18097                            synchronized (mPackages) {
18098                                mSettings.readPreferredActivitiesLPw(parser, userId);
18099                            }
18100                        }
18101                    } );
18102        } catch (Exception e) {
18103            if (DEBUG_BACKUP) {
18104                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18105            }
18106        }
18107    }
18108
18109    /**
18110     * Non-Binder method, support for the backup/restore mechanism: write the
18111     * default browser (etc) settings in its canonical XML format.  Returns the default
18112     * browser XML representation as a byte array, or null if there is none.
18113     */
18114    @Override
18115    public byte[] getDefaultAppsBackup(int userId) {
18116        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18117            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18118        }
18119
18120        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18121        try {
18122            final XmlSerializer serializer = new FastXmlSerializer();
18123            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18124            serializer.startDocument(null, true);
18125            serializer.startTag(null, TAG_DEFAULT_APPS);
18126
18127            synchronized (mPackages) {
18128                mSettings.writeDefaultAppsLPr(serializer, userId);
18129            }
18130
18131            serializer.endTag(null, TAG_DEFAULT_APPS);
18132            serializer.endDocument();
18133            serializer.flush();
18134        } catch (Exception e) {
18135            if (DEBUG_BACKUP) {
18136                Slog.e(TAG, "Unable to write default apps for backup", e);
18137            }
18138            return null;
18139        }
18140
18141        return dataStream.toByteArray();
18142    }
18143
18144    @Override
18145    public void restoreDefaultApps(byte[] backup, int userId) {
18146        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18147            throw new SecurityException("Only the system may call restoreDefaultApps()");
18148        }
18149
18150        try {
18151            final XmlPullParser parser = Xml.newPullParser();
18152            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18153            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
18154                    new BlobXmlRestorer() {
18155                        @Override
18156                        public void apply(XmlPullParser parser, int userId)
18157                                throws XmlPullParserException, IOException {
18158                            synchronized (mPackages) {
18159                                mSettings.readDefaultAppsLPw(parser, userId);
18160                            }
18161                        }
18162                    } );
18163        } catch (Exception e) {
18164            if (DEBUG_BACKUP) {
18165                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
18166            }
18167        }
18168    }
18169
18170    @Override
18171    public byte[] getIntentFilterVerificationBackup(int userId) {
18172        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18173            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
18174        }
18175
18176        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18177        try {
18178            final XmlSerializer serializer = new FastXmlSerializer();
18179            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18180            serializer.startDocument(null, true);
18181            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
18182
18183            synchronized (mPackages) {
18184                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
18185            }
18186
18187            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
18188            serializer.endDocument();
18189            serializer.flush();
18190        } catch (Exception e) {
18191            if (DEBUG_BACKUP) {
18192                Slog.e(TAG, "Unable to write default apps for backup", e);
18193            }
18194            return null;
18195        }
18196
18197        return dataStream.toByteArray();
18198    }
18199
18200    @Override
18201    public void restoreIntentFilterVerification(byte[] backup, int userId) {
18202        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18203            throw new SecurityException("Only the system may call restorePreferredActivities()");
18204        }
18205
18206        try {
18207            final XmlPullParser parser = Xml.newPullParser();
18208            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18209            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
18210                    new BlobXmlRestorer() {
18211                        @Override
18212                        public void apply(XmlPullParser parser, int userId)
18213                                throws XmlPullParserException, IOException {
18214                            synchronized (mPackages) {
18215                                mSettings.readAllDomainVerificationsLPr(parser, userId);
18216                                mSettings.writeLPr();
18217                            }
18218                        }
18219                    } );
18220        } catch (Exception e) {
18221            if (DEBUG_BACKUP) {
18222                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18223            }
18224        }
18225    }
18226
18227    @Override
18228    public byte[] getPermissionGrantBackup(int userId) {
18229        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18230            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
18231        }
18232
18233        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18234        try {
18235            final XmlSerializer serializer = new FastXmlSerializer();
18236            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18237            serializer.startDocument(null, true);
18238            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18239
18240            synchronized (mPackages) {
18241                serializeRuntimePermissionGrantsLPr(serializer, userId);
18242            }
18243
18244            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18245            serializer.endDocument();
18246            serializer.flush();
18247        } catch (Exception e) {
18248            if (DEBUG_BACKUP) {
18249                Slog.e(TAG, "Unable to write default apps for backup", e);
18250            }
18251            return null;
18252        }
18253
18254        return dataStream.toByteArray();
18255    }
18256
18257    @Override
18258    public void restorePermissionGrants(byte[] backup, int userId) {
18259        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18260            throw new SecurityException("Only the system may call restorePermissionGrants()");
18261        }
18262
18263        try {
18264            final XmlPullParser parser = Xml.newPullParser();
18265            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18266            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18267                    new BlobXmlRestorer() {
18268                        @Override
18269                        public void apply(XmlPullParser parser, int userId)
18270                                throws XmlPullParserException, IOException {
18271                            synchronized (mPackages) {
18272                                processRestoredPermissionGrantsLPr(parser, userId);
18273                            }
18274                        }
18275                    } );
18276        } catch (Exception e) {
18277            if (DEBUG_BACKUP) {
18278                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18279            }
18280        }
18281    }
18282
18283    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18284            throws IOException {
18285        serializer.startTag(null, TAG_ALL_GRANTS);
18286
18287        final int N = mSettings.mPackages.size();
18288        for (int i = 0; i < N; i++) {
18289            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18290            boolean pkgGrantsKnown = false;
18291
18292            PermissionsState packagePerms = ps.getPermissionsState();
18293
18294            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18295                final int grantFlags = state.getFlags();
18296                // only look at grants that are not system/policy fixed
18297                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18298                    final boolean isGranted = state.isGranted();
18299                    // And only back up the user-twiddled state bits
18300                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18301                        final String packageName = mSettings.mPackages.keyAt(i);
18302                        if (!pkgGrantsKnown) {
18303                            serializer.startTag(null, TAG_GRANT);
18304                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18305                            pkgGrantsKnown = true;
18306                        }
18307
18308                        final boolean userSet =
18309                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18310                        final boolean userFixed =
18311                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18312                        final boolean revoke =
18313                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18314
18315                        serializer.startTag(null, TAG_PERMISSION);
18316                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18317                        if (isGranted) {
18318                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18319                        }
18320                        if (userSet) {
18321                            serializer.attribute(null, ATTR_USER_SET, "true");
18322                        }
18323                        if (userFixed) {
18324                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18325                        }
18326                        if (revoke) {
18327                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18328                        }
18329                        serializer.endTag(null, TAG_PERMISSION);
18330                    }
18331                }
18332            }
18333
18334            if (pkgGrantsKnown) {
18335                serializer.endTag(null, TAG_GRANT);
18336            }
18337        }
18338
18339        serializer.endTag(null, TAG_ALL_GRANTS);
18340    }
18341
18342    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18343            throws XmlPullParserException, IOException {
18344        String pkgName = null;
18345        int outerDepth = parser.getDepth();
18346        int type;
18347        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18348                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18349            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18350                continue;
18351            }
18352
18353            final String tagName = parser.getName();
18354            if (tagName.equals(TAG_GRANT)) {
18355                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18356                if (DEBUG_BACKUP) {
18357                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18358                }
18359            } else if (tagName.equals(TAG_PERMISSION)) {
18360
18361                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18362                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18363
18364                int newFlagSet = 0;
18365                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18366                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18367                }
18368                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18369                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18370                }
18371                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18372                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18373                }
18374                if (DEBUG_BACKUP) {
18375                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18376                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18377                }
18378                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18379                if (ps != null) {
18380                    // Already installed so we apply the grant immediately
18381                    if (DEBUG_BACKUP) {
18382                        Slog.v(TAG, "        + already installed; applying");
18383                    }
18384                    PermissionsState perms = ps.getPermissionsState();
18385                    BasePermission bp = mSettings.mPermissions.get(permName);
18386                    if (bp != null) {
18387                        if (isGranted) {
18388                            perms.grantRuntimePermission(bp, userId);
18389                        }
18390                        if (newFlagSet != 0) {
18391                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18392                        }
18393                    }
18394                } else {
18395                    // Need to wait for post-restore install to apply the grant
18396                    if (DEBUG_BACKUP) {
18397                        Slog.v(TAG, "        - not yet installed; saving for later");
18398                    }
18399                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18400                            isGranted, newFlagSet, userId);
18401                }
18402            } else {
18403                PackageManagerService.reportSettingsProblem(Log.WARN,
18404                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18405                XmlUtils.skipCurrentTag(parser);
18406            }
18407        }
18408
18409        scheduleWriteSettingsLocked();
18410        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18411    }
18412
18413    @Override
18414    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18415            int sourceUserId, int targetUserId, int flags) {
18416        mContext.enforceCallingOrSelfPermission(
18417                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18418        int callingUid = Binder.getCallingUid();
18419        enforceOwnerRights(ownerPackage, callingUid);
18420        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18421        if (intentFilter.countActions() == 0) {
18422            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18423            return;
18424        }
18425        synchronized (mPackages) {
18426            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18427                    ownerPackage, targetUserId, flags);
18428            CrossProfileIntentResolver resolver =
18429                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18430            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18431            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18432            if (existing != null) {
18433                int size = existing.size();
18434                for (int i = 0; i < size; i++) {
18435                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18436                        return;
18437                    }
18438                }
18439            }
18440            resolver.addFilter(newFilter);
18441            scheduleWritePackageRestrictionsLocked(sourceUserId);
18442        }
18443    }
18444
18445    @Override
18446    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18447        mContext.enforceCallingOrSelfPermission(
18448                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18449        int callingUid = Binder.getCallingUid();
18450        enforceOwnerRights(ownerPackage, callingUid);
18451        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18452        synchronized (mPackages) {
18453            CrossProfileIntentResolver resolver =
18454                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18455            ArraySet<CrossProfileIntentFilter> set =
18456                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18457            for (CrossProfileIntentFilter filter : set) {
18458                if (filter.getOwnerPackage().equals(ownerPackage)) {
18459                    resolver.removeFilter(filter);
18460                }
18461            }
18462            scheduleWritePackageRestrictionsLocked(sourceUserId);
18463        }
18464    }
18465
18466    // Enforcing that callingUid is owning pkg on userId
18467    private void enforceOwnerRights(String pkg, int callingUid) {
18468        // The system owns everything.
18469        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18470            return;
18471        }
18472        int callingUserId = UserHandle.getUserId(callingUid);
18473        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18474        if (pi == null) {
18475            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18476                    + callingUserId);
18477        }
18478        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18479            throw new SecurityException("Calling uid " + callingUid
18480                    + " does not own package " + pkg);
18481        }
18482    }
18483
18484    @Override
18485    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18486        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18487    }
18488
18489    private Intent getHomeIntent() {
18490        Intent intent = new Intent(Intent.ACTION_MAIN);
18491        intent.addCategory(Intent.CATEGORY_HOME);
18492        intent.addCategory(Intent.CATEGORY_DEFAULT);
18493        return intent;
18494    }
18495
18496    private IntentFilter getHomeFilter() {
18497        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18498        filter.addCategory(Intent.CATEGORY_HOME);
18499        filter.addCategory(Intent.CATEGORY_DEFAULT);
18500        return filter;
18501    }
18502
18503    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18504            int userId) {
18505        Intent intent  = getHomeIntent();
18506        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18507                PackageManager.GET_META_DATA, userId);
18508        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18509                true, false, false, userId);
18510
18511        allHomeCandidates.clear();
18512        if (list != null) {
18513            for (ResolveInfo ri : list) {
18514                allHomeCandidates.add(ri);
18515            }
18516        }
18517        return (preferred == null || preferred.activityInfo == null)
18518                ? null
18519                : new ComponentName(preferred.activityInfo.packageName,
18520                        preferred.activityInfo.name);
18521    }
18522
18523    @Override
18524    public void setHomeActivity(ComponentName comp, int userId) {
18525        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18526        getHomeActivitiesAsUser(homeActivities, userId);
18527
18528        boolean found = false;
18529
18530        final int size = homeActivities.size();
18531        final ComponentName[] set = new ComponentName[size];
18532        for (int i = 0; i < size; i++) {
18533            final ResolveInfo candidate = homeActivities.get(i);
18534            final ActivityInfo info = candidate.activityInfo;
18535            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18536            set[i] = activityName;
18537            if (!found && activityName.equals(comp)) {
18538                found = true;
18539            }
18540        }
18541        if (!found) {
18542            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18543                    + userId);
18544        }
18545        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18546                set, comp, userId);
18547    }
18548
18549    private @Nullable String getSetupWizardPackageName() {
18550        final Intent intent = new Intent(Intent.ACTION_MAIN);
18551        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18552
18553        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18554                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18555                        | MATCH_DISABLED_COMPONENTS,
18556                UserHandle.myUserId());
18557        if (matches.size() == 1) {
18558            return matches.get(0).getComponentInfo().packageName;
18559        } else {
18560            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18561                    + ": matches=" + matches);
18562            return null;
18563        }
18564    }
18565
18566    private @Nullable String getStorageManagerPackageName() {
18567        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18568
18569        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18570                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18571                        | MATCH_DISABLED_COMPONENTS,
18572                UserHandle.myUserId());
18573        if (matches.size() == 1) {
18574            return matches.get(0).getComponentInfo().packageName;
18575        } else {
18576            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18577                    + matches.size() + ": matches=" + matches);
18578            return null;
18579        }
18580    }
18581
18582    @Override
18583    public void setApplicationEnabledSetting(String appPackageName,
18584            int newState, int flags, int userId, String callingPackage) {
18585        if (!sUserManager.exists(userId)) return;
18586        if (callingPackage == null) {
18587            callingPackage = Integer.toString(Binder.getCallingUid());
18588        }
18589        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18590    }
18591
18592    @Override
18593    public void setComponentEnabledSetting(ComponentName componentName,
18594            int newState, int flags, int userId) {
18595        if (!sUserManager.exists(userId)) return;
18596        setEnabledSetting(componentName.getPackageName(),
18597                componentName.getClassName(), newState, flags, userId, null);
18598    }
18599
18600    private void setEnabledSetting(final String packageName, String className, int newState,
18601            final int flags, int userId, String callingPackage) {
18602        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18603              || newState == COMPONENT_ENABLED_STATE_ENABLED
18604              || newState == COMPONENT_ENABLED_STATE_DISABLED
18605              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18606              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18607            throw new IllegalArgumentException("Invalid new component state: "
18608                    + newState);
18609        }
18610        PackageSetting pkgSetting;
18611        final int uid = Binder.getCallingUid();
18612        final int permission;
18613        if (uid == Process.SYSTEM_UID) {
18614            permission = PackageManager.PERMISSION_GRANTED;
18615        } else {
18616            permission = mContext.checkCallingOrSelfPermission(
18617                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18618        }
18619        enforceCrossUserPermission(uid, userId,
18620                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18621        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18622        boolean sendNow = false;
18623        boolean isApp = (className == null);
18624        String componentName = isApp ? packageName : className;
18625        int packageUid = -1;
18626        ArrayList<String> components;
18627
18628        // writer
18629        synchronized (mPackages) {
18630            pkgSetting = mSettings.mPackages.get(packageName);
18631            if (pkgSetting == null) {
18632                if (className == null) {
18633                    throw new IllegalArgumentException("Unknown package: " + packageName);
18634                }
18635                throw new IllegalArgumentException(
18636                        "Unknown component: " + packageName + "/" + className);
18637            }
18638        }
18639
18640        // Limit who can change which apps
18641        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18642            // Don't allow apps that don't have permission to modify other apps
18643            if (!allowedByPermission) {
18644                throw new SecurityException(
18645                        "Permission Denial: attempt to change component state from pid="
18646                        + Binder.getCallingPid()
18647                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18648            }
18649            // Don't allow changing protected packages.
18650            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18651                throw new SecurityException("Cannot disable a protected package: " + packageName);
18652            }
18653        }
18654
18655        synchronized (mPackages) {
18656            if (uid == Process.SHELL_UID
18657                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18658                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18659                // unless it is a test package.
18660                int oldState = pkgSetting.getEnabled(userId);
18661                if (className == null
18662                    &&
18663                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18664                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18665                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18666                    &&
18667                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18668                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18669                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18670                    // ok
18671                } else {
18672                    throw new SecurityException(
18673                            "Shell cannot change component state for " + packageName + "/"
18674                            + className + " to " + newState);
18675                }
18676            }
18677            if (className == null) {
18678                // We're dealing with an application/package level state change
18679                if (pkgSetting.getEnabled(userId) == newState) {
18680                    // Nothing to do
18681                    return;
18682                }
18683                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18684                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18685                    // Don't care about who enables an app.
18686                    callingPackage = null;
18687                }
18688                pkgSetting.setEnabled(newState, userId, callingPackage);
18689                // pkgSetting.pkg.mSetEnabled = newState;
18690            } else {
18691                // We're dealing with a component level state change
18692                // First, verify that this is a valid class name.
18693                PackageParser.Package pkg = pkgSetting.pkg;
18694                if (pkg == null || !pkg.hasComponentClassName(className)) {
18695                    if (pkg != null &&
18696                            pkg.applicationInfo.targetSdkVersion >=
18697                                    Build.VERSION_CODES.JELLY_BEAN) {
18698                        throw new IllegalArgumentException("Component class " + className
18699                                + " does not exist in " + packageName);
18700                    } else {
18701                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18702                                + className + " does not exist in " + packageName);
18703                    }
18704                }
18705                switch (newState) {
18706                case COMPONENT_ENABLED_STATE_ENABLED:
18707                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18708                        return;
18709                    }
18710                    break;
18711                case COMPONENT_ENABLED_STATE_DISABLED:
18712                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18713                        return;
18714                    }
18715                    break;
18716                case COMPONENT_ENABLED_STATE_DEFAULT:
18717                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18718                        return;
18719                    }
18720                    break;
18721                default:
18722                    Slog.e(TAG, "Invalid new component state: " + newState);
18723                    return;
18724                }
18725            }
18726            scheduleWritePackageRestrictionsLocked(userId);
18727            components = mPendingBroadcasts.get(userId, packageName);
18728            final boolean newPackage = components == null;
18729            if (newPackage) {
18730                components = new ArrayList<String>();
18731            }
18732            if (!components.contains(componentName)) {
18733                components.add(componentName);
18734            }
18735            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18736                sendNow = true;
18737                // Purge entry from pending broadcast list if another one exists already
18738                // since we are sending one right away.
18739                mPendingBroadcasts.remove(userId, packageName);
18740            } else {
18741                if (newPackage) {
18742                    mPendingBroadcasts.put(userId, packageName, components);
18743                }
18744                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18745                    // Schedule a message
18746                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18747                }
18748            }
18749        }
18750
18751        long callingId = Binder.clearCallingIdentity();
18752        try {
18753            if (sendNow) {
18754                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18755                sendPackageChangedBroadcast(packageName,
18756                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18757            }
18758        } finally {
18759            Binder.restoreCallingIdentity(callingId);
18760        }
18761    }
18762
18763    @Override
18764    public void flushPackageRestrictionsAsUser(int userId) {
18765        if (!sUserManager.exists(userId)) {
18766            return;
18767        }
18768        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18769                false /* checkShell */, "flushPackageRestrictions");
18770        synchronized (mPackages) {
18771            mSettings.writePackageRestrictionsLPr(userId);
18772            mDirtyUsers.remove(userId);
18773            if (mDirtyUsers.isEmpty()) {
18774                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18775            }
18776        }
18777    }
18778
18779    private void sendPackageChangedBroadcast(String packageName,
18780            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18781        if (DEBUG_INSTALL)
18782            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18783                    + componentNames);
18784        Bundle extras = new Bundle(4);
18785        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18786        String nameList[] = new String[componentNames.size()];
18787        componentNames.toArray(nameList);
18788        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18789        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18790        extras.putInt(Intent.EXTRA_UID, packageUid);
18791        // If this is not reporting a change of the overall package, then only send it
18792        // to registered receivers.  We don't want to launch a swath of apps for every
18793        // little component state change.
18794        final int flags = !componentNames.contains(packageName)
18795                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18796        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18797                new int[] {UserHandle.getUserId(packageUid)});
18798    }
18799
18800    @Override
18801    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18802        if (!sUserManager.exists(userId)) return;
18803        final int uid = Binder.getCallingUid();
18804        final int permission = mContext.checkCallingOrSelfPermission(
18805                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18806        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18807        enforceCrossUserPermission(uid, userId,
18808                true /* requireFullPermission */, true /* checkShell */, "stop package");
18809        // writer
18810        synchronized (mPackages) {
18811            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18812                    allowedByPermission, uid, userId)) {
18813                scheduleWritePackageRestrictionsLocked(userId);
18814            }
18815        }
18816    }
18817
18818    @Override
18819    public String getInstallerPackageName(String packageName) {
18820        // reader
18821        synchronized (mPackages) {
18822            return mSettings.getInstallerPackageNameLPr(packageName);
18823        }
18824    }
18825
18826    public boolean isOrphaned(String packageName) {
18827        // reader
18828        synchronized (mPackages) {
18829            return mSettings.isOrphaned(packageName);
18830        }
18831    }
18832
18833    @Override
18834    public int getApplicationEnabledSetting(String packageName, int userId) {
18835        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18836        int uid = Binder.getCallingUid();
18837        enforceCrossUserPermission(uid, userId,
18838                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18839        // reader
18840        synchronized (mPackages) {
18841            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18842        }
18843    }
18844
18845    @Override
18846    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18847        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18848        int uid = Binder.getCallingUid();
18849        enforceCrossUserPermission(uid, userId,
18850                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18851        // reader
18852        synchronized (mPackages) {
18853            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18854        }
18855    }
18856
18857    @Override
18858    public void enterSafeMode() {
18859        enforceSystemOrRoot("Only the system can request entering safe mode");
18860
18861        if (!mSystemReady) {
18862            mSafeMode = true;
18863        }
18864    }
18865
18866    @Override
18867    public void systemReady() {
18868        mSystemReady = true;
18869
18870        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18871        // disabled after already being started.
18872        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18873                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18874
18875        // Read the compatibilty setting when the system is ready.
18876        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18877                mContext.getContentResolver(),
18878                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18879        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18880        if (DEBUG_SETTINGS) {
18881            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18882        }
18883
18884        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18885
18886        synchronized (mPackages) {
18887            // Verify that all of the preferred activity components actually
18888            // exist.  It is possible for applications to be updated and at
18889            // that point remove a previously declared activity component that
18890            // had been set as a preferred activity.  We try to clean this up
18891            // the next time we encounter that preferred activity, but it is
18892            // possible for the user flow to never be able to return to that
18893            // situation so here we do a sanity check to make sure we haven't
18894            // left any junk around.
18895            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18896            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18897                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18898                removed.clear();
18899                for (PreferredActivity pa : pir.filterSet()) {
18900                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18901                        removed.add(pa);
18902                    }
18903                }
18904                if (removed.size() > 0) {
18905                    for (int r=0; r<removed.size(); r++) {
18906                        PreferredActivity pa = removed.get(r);
18907                        Slog.w(TAG, "Removing dangling preferred activity: "
18908                                + pa.mPref.mComponent);
18909                        pir.removeFilter(pa);
18910                    }
18911                    mSettings.writePackageRestrictionsLPr(
18912                            mSettings.mPreferredActivities.keyAt(i));
18913                }
18914            }
18915
18916            for (int userId : UserManagerService.getInstance().getUserIds()) {
18917                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18918                    grantPermissionsUserIds = ArrayUtils.appendInt(
18919                            grantPermissionsUserIds, userId);
18920                }
18921            }
18922        }
18923        sUserManager.systemReady();
18924
18925        // If we upgraded grant all default permissions before kicking off.
18926        for (int userId : grantPermissionsUserIds) {
18927            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18928        }
18929
18930        // If we did not grant default permissions, we preload from this the
18931        // default permission exceptions lazily to ensure we don't hit the
18932        // disk on a new user creation.
18933        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18934            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18935        }
18936
18937        // Kick off any messages waiting for system ready
18938        if (mPostSystemReadyMessages != null) {
18939            for (Message msg : mPostSystemReadyMessages) {
18940                msg.sendToTarget();
18941            }
18942            mPostSystemReadyMessages = null;
18943        }
18944
18945        // Watch for external volumes that come and go over time
18946        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18947        storage.registerListener(mStorageListener);
18948
18949        mInstallerService.systemReady();
18950        mPackageDexOptimizer.systemReady();
18951
18952        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18953                StorageManagerInternal.class);
18954        StorageManagerInternal.addExternalStoragePolicy(
18955                new StorageManagerInternal.ExternalStorageMountPolicy() {
18956            @Override
18957            public int getMountMode(int uid, String packageName) {
18958                if (Process.isIsolated(uid)) {
18959                    return Zygote.MOUNT_EXTERNAL_NONE;
18960                }
18961                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18962                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18963                }
18964                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18965                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18966                }
18967                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18968                    return Zygote.MOUNT_EXTERNAL_READ;
18969                }
18970                return Zygote.MOUNT_EXTERNAL_WRITE;
18971            }
18972
18973            @Override
18974            public boolean hasExternalStorage(int uid, String packageName) {
18975                return true;
18976            }
18977        });
18978
18979        // Now that we're mostly running, clean up stale users and apps
18980        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18981        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18982    }
18983
18984    @Override
18985    public boolean isSafeMode() {
18986        return mSafeMode;
18987    }
18988
18989    @Override
18990    public boolean hasSystemUidErrors() {
18991        return mHasSystemUidErrors;
18992    }
18993
18994    static String arrayToString(int[] array) {
18995        StringBuffer buf = new StringBuffer(128);
18996        buf.append('[');
18997        if (array != null) {
18998            for (int i=0; i<array.length; i++) {
18999                if (i > 0) buf.append(", ");
19000                buf.append(array[i]);
19001            }
19002        }
19003        buf.append(']');
19004        return buf.toString();
19005    }
19006
19007    static class DumpState {
19008        public static final int DUMP_LIBS = 1 << 0;
19009        public static final int DUMP_FEATURES = 1 << 1;
19010        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19011        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19012        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
19013        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
19014        public static final int DUMP_PERMISSIONS = 1 << 6;
19015        public static final int DUMP_PACKAGES = 1 << 7;
19016        public static final int DUMP_SHARED_USERS = 1 << 8;
19017        public static final int DUMP_MESSAGES = 1 << 9;
19018        public static final int DUMP_PROVIDERS = 1 << 10;
19019        public static final int DUMP_VERIFIERS = 1 << 11;
19020        public static final int DUMP_PREFERRED = 1 << 12;
19021        public static final int DUMP_PREFERRED_XML = 1 << 13;
19022        public static final int DUMP_KEYSETS = 1 << 14;
19023        public static final int DUMP_VERSION = 1 << 15;
19024        public static final int DUMP_INSTALLS = 1 << 16;
19025        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
19026        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
19027        public static final int DUMP_FROZEN = 1 << 19;
19028        public static final int DUMP_DEXOPT = 1 << 20;
19029        public static final int DUMP_COMPILER_STATS = 1 << 21;
19030
19031        public static final int OPTION_SHOW_FILTERS = 1 << 0;
19032
19033        private int mTypes;
19034
19035        private int mOptions;
19036
19037        private boolean mTitlePrinted;
19038
19039        private SharedUserSetting mSharedUser;
19040
19041        public boolean isDumping(int type) {
19042            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
19043                return true;
19044            }
19045
19046            return (mTypes & type) != 0;
19047        }
19048
19049        public void setDump(int type) {
19050            mTypes |= type;
19051        }
19052
19053        public boolean isOptionEnabled(int option) {
19054            return (mOptions & option) != 0;
19055        }
19056
19057        public void setOptionEnabled(int option) {
19058            mOptions |= option;
19059        }
19060
19061        public boolean onTitlePrinted() {
19062            final boolean printed = mTitlePrinted;
19063            mTitlePrinted = true;
19064            return printed;
19065        }
19066
19067        public boolean getTitlePrinted() {
19068            return mTitlePrinted;
19069        }
19070
19071        public void setTitlePrinted(boolean enabled) {
19072            mTitlePrinted = enabled;
19073        }
19074
19075        public SharedUserSetting getSharedUser() {
19076            return mSharedUser;
19077        }
19078
19079        public void setSharedUser(SharedUserSetting user) {
19080            mSharedUser = user;
19081        }
19082    }
19083
19084    @Override
19085    public void onShellCommand(FileDescriptor in, FileDescriptor out,
19086            FileDescriptor err, String[] args, ShellCallback callback,
19087            ResultReceiver resultReceiver) {
19088        (new PackageManagerShellCommand(this)).exec(
19089                this, in, out, err, args, callback, resultReceiver);
19090    }
19091
19092    @Override
19093    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
19094        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
19095                != PackageManager.PERMISSION_GRANTED) {
19096            pw.println("Permission Denial: can't dump ActivityManager from from pid="
19097                    + Binder.getCallingPid()
19098                    + ", uid=" + Binder.getCallingUid()
19099                    + " without permission "
19100                    + android.Manifest.permission.DUMP);
19101            return;
19102        }
19103
19104        DumpState dumpState = new DumpState();
19105        boolean fullPreferred = false;
19106        boolean checkin = false;
19107
19108        String packageName = null;
19109        ArraySet<String> permissionNames = null;
19110
19111        int opti = 0;
19112        while (opti < args.length) {
19113            String opt = args[opti];
19114            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
19115                break;
19116            }
19117            opti++;
19118
19119            if ("-a".equals(opt)) {
19120                // Right now we only know how to print all.
19121            } else if ("-h".equals(opt)) {
19122                pw.println("Package manager dump options:");
19123                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
19124                pw.println("    --checkin: dump for a checkin");
19125                pw.println("    -f: print details of intent filters");
19126                pw.println("    -h: print this help");
19127                pw.println("  cmd may be one of:");
19128                pw.println("    l[ibraries]: list known shared libraries");
19129                pw.println("    f[eatures]: list device features");
19130                pw.println("    k[eysets]: print known keysets");
19131                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
19132                pw.println("    perm[issions]: dump permissions");
19133                pw.println("    permission [name ...]: dump declaration and use of given permission");
19134                pw.println("    pref[erred]: print preferred package settings");
19135                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
19136                pw.println("    prov[iders]: dump content providers");
19137                pw.println("    p[ackages]: dump installed packages");
19138                pw.println("    s[hared-users]: dump shared user IDs");
19139                pw.println("    m[essages]: print collected runtime messages");
19140                pw.println("    v[erifiers]: print package verifier info");
19141                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
19142                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
19143                pw.println("    version: print database version info");
19144                pw.println("    write: write current settings now");
19145                pw.println("    installs: details about install sessions");
19146                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
19147                pw.println("    dexopt: dump dexopt state");
19148                pw.println("    compiler-stats: dump compiler statistics");
19149                pw.println("    <package.name>: info about given package");
19150                return;
19151            } else if ("--checkin".equals(opt)) {
19152                checkin = true;
19153            } else if ("-f".equals(opt)) {
19154                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19155            } else {
19156                pw.println("Unknown argument: " + opt + "; use -h for help");
19157            }
19158        }
19159
19160        // Is the caller requesting to dump a particular piece of data?
19161        if (opti < args.length) {
19162            String cmd = args[opti];
19163            opti++;
19164            // Is this a package name?
19165            if ("android".equals(cmd) || cmd.contains(".")) {
19166                packageName = cmd;
19167                // When dumping a single package, we always dump all of its
19168                // filter information since the amount of data will be reasonable.
19169                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
19170            } else if ("check-permission".equals(cmd)) {
19171                if (opti >= args.length) {
19172                    pw.println("Error: check-permission missing permission argument");
19173                    return;
19174                }
19175                String perm = args[opti];
19176                opti++;
19177                if (opti >= args.length) {
19178                    pw.println("Error: check-permission missing package argument");
19179                    return;
19180                }
19181                String pkg = args[opti];
19182                opti++;
19183                int user = UserHandle.getUserId(Binder.getCallingUid());
19184                if (opti < args.length) {
19185                    try {
19186                        user = Integer.parseInt(args[opti]);
19187                    } catch (NumberFormatException e) {
19188                        pw.println("Error: check-permission user argument is not a number: "
19189                                + args[opti]);
19190                        return;
19191                    }
19192                }
19193                pw.println(checkPermission(perm, pkg, user));
19194                return;
19195            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
19196                dumpState.setDump(DumpState.DUMP_LIBS);
19197            } else if ("f".equals(cmd) || "features".equals(cmd)) {
19198                dumpState.setDump(DumpState.DUMP_FEATURES);
19199            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
19200                if (opti >= args.length) {
19201                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
19202                            | DumpState.DUMP_SERVICE_RESOLVERS
19203                            | DumpState.DUMP_RECEIVER_RESOLVERS
19204                            | DumpState.DUMP_CONTENT_RESOLVERS);
19205                } else {
19206                    while (opti < args.length) {
19207                        String name = args[opti];
19208                        if ("a".equals(name) || "activity".equals(name)) {
19209                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
19210                        } else if ("s".equals(name) || "service".equals(name)) {
19211                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
19212                        } else if ("r".equals(name) || "receiver".equals(name)) {
19213                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
19214                        } else if ("c".equals(name) || "content".equals(name)) {
19215                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
19216                        } else {
19217                            pw.println("Error: unknown resolver table type: " + name);
19218                            return;
19219                        }
19220                        opti++;
19221                    }
19222                }
19223            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
19224                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
19225            } else if ("permission".equals(cmd)) {
19226                if (opti >= args.length) {
19227                    pw.println("Error: permission requires permission name");
19228                    return;
19229                }
19230                permissionNames = new ArraySet<>();
19231                while (opti < args.length) {
19232                    permissionNames.add(args[opti]);
19233                    opti++;
19234                }
19235                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19236                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19237            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19238                dumpState.setDump(DumpState.DUMP_PREFERRED);
19239            } else if ("preferred-xml".equals(cmd)) {
19240                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19241                if (opti < args.length && "--full".equals(args[opti])) {
19242                    fullPreferred = true;
19243                    opti++;
19244                }
19245            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19246                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19247            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19248                dumpState.setDump(DumpState.DUMP_PACKAGES);
19249            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19250                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19251            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19252                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19253            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19254                dumpState.setDump(DumpState.DUMP_MESSAGES);
19255            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19256                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19257            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19258                    || "intent-filter-verifiers".equals(cmd)) {
19259                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19260            } else if ("version".equals(cmd)) {
19261                dumpState.setDump(DumpState.DUMP_VERSION);
19262            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19263                dumpState.setDump(DumpState.DUMP_KEYSETS);
19264            } else if ("installs".equals(cmd)) {
19265                dumpState.setDump(DumpState.DUMP_INSTALLS);
19266            } else if ("frozen".equals(cmd)) {
19267                dumpState.setDump(DumpState.DUMP_FROZEN);
19268            } else if ("dexopt".equals(cmd)) {
19269                dumpState.setDump(DumpState.DUMP_DEXOPT);
19270            } else if ("compiler-stats".equals(cmd)) {
19271                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19272            } else if ("write".equals(cmd)) {
19273                synchronized (mPackages) {
19274                    mSettings.writeLPr();
19275                    pw.println("Settings written.");
19276                    return;
19277                }
19278            }
19279        }
19280
19281        if (checkin) {
19282            pw.println("vers,1");
19283        }
19284
19285        // reader
19286        synchronized (mPackages) {
19287            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19288                if (!checkin) {
19289                    if (dumpState.onTitlePrinted())
19290                        pw.println();
19291                    pw.println("Database versions:");
19292                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19293                }
19294            }
19295
19296            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19297                if (!checkin) {
19298                    if (dumpState.onTitlePrinted())
19299                        pw.println();
19300                    pw.println("Verifiers:");
19301                    pw.print("  Required: ");
19302                    pw.print(mRequiredVerifierPackage);
19303                    pw.print(" (uid=");
19304                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19305                            UserHandle.USER_SYSTEM));
19306                    pw.println(")");
19307                } else if (mRequiredVerifierPackage != null) {
19308                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19309                    pw.print(",");
19310                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19311                            UserHandle.USER_SYSTEM));
19312                }
19313            }
19314
19315            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19316                    packageName == null) {
19317                if (mIntentFilterVerifierComponent != null) {
19318                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19319                    if (!checkin) {
19320                        if (dumpState.onTitlePrinted())
19321                            pw.println();
19322                        pw.println("Intent Filter Verifier:");
19323                        pw.print("  Using: ");
19324                        pw.print(verifierPackageName);
19325                        pw.print(" (uid=");
19326                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19327                                UserHandle.USER_SYSTEM));
19328                        pw.println(")");
19329                    } else if (verifierPackageName != null) {
19330                        pw.print("ifv,"); pw.print(verifierPackageName);
19331                        pw.print(",");
19332                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19333                                UserHandle.USER_SYSTEM));
19334                    }
19335                } else {
19336                    pw.println();
19337                    pw.println("No Intent Filter Verifier available!");
19338                }
19339            }
19340
19341            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19342                boolean printedHeader = false;
19343                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19344                while (it.hasNext()) {
19345                    String name = it.next();
19346                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19347                    if (!checkin) {
19348                        if (!printedHeader) {
19349                            if (dumpState.onTitlePrinted())
19350                                pw.println();
19351                            pw.println("Libraries:");
19352                            printedHeader = true;
19353                        }
19354                        pw.print("  ");
19355                    } else {
19356                        pw.print("lib,");
19357                    }
19358                    pw.print(name);
19359                    if (!checkin) {
19360                        pw.print(" -> ");
19361                    }
19362                    if (ent.path != null) {
19363                        if (!checkin) {
19364                            pw.print("(jar) ");
19365                            pw.print(ent.path);
19366                        } else {
19367                            pw.print(",jar,");
19368                            pw.print(ent.path);
19369                        }
19370                    } else {
19371                        if (!checkin) {
19372                            pw.print("(apk) ");
19373                            pw.print(ent.apk);
19374                        } else {
19375                            pw.print(",apk,");
19376                            pw.print(ent.apk);
19377                        }
19378                    }
19379                    pw.println();
19380                }
19381            }
19382
19383            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19384                if (dumpState.onTitlePrinted())
19385                    pw.println();
19386                if (!checkin) {
19387                    pw.println("Features:");
19388                }
19389
19390                for (FeatureInfo feat : mAvailableFeatures.values()) {
19391                    if (checkin) {
19392                        pw.print("feat,");
19393                        pw.print(feat.name);
19394                        pw.print(",");
19395                        pw.println(feat.version);
19396                    } else {
19397                        pw.print("  ");
19398                        pw.print(feat.name);
19399                        if (feat.version > 0) {
19400                            pw.print(" version=");
19401                            pw.print(feat.version);
19402                        }
19403                        pw.println();
19404                    }
19405                }
19406            }
19407
19408            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19409                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19410                        : "Activity Resolver Table:", "  ", packageName,
19411                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19412                    dumpState.setTitlePrinted(true);
19413                }
19414            }
19415            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19416                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19417                        : "Receiver Resolver Table:", "  ", packageName,
19418                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19419                    dumpState.setTitlePrinted(true);
19420                }
19421            }
19422            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19423                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19424                        : "Service Resolver Table:", "  ", packageName,
19425                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19426                    dumpState.setTitlePrinted(true);
19427                }
19428            }
19429            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19430                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19431                        : "Provider Resolver Table:", "  ", packageName,
19432                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19433                    dumpState.setTitlePrinted(true);
19434                }
19435            }
19436
19437            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19438                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19439                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19440                    int user = mSettings.mPreferredActivities.keyAt(i);
19441                    if (pir.dump(pw,
19442                            dumpState.getTitlePrinted()
19443                                ? "\nPreferred Activities User " + user + ":"
19444                                : "Preferred Activities User " + user + ":", "  ",
19445                            packageName, true, false)) {
19446                        dumpState.setTitlePrinted(true);
19447                    }
19448                }
19449            }
19450
19451            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19452                pw.flush();
19453                FileOutputStream fout = new FileOutputStream(fd);
19454                BufferedOutputStream str = new BufferedOutputStream(fout);
19455                XmlSerializer serializer = new FastXmlSerializer();
19456                try {
19457                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19458                    serializer.startDocument(null, true);
19459                    serializer.setFeature(
19460                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19461                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19462                    serializer.endDocument();
19463                    serializer.flush();
19464                } catch (IllegalArgumentException e) {
19465                    pw.println("Failed writing: " + e);
19466                } catch (IllegalStateException e) {
19467                    pw.println("Failed writing: " + e);
19468                } catch (IOException e) {
19469                    pw.println("Failed writing: " + e);
19470                }
19471            }
19472
19473            if (!checkin
19474                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19475                    && packageName == null) {
19476                pw.println();
19477                int count = mSettings.mPackages.size();
19478                if (count == 0) {
19479                    pw.println("No applications!");
19480                    pw.println();
19481                } else {
19482                    final String prefix = "  ";
19483                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19484                    if (allPackageSettings.size() == 0) {
19485                        pw.println("No domain preferred apps!");
19486                        pw.println();
19487                    } else {
19488                        pw.println("App verification status:");
19489                        pw.println();
19490                        count = 0;
19491                        for (PackageSetting ps : allPackageSettings) {
19492                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19493                            if (ivi == null || ivi.getPackageName() == null) continue;
19494                            pw.println(prefix + "Package: " + ivi.getPackageName());
19495                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19496                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19497                            pw.println();
19498                            count++;
19499                        }
19500                        if (count == 0) {
19501                            pw.println(prefix + "No app verification established.");
19502                            pw.println();
19503                        }
19504                        for (int userId : sUserManager.getUserIds()) {
19505                            pw.println("App linkages for user " + userId + ":");
19506                            pw.println();
19507                            count = 0;
19508                            for (PackageSetting ps : allPackageSettings) {
19509                                final long status = ps.getDomainVerificationStatusForUser(userId);
19510                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19511                                    continue;
19512                                }
19513                                pw.println(prefix + "Package: " + ps.name);
19514                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19515                                String statusStr = IntentFilterVerificationInfo.
19516                                        getStatusStringFromValue(status);
19517                                pw.println(prefix + "Status:  " + statusStr);
19518                                pw.println();
19519                                count++;
19520                            }
19521                            if (count == 0) {
19522                                pw.println(prefix + "No configured app linkages.");
19523                                pw.println();
19524                            }
19525                        }
19526                    }
19527                }
19528            }
19529
19530            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19531                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19532                if (packageName == null && permissionNames == null) {
19533                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19534                        if (iperm == 0) {
19535                            if (dumpState.onTitlePrinted())
19536                                pw.println();
19537                            pw.println("AppOp Permissions:");
19538                        }
19539                        pw.print("  AppOp Permission ");
19540                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19541                        pw.println(":");
19542                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19543                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19544                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19545                        }
19546                    }
19547                }
19548            }
19549
19550            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19551                boolean printedSomething = false;
19552                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19553                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19554                        continue;
19555                    }
19556                    if (!printedSomething) {
19557                        if (dumpState.onTitlePrinted())
19558                            pw.println();
19559                        pw.println("Registered ContentProviders:");
19560                        printedSomething = true;
19561                    }
19562                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19563                    pw.print("    "); pw.println(p.toString());
19564                }
19565                printedSomething = false;
19566                for (Map.Entry<String, PackageParser.Provider> entry :
19567                        mProvidersByAuthority.entrySet()) {
19568                    PackageParser.Provider p = entry.getValue();
19569                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19570                        continue;
19571                    }
19572                    if (!printedSomething) {
19573                        if (dumpState.onTitlePrinted())
19574                            pw.println();
19575                        pw.println("ContentProvider Authorities:");
19576                        printedSomething = true;
19577                    }
19578                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19579                    pw.print("    "); pw.println(p.toString());
19580                    if (p.info != null && p.info.applicationInfo != null) {
19581                        final String appInfo = p.info.applicationInfo.toString();
19582                        pw.print("      applicationInfo="); pw.println(appInfo);
19583                    }
19584                }
19585            }
19586
19587            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19588                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19589            }
19590
19591            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19592                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19593            }
19594
19595            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19596                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19597            }
19598
19599            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19600                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19601            }
19602
19603            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19604                // XXX should handle packageName != null by dumping only install data that
19605                // the given package is involved with.
19606                if (dumpState.onTitlePrinted()) pw.println();
19607                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19608            }
19609
19610            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19611                // XXX should handle packageName != null by dumping only install data that
19612                // the given package is involved with.
19613                if (dumpState.onTitlePrinted()) pw.println();
19614
19615                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19616                ipw.println();
19617                ipw.println("Frozen packages:");
19618                ipw.increaseIndent();
19619                if (mFrozenPackages.size() == 0) {
19620                    ipw.println("(none)");
19621                } else {
19622                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19623                        ipw.println(mFrozenPackages.valueAt(i));
19624                    }
19625                }
19626                ipw.decreaseIndent();
19627            }
19628
19629            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19630                if (dumpState.onTitlePrinted()) pw.println();
19631                dumpDexoptStateLPr(pw, packageName);
19632            }
19633
19634            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19635                if (dumpState.onTitlePrinted()) pw.println();
19636                dumpCompilerStatsLPr(pw, packageName);
19637            }
19638
19639            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19640                if (dumpState.onTitlePrinted()) pw.println();
19641                mSettings.dumpReadMessagesLPr(pw, dumpState);
19642
19643                pw.println();
19644                pw.println("Package warning messages:");
19645                BufferedReader in = null;
19646                String line = null;
19647                try {
19648                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19649                    while ((line = in.readLine()) != null) {
19650                        if (line.contains("ignored: updated version")) continue;
19651                        pw.println(line);
19652                    }
19653                } catch (IOException ignored) {
19654                } finally {
19655                    IoUtils.closeQuietly(in);
19656                }
19657            }
19658
19659            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19660                BufferedReader in = null;
19661                String line = null;
19662                try {
19663                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19664                    while ((line = in.readLine()) != null) {
19665                        if (line.contains("ignored: updated version")) continue;
19666                        pw.print("msg,");
19667                        pw.println(line);
19668                    }
19669                } catch (IOException ignored) {
19670                } finally {
19671                    IoUtils.closeQuietly(in);
19672                }
19673            }
19674        }
19675    }
19676
19677    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19678        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19679        ipw.println();
19680        ipw.println("Dexopt state:");
19681        ipw.increaseIndent();
19682        Collection<PackageParser.Package> packages = null;
19683        if (packageName != null) {
19684            PackageParser.Package targetPackage = mPackages.get(packageName);
19685            if (targetPackage != null) {
19686                packages = Collections.singletonList(targetPackage);
19687            } else {
19688                ipw.println("Unable to find package: " + packageName);
19689                return;
19690            }
19691        } else {
19692            packages = mPackages.values();
19693        }
19694
19695        for (PackageParser.Package pkg : packages) {
19696            ipw.println("[" + pkg.packageName + "]");
19697            ipw.increaseIndent();
19698            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19699            ipw.decreaseIndent();
19700        }
19701    }
19702
19703    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19704        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19705        ipw.println();
19706        ipw.println("Compiler stats:");
19707        ipw.increaseIndent();
19708        Collection<PackageParser.Package> packages = null;
19709        if (packageName != null) {
19710            PackageParser.Package targetPackage = mPackages.get(packageName);
19711            if (targetPackage != null) {
19712                packages = Collections.singletonList(targetPackage);
19713            } else {
19714                ipw.println("Unable to find package: " + packageName);
19715                return;
19716            }
19717        } else {
19718            packages = mPackages.values();
19719        }
19720
19721        for (PackageParser.Package pkg : packages) {
19722            ipw.println("[" + pkg.packageName + "]");
19723            ipw.increaseIndent();
19724
19725            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19726            if (stats == null) {
19727                ipw.println("(No recorded stats)");
19728            } else {
19729                stats.dump(ipw);
19730            }
19731            ipw.decreaseIndent();
19732        }
19733    }
19734
19735    private String dumpDomainString(String packageName) {
19736        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19737                .getList();
19738        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19739
19740        ArraySet<String> result = new ArraySet<>();
19741        if (iviList.size() > 0) {
19742            for (IntentFilterVerificationInfo ivi : iviList) {
19743                for (String host : ivi.getDomains()) {
19744                    result.add(host);
19745                }
19746            }
19747        }
19748        if (filters != null && filters.size() > 0) {
19749            for (IntentFilter filter : filters) {
19750                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19751                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19752                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19753                    result.addAll(filter.getHostsList());
19754                }
19755            }
19756        }
19757
19758        StringBuilder sb = new StringBuilder(result.size() * 16);
19759        for (String domain : result) {
19760            if (sb.length() > 0) sb.append(" ");
19761            sb.append(domain);
19762        }
19763        return sb.toString();
19764    }
19765
19766    // ------- apps on sdcard specific code -------
19767    static final boolean DEBUG_SD_INSTALL = false;
19768
19769    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19770
19771    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19772
19773    private boolean mMediaMounted = false;
19774
19775    static String getEncryptKey() {
19776        try {
19777            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19778                    SD_ENCRYPTION_KEYSTORE_NAME);
19779            if (sdEncKey == null) {
19780                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19781                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19782                if (sdEncKey == null) {
19783                    Slog.e(TAG, "Failed to create encryption keys");
19784                    return null;
19785                }
19786            }
19787            return sdEncKey;
19788        } catch (NoSuchAlgorithmException nsae) {
19789            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19790            return null;
19791        } catch (IOException ioe) {
19792            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19793            return null;
19794        }
19795    }
19796
19797    /*
19798     * Update media status on PackageManager.
19799     */
19800    @Override
19801    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19802        int callingUid = Binder.getCallingUid();
19803        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19804            throw new SecurityException("Media status can only be updated by the system");
19805        }
19806        // reader; this apparently protects mMediaMounted, but should probably
19807        // be a different lock in that case.
19808        synchronized (mPackages) {
19809            Log.i(TAG, "Updating external media status from "
19810                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19811                    + (mediaStatus ? "mounted" : "unmounted"));
19812            if (DEBUG_SD_INSTALL)
19813                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19814                        + ", mMediaMounted=" + mMediaMounted);
19815            if (mediaStatus == mMediaMounted) {
19816                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19817                        : 0, -1);
19818                mHandler.sendMessage(msg);
19819                return;
19820            }
19821            mMediaMounted = mediaStatus;
19822        }
19823        // Queue up an async operation since the package installation may take a
19824        // little while.
19825        mHandler.post(new Runnable() {
19826            public void run() {
19827                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19828            }
19829        });
19830    }
19831
19832    /**
19833     * Called by StorageManagerService when the initial ASECs to scan are available.
19834     * Should block until all the ASEC containers are finished being scanned.
19835     */
19836    public void scanAvailableAsecs() {
19837        updateExternalMediaStatusInner(true, false, false);
19838    }
19839
19840    /*
19841     * Collect information of applications on external media, map them against
19842     * existing containers and update information based on current mount status.
19843     * Please note that we always have to report status if reportStatus has been
19844     * set to true especially when unloading packages.
19845     */
19846    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19847            boolean externalStorage) {
19848        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19849        int[] uidArr = EmptyArray.INT;
19850
19851        final String[] list = PackageHelper.getSecureContainerList();
19852        if (ArrayUtils.isEmpty(list)) {
19853            Log.i(TAG, "No secure containers found");
19854        } else {
19855            // Process list of secure containers and categorize them
19856            // as active or stale based on their package internal state.
19857
19858            // reader
19859            synchronized (mPackages) {
19860                for (String cid : list) {
19861                    // Leave stages untouched for now; installer service owns them
19862                    if (PackageInstallerService.isStageName(cid)) continue;
19863
19864                    if (DEBUG_SD_INSTALL)
19865                        Log.i(TAG, "Processing container " + cid);
19866                    String pkgName = getAsecPackageName(cid);
19867                    if (pkgName == null) {
19868                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19869                        continue;
19870                    }
19871                    if (DEBUG_SD_INSTALL)
19872                        Log.i(TAG, "Looking for pkg : " + pkgName);
19873
19874                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19875                    if (ps == null) {
19876                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19877                        continue;
19878                    }
19879
19880                    /*
19881                     * Skip packages that are not external if we're unmounting
19882                     * external storage.
19883                     */
19884                    if (externalStorage && !isMounted && !isExternal(ps)) {
19885                        continue;
19886                    }
19887
19888                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19889                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19890                    // The package status is changed only if the code path
19891                    // matches between settings and the container id.
19892                    if (ps.codePathString != null
19893                            && ps.codePathString.startsWith(args.getCodePath())) {
19894                        if (DEBUG_SD_INSTALL) {
19895                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19896                                    + " at code path: " + ps.codePathString);
19897                        }
19898
19899                        // We do have a valid package installed on sdcard
19900                        processCids.put(args, ps.codePathString);
19901                        final int uid = ps.appId;
19902                        if (uid != -1) {
19903                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19904                        }
19905                    } else {
19906                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19907                                + ps.codePathString);
19908                    }
19909                }
19910            }
19911
19912            Arrays.sort(uidArr);
19913        }
19914
19915        // Process packages with valid entries.
19916        if (isMounted) {
19917            if (DEBUG_SD_INSTALL)
19918                Log.i(TAG, "Loading packages");
19919            loadMediaPackages(processCids, uidArr, externalStorage);
19920            startCleaningPackages();
19921            mInstallerService.onSecureContainersAvailable();
19922        } else {
19923            if (DEBUG_SD_INSTALL)
19924                Log.i(TAG, "Unloading packages");
19925            unloadMediaPackages(processCids, uidArr, reportStatus);
19926        }
19927    }
19928
19929    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19930            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19931        final int size = infos.size();
19932        final String[] packageNames = new String[size];
19933        final int[] packageUids = new int[size];
19934        for (int i = 0; i < size; i++) {
19935            final ApplicationInfo info = infos.get(i);
19936            packageNames[i] = info.packageName;
19937            packageUids[i] = info.uid;
19938        }
19939        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19940                finishedReceiver);
19941    }
19942
19943    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19944            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19945        sendResourcesChangedBroadcast(mediaStatus, replacing,
19946                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19947    }
19948
19949    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19950            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19951        int size = pkgList.length;
19952        if (size > 0) {
19953            // Send broadcasts here
19954            Bundle extras = new Bundle();
19955            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19956            if (uidArr != null) {
19957                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19958            }
19959            if (replacing) {
19960                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19961            }
19962            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19963                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19964            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19965        }
19966    }
19967
19968   /*
19969     * Look at potentially valid container ids from processCids If package
19970     * information doesn't match the one on record or package scanning fails,
19971     * the cid is added to list of removeCids. We currently don't delete stale
19972     * containers.
19973     */
19974    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19975            boolean externalStorage) {
19976        ArrayList<String> pkgList = new ArrayList<String>();
19977        Set<AsecInstallArgs> keys = processCids.keySet();
19978
19979        for (AsecInstallArgs args : keys) {
19980            String codePath = processCids.get(args);
19981            if (DEBUG_SD_INSTALL)
19982                Log.i(TAG, "Loading container : " + args.cid);
19983            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19984            try {
19985                // Make sure there are no container errors first.
19986                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19987                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19988                            + " when installing from sdcard");
19989                    continue;
19990                }
19991                // Check code path here.
19992                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19993                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19994                            + " does not match one in settings " + codePath);
19995                    continue;
19996                }
19997                // Parse package
19998                int parseFlags = mDefParseFlags;
19999                if (args.isExternalAsec()) {
20000                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20001                }
20002                if (args.isFwdLocked()) {
20003                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20004                }
20005
20006                synchronized (mInstallLock) {
20007                    PackageParser.Package pkg = null;
20008                    try {
20009                        // Sadly we don't know the package name yet to freeze it
20010                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
20011                                SCAN_IGNORE_FROZEN, 0, null);
20012                    } catch (PackageManagerException e) {
20013                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
20014                    }
20015                    // Scan the package
20016                    if (pkg != null) {
20017                        /*
20018                         * TODO why is the lock being held? doPostInstall is
20019                         * called in other places without the lock. This needs
20020                         * to be straightened out.
20021                         */
20022                        // writer
20023                        synchronized (mPackages) {
20024                            retCode = PackageManager.INSTALL_SUCCEEDED;
20025                            pkgList.add(pkg.packageName);
20026                            // Post process args
20027                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
20028                                    pkg.applicationInfo.uid);
20029                        }
20030                    } else {
20031                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
20032                    }
20033                }
20034
20035            } finally {
20036                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
20037                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
20038                }
20039            }
20040        }
20041        // writer
20042        synchronized (mPackages) {
20043            // If the platform SDK has changed since the last time we booted,
20044            // we need to re-grant app permission to catch any new ones that
20045            // appear. This is really a hack, and means that apps can in some
20046            // cases get permissions that the user didn't initially explicitly
20047            // allow... it would be nice to have some better way to handle
20048            // this situation.
20049            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
20050                    : mSettings.getInternalVersion();
20051            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
20052                    : StorageManager.UUID_PRIVATE_INTERNAL;
20053
20054            int updateFlags = UPDATE_PERMISSIONS_ALL;
20055            if (ver.sdkVersion != mSdkVersion) {
20056                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20057                        + mSdkVersion + "; regranting permissions for external");
20058                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20059            }
20060            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20061
20062            // Yay, everything is now upgraded
20063            ver.forceCurrent();
20064
20065            // can downgrade to reader
20066            // Persist settings
20067            mSettings.writeLPr();
20068        }
20069        // Send a broadcast to let everyone know we are done processing
20070        if (pkgList.size() > 0) {
20071            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
20072        }
20073    }
20074
20075   /*
20076     * Utility method to unload a list of specified containers
20077     */
20078    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
20079        // Just unmount all valid containers.
20080        for (AsecInstallArgs arg : cidArgs) {
20081            synchronized (mInstallLock) {
20082                arg.doPostDeleteLI(false);
20083           }
20084       }
20085   }
20086
20087    /*
20088     * Unload packages mounted on external media. This involves deleting package
20089     * data from internal structures, sending broadcasts about disabled packages,
20090     * gc'ing to free up references, unmounting all secure containers
20091     * corresponding to packages on external media, and posting a
20092     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
20093     * that we always have to post this message if status has been requested no
20094     * matter what.
20095     */
20096    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
20097            final boolean reportStatus) {
20098        if (DEBUG_SD_INSTALL)
20099            Log.i(TAG, "unloading media packages");
20100        ArrayList<String> pkgList = new ArrayList<String>();
20101        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
20102        final Set<AsecInstallArgs> keys = processCids.keySet();
20103        for (AsecInstallArgs args : keys) {
20104            String pkgName = args.getPackageName();
20105            if (DEBUG_SD_INSTALL)
20106                Log.i(TAG, "Trying to unload pkg : " + pkgName);
20107            // Delete package internally
20108            PackageRemovedInfo outInfo = new PackageRemovedInfo();
20109            synchronized (mInstallLock) {
20110                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20111                final boolean res;
20112                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
20113                        "unloadMediaPackages")) {
20114                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
20115                            null);
20116                }
20117                if (res) {
20118                    pkgList.add(pkgName);
20119                } else {
20120                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
20121                    failedList.add(args);
20122                }
20123            }
20124        }
20125
20126        // reader
20127        synchronized (mPackages) {
20128            // We didn't update the settings after removing each package;
20129            // write them now for all packages.
20130            mSettings.writeLPr();
20131        }
20132
20133        // We have to absolutely send UPDATED_MEDIA_STATUS only
20134        // after confirming that all the receivers processed the ordered
20135        // broadcast when packages get disabled, force a gc to clean things up.
20136        // and unload all the containers.
20137        if (pkgList.size() > 0) {
20138            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
20139                    new IIntentReceiver.Stub() {
20140                public void performReceive(Intent intent, int resultCode, String data,
20141                        Bundle extras, boolean ordered, boolean sticky,
20142                        int sendingUser) throws RemoteException {
20143                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
20144                            reportStatus ? 1 : 0, 1, keys);
20145                    mHandler.sendMessage(msg);
20146                }
20147            });
20148        } else {
20149            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
20150                    keys);
20151            mHandler.sendMessage(msg);
20152        }
20153    }
20154
20155    private void loadPrivatePackages(final VolumeInfo vol) {
20156        mHandler.post(new Runnable() {
20157            @Override
20158            public void run() {
20159                loadPrivatePackagesInner(vol);
20160            }
20161        });
20162    }
20163
20164    private void loadPrivatePackagesInner(VolumeInfo vol) {
20165        final String volumeUuid = vol.fsUuid;
20166        if (TextUtils.isEmpty(volumeUuid)) {
20167            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
20168            return;
20169        }
20170
20171        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
20172        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
20173        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
20174
20175        final VersionInfo ver;
20176        final List<PackageSetting> packages;
20177        synchronized (mPackages) {
20178            ver = mSettings.findOrCreateVersion(volumeUuid);
20179            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20180        }
20181
20182        for (PackageSetting ps : packages) {
20183            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
20184            synchronized (mInstallLock) {
20185                final PackageParser.Package pkg;
20186                try {
20187                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
20188                    loaded.add(pkg.applicationInfo);
20189
20190                } catch (PackageManagerException e) {
20191                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
20192                }
20193
20194                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
20195                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
20196                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
20197                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20198                }
20199            }
20200        }
20201
20202        // Reconcile app data for all started/unlocked users
20203        final StorageManager sm = mContext.getSystemService(StorageManager.class);
20204        final UserManager um = mContext.getSystemService(UserManager.class);
20205        UserManagerInternal umInternal = getUserManagerInternal();
20206        for (UserInfo user : um.getUsers()) {
20207            final int flags;
20208            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20209                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20210            } else if (umInternal.isUserRunning(user.id)) {
20211                flags = StorageManager.FLAG_STORAGE_DE;
20212            } else {
20213                continue;
20214            }
20215
20216            try {
20217                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
20218                synchronized (mInstallLock) {
20219                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
20220                }
20221            } catch (IllegalStateException e) {
20222                // Device was probably ejected, and we'll process that event momentarily
20223                Slog.w(TAG, "Failed to prepare storage: " + e);
20224            }
20225        }
20226
20227        synchronized (mPackages) {
20228            int updateFlags = UPDATE_PERMISSIONS_ALL;
20229            if (ver.sdkVersion != mSdkVersion) {
20230                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
20231                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20232                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20233            }
20234            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20235
20236            // Yay, everything is now upgraded
20237            ver.forceCurrent();
20238
20239            mSettings.writeLPr();
20240        }
20241
20242        for (PackageFreezer freezer : freezers) {
20243            freezer.close();
20244        }
20245
20246        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20247        sendResourcesChangedBroadcast(true, false, loaded, null);
20248    }
20249
20250    private void unloadPrivatePackages(final VolumeInfo vol) {
20251        mHandler.post(new Runnable() {
20252            @Override
20253            public void run() {
20254                unloadPrivatePackagesInner(vol);
20255            }
20256        });
20257    }
20258
20259    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20260        final String volumeUuid = vol.fsUuid;
20261        if (TextUtils.isEmpty(volumeUuid)) {
20262            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20263            return;
20264        }
20265
20266        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20267        synchronized (mInstallLock) {
20268        synchronized (mPackages) {
20269            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20270            for (PackageSetting ps : packages) {
20271                if (ps.pkg == null) continue;
20272
20273                final ApplicationInfo info = ps.pkg.applicationInfo;
20274                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20275                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20276
20277                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20278                        "unloadPrivatePackagesInner")) {
20279                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20280                            false, null)) {
20281                        unloaded.add(info);
20282                    } else {
20283                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20284                    }
20285                }
20286
20287                // Try very hard to release any references to this package
20288                // so we don't risk the system server being killed due to
20289                // open FDs
20290                AttributeCache.instance().removePackage(ps.name);
20291            }
20292
20293            mSettings.writeLPr();
20294        }
20295        }
20296
20297        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20298        sendResourcesChangedBroadcast(false, false, unloaded, null);
20299
20300        // Try very hard to release any references to this path so we don't risk
20301        // the system server being killed due to open FDs
20302        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20303
20304        for (int i = 0; i < 3; i++) {
20305            System.gc();
20306            System.runFinalization();
20307        }
20308    }
20309
20310    /**
20311     * Prepare storage areas for given user on all mounted devices.
20312     */
20313    void prepareUserData(int userId, int userSerial, int flags) {
20314        synchronized (mInstallLock) {
20315            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20316            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20317                final String volumeUuid = vol.getFsUuid();
20318                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20319            }
20320        }
20321    }
20322
20323    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20324            boolean allowRecover) {
20325        // Prepare storage and verify that serial numbers are consistent; if
20326        // there's a mismatch we need to destroy to avoid leaking data
20327        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20328        try {
20329            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20330
20331            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20332                UserManagerService.enforceSerialNumber(
20333                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20334                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20335                    UserManagerService.enforceSerialNumber(
20336                            Environment.getDataSystemDeDirectory(userId), userSerial);
20337                }
20338            }
20339            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20340                UserManagerService.enforceSerialNumber(
20341                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20342                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20343                    UserManagerService.enforceSerialNumber(
20344                            Environment.getDataSystemCeDirectory(userId), userSerial);
20345                }
20346            }
20347
20348            synchronized (mInstallLock) {
20349                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20350            }
20351        } catch (Exception e) {
20352            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20353                    + " because we failed to prepare: " + e);
20354            destroyUserDataLI(volumeUuid, userId,
20355                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20356
20357            if (allowRecover) {
20358                // Try one last time; if we fail again we're really in trouble
20359                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20360            }
20361        }
20362    }
20363
20364    /**
20365     * Destroy storage areas for given user on all mounted devices.
20366     */
20367    void destroyUserData(int userId, int flags) {
20368        synchronized (mInstallLock) {
20369            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20370            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20371                final String volumeUuid = vol.getFsUuid();
20372                destroyUserDataLI(volumeUuid, userId, flags);
20373            }
20374        }
20375    }
20376
20377    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20378        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20379        try {
20380            // Clean up app data, profile data, and media data
20381            mInstaller.destroyUserData(volumeUuid, userId, flags);
20382
20383            // Clean up system data
20384            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20385                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20386                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20387                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20388                }
20389                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20390                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20391                }
20392            }
20393
20394            // Data with special labels is now gone, so finish the job
20395            storage.destroyUserStorage(volumeUuid, userId, flags);
20396
20397        } catch (Exception e) {
20398            logCriticalInfo(Log.WARN,
20399                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20400        }
20401    }
20402
20403    /**
20404     * Examine all users present on given mounted volume, and destroy data
20405     * belonging to users that are no longer valid, or whose user ID has been
20406     * recycled.
20407     */
20408    private void reconcileUsers(String volumeUuid) {
20409        final List<File> files = new ArrayList<>();
20410        Collections.addAll(files, FileUtils
20411                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20412        Collections.addAll(files, FileUtils
20413                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20414        Collections.addAll(files, FileUtils
20415                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20416        Collections.addAll(files, FileUtils
20417                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20418        for (File file : files) {
20419            if (!file.isDirectory()) continue;
20420
20421            final int userId;
20422            final UserInfo info;
20423            try {
20424                userId = Integer.parseInt(file.getName());
20425                info = sUserManager.getUserInfo(userId);
20426            } catch (NumberFormatException e) {
20427                Slog.w(TAG, "Invalid user directory " + file);
20428                continue;
20429            }
20430
20431            boolean destroyUser = false;
20432            if (info == null) {
20433                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20434                        + " because no matching user was found");
20435                destroyUser = true;
20436            } else if (!mOnlyCore) {
20437                try {
20438                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20439                } catch (IOException e) {
20440                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20441                            + " because we failed to enforce serial number: " + e);
20442                    destroyUser = true;
20443                }
20444            }
20445
20446            if (destroyUser) {
20447                synchronized (mInstallLock) {
20448                    destroyUserDataLI(volumeUuid, userId,
20449                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20450                }
20451            }
20452        }
20453    }
20454
20455    private void assertPackageKnown(String volumeUuid, String packageName)
20456            throws PackageManagerException {
20457        synchronized (mPackages) {
20458            // Normalize package name to handle renamed packages
20459            packageName = normalizePackageNameLPr(packageName);
20460
20461            final PackageSetting ps = mSettings.mPackages.get(packageName);
20462            if (ps == null) {
20463                throw new PackageManagerException("Package " + packageName + " is unknown");
20464            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20465                throw new PackageManagerException(
20466                        "Package " + packageName + " found on unknown volume " + volumeUuid
20467                                + "; expected volume " + ps.volumeUuid);
20468            }
20469        }
20470    }
20471
20472    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20473            throws PackageManagerException {
20474        synchronized (mPackages) {
20475            // Normalize package name to handle renamed packages
20476            packageName = normalizePackageNameLPr(packageName);
20477
20478            final PackageSetting ps = mSettings.mPackages.get(packageName);
20479            if (ps == null) {
20480                throw new PackageManagerException("Package " + packageName + " is unknown");
20481            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20482                throw new PackageManagerException(
20483                        "Package " + packageName + " found on unknown volume " + volumeUuid
20484                                + "; expected volume " + ps.volumeUuid);
20485            } else if (!ps.getInstalled(userId)) {
20486                throw new PackageManagerException(
20487                        "Package " + packageName + " not installed for user " + userId);
20488            }
20489        }
20490    }
20491
20492    /**
20493     * Examine all apps present on given mounted volume, and destroy apps that
20494     * aren't expected, either due to uninstallation or reinstallation on
20495     * another volume.
20496     */
20497    private void reconcileApps(String volumeUuid) {
20498        final File[] files = FileUtils
20499                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20500        for (File file : files) {
20501            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20502                    && !PackageInstallerService.isStageName(file.getName());
20503            if (!isPackage) {
20504                // Ignore entries which are not packages
20505                continue;
20506            }
20507
20508            try {
20509                final PackageLite pkg = PackageParser.parsePackageLite(file,
20510                        PackageParser.PARSE_MUST_BE_APK);
20511                assertPackageKnown(volumeUuid, pkg.packageName);
20512
20513            } catch (PackageParserException | PackageManagerException e) {
20514                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20515                synchronized (mInstallLock) {
20516                    removeCodePathLI(file);
20517                }
20518            }
20519        }
20520    }
20521
20522    /**
20523     * Reconcile all app data for the given user.
20524     * <p>
20525     * Verifies that directories exist and that ownership and labeling is
20526     * correct for all installed apps on all mounted volumes.
20527     */
20528    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20529        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20530        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20531            final String volumeUuid = vol.getFsUuid();
20532            synchronized (mInstallLock) {
20533                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20534            }
20535        }
20536    }
20537
20538    /**
20539     * Reconcile all app data on given mounted volume.
20540     * <p>
20541     * Destroys app data that isn't expected, either due to uninstallation or
20542     * reinstallation on another volume.
20543     * <p>
20544     * Verifies that directories exist and that ownership and labeling is
20545     * correct for all installed apps.
20546     */
20547    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20548            boolean migrateAppData) {
20549        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20550                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20551
20552        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20553        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20554
20555        // First look for stale data that doesn't belong, and check if things
20556        // have changed since we did our last restorecon
20557        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20558            if (StorageManager.isFileEncryptedNativeOrEmulated()
20559                    && !StorageManager.isUserKeyUnlocked(userId)) {
20560                throw new RuntimeException(
20561                        "Yikes, someone asked us to reconcile CE storage while " + userId
20562                                + " was still locked; this would have caused massive data loss!");
20563            }
20564
20565            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20566            for (File file : files) {
20567                final String packageName = file.getName();
20568                try {
20569                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20570                } catch (PackageManagerException e) {
20571                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20572                    try {
20573                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20574                                StorageManager.FLAG_STORAGE_CE, 0);
20575                    } catch (InstallerException e2) {
20576                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20577                    }
20578                }
20579            }
20580        }
20581        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20582            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20583            for (File file : files) {
20584                final String packageName = file.getName();
20585                try {
20586                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20587                } catch (PackageManagerException e) {
20588                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20589                    try {
20590                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20591                                StorageManager.FLAG_STORAGE_DE, 0);
20592                    } catch (InstallerException e2) {
20593                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20594                    }
20595                }
20596            }
20597        }
20598
20599        // Ensure that data directories are ready to roll for all packages
20600        // installed for this volume and user
20601        final List<PackageSetting> packages;
20602        synchronized (mPackages) {
20603            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20604        }
20605        int preparedCount = 0;
20606        for (PackageSetting ps : packages) {
20607            final String packageName = ps.name;
20608            if (ps.pkg == null) {
20609                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20610                // TODO: might be due to legacy ASEC apps; we should circle back
20611                // and reconcile again once they're scanned
20612                continue;
20613            }
20614
20615            if (ps.getInstalled(userId)) {
20616                prepareAppDataLIF(ps.pkg, userId, flags);
20617
20618                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20619                    // We may have just shuffled around app data directories, so
20620                    // prepare them one more time
20621                    prepareAppDataLIF(ps.pkg, userId, flags);
20622                }
20623
20624                preparedCount++;
20625            }
20626        }
20627
20628        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20629    }
20630
20631    /**
20632     * Prepare app data for the given app just after it was installed or
20633     * upgraded. This method carefully only touches users that it's installed
20634     * for, and it forces a restorecon to handle any seinfo changes.
20635     * <p>
20636     * Verifies that directories exist and that ownership and labeling is
20637     * correct for all installed apps. If there is an ownership mismatch, it
20638     * will try recovering system apps by wiping data; third-party app data is
20639     * left intact.
20640     * <p>
20641     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20642     */
20643    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20644        final PackageSetting ps;
20645        synchronized (mPackages) {
20646            ps = mSettings.mPackages.get(pkg.packageName);
20647            mSettings.writeKernelMappingLPr(ps);
20648        }
20649
20650        final UserManager um = mContext.getSystemService(UserManager.class);
20651        UserManagerInternal umInternal = getUserManagerInternal();
20652        for (UserInfo user : um.getUsers()) {
20653            final int flags;
20654            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20655                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20656            } else if (umInternal.isUserRunning(user.id)) {
20657                flags = StorageManager.FLAG_STORAGE_DE;
20658            } else {
20659                continue;
20660            }
20661
20662            if (ps.getInstalled(user.id)) {
20663                // TODO: when user data is locked, mark that we're still dirty
20664                prepareAppDataLIF(pkg, user.id, flags);
20665            }
20666        }
20667    }
20668
20669    /**
20670     * Prepare app data for the given app.
20671     * <p>
20672     * Verifies that directories exist and that ownership and labeling is
20673     * correct for all installed apps. If there is an ownership mismatch, this
20674     * will try recovering system apps by wiping data; third-party app data is
20675     * left intact.
20676     */
20677    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20678        if (pkg == null) {
20679            Slog.wtf(TAG, "Package was null!", new Throwable());
20680            return;
20681        }
20682        prepareAppDataLeafLIF(pkg, userId, flags);
20683        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20684        for (int i = 0; i < childCount; i++) {
20685            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20686        }
20687    }
20688
20689    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20690        if (DEBUG_APP_DATA) {
20691            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20692                    + Integer.toHexString(flags));
20693        }
20694
20695        final String volumeUuid = pkg.volumeUuid;
20696        final String packageName = pkg.packageName;
20697        final ApplicationInfo app = pkg.applicationInfo;
20698        final int appId = UserHandle.getAppId(app.uid);
20699
20700        Preconditions.checkNotNull(app.seinfo);
20701
20702        long ceDataInode = -1;
20703        try {
20704            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20705                    appId, app.seinfo, app.targetSdkVersion);
20706        } catch (InstallerException e) {
20707            if (app.isSystemApp()) {
20708                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20709                        + ", but trying to recover: " + e);
20710                destroyAppDataLeafLIF(pkg, userId, flags);
20711                try {
20712                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20713                            appId, app.seinfo, app.targetSdkVersion);
20714                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20715                } catch (InstallerException e2) {
20716                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20717                }
20718            } else {
20719                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20720            }
20721        }
20722
20723        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20724            // TODO: mark this structure as dirty so we persist it!
20725            synchronized (mPackages) {
20726                final PackageSetting ps = mSettings.mPackages.get(packageName);
20727                if (ps != null) {
20728                    ps.setCeDataInode(ceDataInode, userId);
20729                }
20730            }
20731        }
20732
20733        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20734    }
20735
20736    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20737        if (pkg == null) {
20738            Slog.wtf(TAG, "Package was null!", new Throwable());
20739            return;
20740        }
20741        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20742        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20743        for (int i = 0; i < childCount; i++) {
20744            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20745        }
20746    }
20747
20748    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20749        final String volumeUuid = pkg.volumeUuid;
20750        final String packageName = pkg.packageName;
20751        final ApplicationInfo app = pkg.applicationInfo;
20752
20753        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20754            // Create a native library symlink only if we have native libraries
20755            // and if the native libraries are 32 bit libraries. We do not provide
20756            // this symlink for 64 bit libraries.
20757            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20758                final String nativeLibPath = app.nativeLibraryDir;
20759                try {
20760                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20761                            nativeLibPath, userId);
20762                } catch (InstallerException e) {
20763                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20764                }
20765            }
20766        }
20767    }
20768
20769    /**
20770     * For system apps on non-FBE devices, this method migrates any existing
20771     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20772     * requested by the app.
20773     */
20774    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20775        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20776                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20777            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20778                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20779            try {
20780                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20781                        storageTarget);
20782            } catch (InstallerException e) {
20783                logCriticalInfo(Log.WARN,
20784                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20785            }
20786            return true;
20787        } else {
20788            return false;
20789        }
20790    }
20791
20792    public PackageFreezer freezePackage(String packageName, String killReason) {
20793        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20794    }
20795
20796    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20797        return new PackageFreezer(packageName, userId, killReason);
20798    }
20799
20800    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20801            String killReason) {
20802        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20803    }
20804
20805    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20806            String killReason) {
20807        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20808            return new PackageFreezer();
20809        } else {
20810            return freezePackage(packageName, userId, killReason);
20811        }
20812    }
20813
20814    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20815            String killReason) {
20816        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20817    }
20818
20819    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20820            String killReason) {
20821        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20822            return new PackageFreezer();
20823        } else {
20824            return freezePackage(packageName, userId, killReason);
20825        }
20826    }
20827
20828    /**
20829     * Class that freezes and kills the given package upon creation, and
20830     * unfreezes it upon closing. This is typically used when doing surgery on
20831     * app code/data to prevent the app from running while you're working.
20832     */
20833    private class PackageFreezer implements AutoCloseable {
20834        private final String mPackageName;
20835        private final PackageFreezer[] mChildren;
20836
20837        private final boolean mWeFroze;
20838
20839        private final AtomicBoolean mClosed = new AtomicBoolean();
20840        private final CloseGuard mCloseGuard = CloseGuard.get();
20841
20842        /**
20843         * Create and return a stub freezer that doesn't actually do anything,
20844         * typically used when someone requested
20845         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20846         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20847         */
20848        public PackageFreezer() {
20849            mPackageName = null;
20850            mChildren = null;
20851            mWeFroze = false;
20852            mCloseGuard.open("close");
20853        }
20854
20855        public PackageFreezer(String packageName, int userId, String killReason) {
20856            synchronized (mPackages) {
20857                mPackageName = packageName;
20858                mWeFroze = mFrozenPackages.add(mPackageName);
20859
20860                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20861                if (ps != null) {
20862                    killApplication(ps.name, ps.appId, userId, killReason);
20863                }
20864
20865                final PackageParser.Package p = mPackages.get(packageName);
20866                if (p != null && p.childPackages != null) {
20867                    final int N = p.childPackages.size();
20868                    mChildren = new PackageFreezer[N];
20869                    for (int i = 0; i < N; i++) {
20870                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20871                                userId, killReason);
20872                    }
20873                } else {
20874                    mChildren = null;
20875                }
20876            }
20877            mCloseGuard.open("close");
20878        }
20879
20880        @Override
20881        protected void finalize() throws Throwable {
20882            try {
20883                mCloseGuard.warnIfOpen();
20884                close();
20885            } finally {
20886                super.finalize();
20887            }
20888        }
20889
20890        @Override
20891        public void close() {
20892            mCloseGuard.close();
20893            if (mClosed.compareAndSet(false, true)) {
20894                synchronized (mPackages) {
20895                    if (mWeFroze) {
20896                        mFrozenPackages.remove(mPackageName);
20897                    }
20898
20899                    if (mChildren != null) {
20900                        for (PackageFreezer freezer : mChildren) {
20901                            freezer.close();
20902                        }
20903                    }
20904                }
20905            }
20906        }
20907    }
20908
20909    /**
20910     * Verify that given package is currently frozen.
20911     */
20912    private void checkPackageFrozen(String packageName) {
20913        synchronized (mPackages) {
20914            if (!mFrozenPackages.contains(packageName)) {
20915                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20916            }
20917        }
20918    }
20919
20920    @Override
20921    public int movePackage(final String packageName, final String volumeUuid) {
20922        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20923
20924        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20925        final int moveId = mNextMoveId.getAndIncrement();
20926        mHandler.post(new Runnable() {
20927            @Override
20928            public void run() {
20929                try {
20930                    movePackageInternal(packageName, volumeUuid, moveId, user);
20931                } catch (PackageManagerException e) {
20932                    Slog.w(TAG, "Failed to move " + packageName, e);
20933                    mMoveCallbacks.notifyStatusChanged(moveId,
20934                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20935                }
20936            }
20937        });
20938        return moveId;
20939    }
20940
20941    private void movePackageInternal(final String packageName, final String volumeUuid,
20942            final int moveId, UserHandle user) throws PackageManagerException {
20943        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20944        final PackageManager pm = mContext.getPackageManager();
20945
20946        final boolean currentAsec;
20947        final String currentVolumeUuid;
20948        final File codeFile;
20949        final String installerPackageName;
20950        final String packageAbiOverride;
20951        final int appId;
20952        final String seinfo;
20953        final String label;
20954        final int targetSdkVersion;
20955        final PackageFreezer freezer;
20956        final int[] installedUserIds;
20957
20958        // reader
20959        synchronized (mPackages) {
20960            final PackageParser.Package pkg = mPackages.get(packageName);
20961            final PackageSetting ps = mSettings.mPackages.get(packageName);
20962            if (pkg == null || ps == null) {
20963                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20964            }
20965
20966            if (pkg.applicationInfo.isSystemApp()) {
20967                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20968                        "Cannot move system application");
20969            }
20970
20971            if (pkg.applicationInfo.isExternalAsec()) {
20972                currentAsec = true;
20973                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20974            } else if (pkg.applicationInfo.isForwardLocked()) {
20975                currentAsec = true;
20976                currentVolumeUuid = "forward_locked";
20977            } else {
20978                currentAsec = false;
20979                currentVolumeUuid = ps.volumeUuid;
20980
20981                final File probe = new File(pkg.codePath);
20982                final File probeOat = new File(probe, "oat");
20983                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20984                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20985                            "Move only supported for modern cluster style installs");
20986                }
20987            }
20988
20989            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20990                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20991                        "Package already moved to " + volumeUuid);
20992            }
20993            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20994                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20995                        "Device admin cannot be moved");
20996            }
20997
20998            if (mFrozenPackages.contains(packageName)) {
20999                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21000                        "Failed to move already frozen package");
21001            }
21002
21003            codeFile = new File(pkg.codePath);
21004            installerPackageName = ps.installerPackageName;
21005            packageAbiOverride = ps.cpuAbiOverrideString;
21006            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21007            seinfo = pkg.applicationInfo.seinfo;
21008            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21009            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21010            freezer = freezePackage(packageName, "movePackageInternal");
21011            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21012        }
21013
21014        final Bundle extras = new Bundle();
21015        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21016        extras.putString(Intent.EXTRA_TITLE, label);
21017        mMoveCallbacks.notifyCreated(moveId, extras);
21018
21019        int installFlags;
21020        final boolean moveCompleteApp;
21021        final File measurePath;
21022
21023        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21024            installFlags = INSTALL_INTERNAL;
21025            moveCompleteApp = !currentAsec;
21026            measurePath = Environment.getDataAppDirectory(volumeUuid);
21027        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21028            installFlags = INSTALL_EXTERNAL;
21029            moveCompleteApp = false;
21030            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21031        } else {
21032            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21033            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21034                    || !volume.isMountedWritable()) {
21035                freezer.close();
21036                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21037                        "Move location not mounted private volume");
21038            }
21039
21040            Preconditions.checkState(!currentAsec);
21041
21042            installFlags = INSTALL_INTERNAL;
21043            moveCompleteApp = true;
21044            measurePath = Environment.getDataAppDirectory(volumeUuid);
21045        }
21046
21047        final PackageStats stats = new PackageStats(null, -1);
21048        synchronized (mInstaller) {
21049            for (int userId : installedUserIds) {
21050                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21051                    freezer.close();
21052                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21053                            "Failed to measure package size");
21054                }
21055            }
21056        }
21057
21058        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21059                + stats.dataSize);
21060
21061        final long startFreeBytes = measurePath.getFreeSpace();
21062        final long sizeBytes;
21063        if (moveCompleteApp) {
21064            sizeBytes = stats.codeSize + stats.dataSize;
21065        } else {
21066            sizeBytes = stats.codeSize;
21067        }
21068
21069        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21070            freezer.close();
21071            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21072                    "Not enough free space to move");
21073        }
21074
21075        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21076
21077        final CountDownLatch installedLatch = new CountDownLatch(1);
21078        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21079            @Override
21080            public void onUserActionRequired(Intent intent) throws RemoteException {
21081                throw new IllegalStateException();
21082            }
21083
21084            @Override
21085            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21086                    Bundle extras) throws RemoteException {
21087                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21088                        + PackageManager.installStatusToString(returnCode, msg));
21089
21090                installedLatch.countDown();
21091                freezer.close();
21092
21093                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21094                switch (status) {
21095                    case PackageInstaller.STATUS_SUCCESS:
21096                        mMoveCallbacks.notifyStatusChanged(moveId,
21097                                PackageManager.MOVE_SUCCEEDED);
21098                        break;
21099                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21100                        mMoveCallbacks.notifyStatusChanged(moveId,
21101                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21102                        break;
21103                    default:
21104                        mMoveCallbacks.notifyStatusChanged(moveId,
21105                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21106                        break;
21107                }
21108            }
21109        };
21110
21111        final MoveInfo move;
21112        if (moveCompleteApp) {
21113            // Kick off a thread to report progress estimates
21114            new Thread() {
21115                @Override
21116                public void run() {
21117                    while (true) {
21118                        try {
21119                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21120                                break;
21121                            }
21122                        } catch (InterruptedException ignored) {
21123                        }
21124
21125                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
21126                        final int progress = 10 + (int) MathUtils.constrain(
21127                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21128                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21129                    }
21130                }
21131            }.start();
21132
21133            final String dataAppName = codeFile.getName();
21134            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21135                    dataAppName, appId, seinfo, targetSdkVersion);
21136        } else {
21137            move = null;
21138        }
21139
21140        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21141
21142        final Message msg = mHandler.obtainMessage(INIT_COPY);
21143        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21144        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21145                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21146                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21147                PackageManager.INSTALL_REASON_UNKNOWN);
21148        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21149        msg.obj = params;
21150
21151        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21152                System.identityHashCode(msg.obj));
21153        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21154                System.identityHashCode(msg.obj));
21155
21156        mHandler.sendMessage(msg);
21157    }
21158
21159    @Override
21160    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21162
21163        final int realMoveId = mNextMoveId.getAndIncrement();
21164        final Bundle extras = new Bundle();
21165        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21166        mMoveCallbacks.notifyCreated(realMoveId, extras);
21167
21168        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21169            @Override
21170            public void onCreated(int moveId, Bundle extras) {
21171                // Ignored
21172            }
21173
21174            @Override
21175            public void onStatusChanged(int moveId, int status, long estMillis) {
21176                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21177            }
21178        };
21179
21180        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21181        storage.setPrimaryStorageUuid(volumeUuid, callback);
21182        return realMoveId;
21183    }
21184
21185    @Override
21186    public int getMoveStatus(int moveId) {
21187        mContext.enforceCallingOrSelfPermission(
21188                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21189        return mMoveCallbacks.mLastStatus.get(moveId);
21190    }
21191
21192    @Override
21193    public void registerMoveCallback(IPackageMoveObserver callback) {
21194        mContext.enforceCallingOrSelfPermission(
21195                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21196        mMoveCallbacks.register(callback);
21197    }
21198
21199    @Override
21200    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21201        mContext.enforceCallingOrSelfPermission(
21202                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21203        mMoveCallbacks.unregister(callback);
21204    }
21205
21206    @Override
21207    public boolean setInstallLocation(int loc) {
21208        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21209                null);
21210        if (getInstallLocation() == loc) {
21211            return true;
21212        }
21213        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21214                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21215            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21216                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21217            return true;
21218        }
21219        return false;
21220   }
21221
21222    @Override
21223    public int getInstallLocation() {
21224        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21225                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21226                PackageHelper.APP_INSTALL_AUTO);
21227    }
21228
21229    /** Called by UserManagerService */
21230    void cleanUpUser(UserManagerService userManager, int userHandle) {
21231        synchronized (mPackages) {
21232            mDirtyUsers.remove(userHandle);
21233            mUserNeedsBadging.delete(userHandle);
21234            mSettings.removeUserLPw(userHandle);
21235            mPendingBroadcasts.remove(userHandle);
21236            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21237            removeUnusedPackagesLPw(userManager, userHandle);
21238        }
21239    }
21240
21241    /**
21242     * We're removing userHandle and would like to remove any downloaded packages
21243     * that are no longer in use by any other user.
21244     * @param userHandle the user being removed
21245     */
21246    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21247        final boolean DEBUG_CLEAN_APKS = false;
21248        int [] users = userManager.getUserIds();
21249        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21250        while (psit.hasNext()) {
21251            PackageSetting ps = psit.next();
21252            if (ps.pkg == null) {
21253                continue;
21254            }
21255            final String packageName = ps.pkg.packageName;
21256            // Skip over if system app
21257            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21258                continue;
21259            }
21260            if (DEBUG_CLEAN_APKS) {
21261                Slog.i(TAG, "Checking package " + packageName);
21262            }
21263            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21264            if (keep) {
21265                if (DEBUG_CLEAN_APKS) {
21266                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21267                }
21268            } else {
21269                for (int i = 0; i < users.length; i++) {
21270                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21271                        keep = true;
21272                        if (DEBUG_CLEAN_APKS) {
21273                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21274                                    + users[i]);
21275                        }
21276                        break;
21277                    }
21278                }
21279            }
21280            if (!keep) {
21281                if (DEBUG_CLEAN_APKS) {
21282                    Slog.i(TAG, "  Removing package " + packageName);
21283                }
21284                mHandler.post(new Runnable() {
21285                    public void run() {
21286                        deletePackageX(packageName, userHandle, 0);
21287                    } //end run
21288                });
21289            }
21290        }
21291    }
21292
21293    /** Called by UserManagerService */
21294    void createNewUser(int userId, String[] disallowedPackages) {
21295        synchronized (mInstallLock) {
21296            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21297        }
21298        synchronized (mPackages) {
21299            scheduleWritePackageRestrictionsLocked(userId);
21300            scheduleWritePackageListLocked(userId);
21301            applyFactoryDefaultBrowserLPw(userId);
21302            primeDomainVerificationsLPw(userId);
21303        }
21304    }
21305
21306    void onNewUserCreated(final int userId) {
21307        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21308        // If permission review for legacy apps is required, we represent
21309        // dagerous permissions for such apps as always granted runtime
21310        // permissions to keep per user flag state whether review is needed.
21311        // Hence, if a new user is added we have to propagate dangerous
21312        // permission grants for these legacy apps.
21313        if (mPermissionReviewRequired) {
21314            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21315                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21316        }
21317    }
21318
21319    @Override
21320    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21321        mContext.enforceCallingOrSelfPermission(
21322                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21323                "Only package verification agents can read the verifier device identity");
21324
21325        synchronized (mPackages) {
21326            return mSettings.getVerifierDeviceIdentityLPw();
21327        }
21328    }
21329
21330    @Override
21331    public void setPermissionEnforced(String permission, boolean enforced) {
21332        // TODO: Now that we no longer change GID for storage, this should to away.
21333        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21334                "setPermissionEnforced");
21335        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21336            synchronized (mPackages) {
21337                if (mSettings.mReadExternalStorageEnforced == null
21338                        || mSettings.mReadExternalStorageEnforced != enforced) {
21339                    mSettings.mReadExternalStorageEnforced = enforced;
21340                    mSettings.writeLPr();
21341                }
21342            }
21343            // kill any non-foreground processes so we restart them and
21344            // grant/revoke the GID.
21345            final IActivityManager am = ActivityManager.getService();
21346            if (am != null) {
21347                final long token = Binder.clearCallingIdentity();
21348                try {
21349                    am.killProcessesBelowForeground("setPermissionEnforcement");
21350                } catch (RemoteException e) {
21351                } finally {
21352                    Binder.restoreCallingIdentity(token);
21353                }
21354            }
21355        } else {
21356            throw new IllegalArgumentException("No selective enforcement for " + permission);
21357        }
21358    }
21359
21360    @Override
21361    @Deprecated
21362    public boolean isPermissionEnforced(String permission) {
21363        return true;
21364    }
21365
21366    @Override
21367    public boolean isStorageLow() {
21368        final long token = Binder.clearCallingIdentity();
21369        try {
21370            final DeviceStorageMonitorInternal
21371                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21372            if (dsm != null) {
21373                return dsm.isMemoryLow();
21374            } else {
21375                return false;
21376            }
21377        } finally {
21378            Binder.restoreCallingIdentity(token);
21379        }
21380    }
21381
21382    @Override
21383    public IPackageInstaller getPackageInstaller() {
21384        return mInstallerService;
21385    }
21386
21387    private boolean userNeedsBadging(int userId) {
21388        int index = mUserNeedsBadging.indexOfKey(userId);
21389        if (index < 0) {
21390            final UserInfo userInfo;
21391            final long token = Binder.clearCallingIdentity();
21392            try {
21393                userInfo = sUserManager.getUserInfo(userId);
21394            } finally {
21395                Binder.restoreCallingIdentity(token);
21396            }
21397            final boolean b;
21398            if (userInfo != null && userInfo.isManagedProfile()) {
21399                b = true;
21400            } else {
21401                b = false;
21402            }
21403            mUserNeedsBadging.put(userId, b);
21404            return b;
21405        }
21406        return mUserNeedsBadging.valueAt(index);
21407    }
21408
21409    @Override
21410    public KeySet getKeySetByAlias(String packageName, String alias) {
21411        if (packageName == null || alias == null) {
21412            return null;
21413        }
21414        synchronized(mPackages) {
21415            final PackageParser.Package pkg = mPackages.get(packageName);
21416            if (pkg == null) {
21417                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21418                throw new IllegalArgumentException("Unknown package: " + packageName);
21419            }
21420            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21421            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21422        }
21423    }
21424
21425    @Override
21426    public KeySet getSigningKeySet(String packageName) {
21427        if (packageName == null) {
21428            return null;
21429        }
21430        synchronized(mPackages) {
21431            final PackageParser.Package pkg = mPackages.get(packageName);
21432            if (pkg == null) {
21433                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21434                throw new IllegalArgumentException("Unknown package: " + packageName);
21435            }
21436            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21437                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21438                throw new SecurityException("May not access signing KeySet of other apps.");
21439            }
21440            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21441            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21442        }
21443    }
21444
21445    @Override
21446    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21447        if (packageName == null || ks == null) {
21448            return false;
21449        }
21450        synchronized(mPackages) {
21451            final PackageParser.Package pkg = mPackages.get(packageName);
21452            if (pkg == null) {
21453                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21454                throw new IllegalArgumentException("Unknown package: " + packageName);
21455            }
21456            IBinder ksh = ks.getToken();
21457            if (ksh instanceof KeySetHandle) {
21458                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21459                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21460            }
21461            return false;
21462        }
21463    }
21464
21465    @Override
21466    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21467        if (packageName == null || ks == null) {
21468            return false;
21469        }
21470        synchronized(mPackages) {
21471            final PackageParser.Package pkg = mPackages.get(packageName);
21472            if (pkg == null) {
21473                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21474                throw new IllegalArgumentException("Unknown package: " + packageName);
21475            }
21476            IBinder ksh = ks.getToken();
21477            if (ksh instanceof KeySetHandle) {
21478                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21479                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21480            }
21481            return false;
21482        }
21483    }
21484
21485    private void deletePackageIfUnusedLPr(final String packageName) {
21486        PackageSetting ps = mSettings.mPackages.get(packageName);
21487        if (ps == null) {
21488            return;
21489        }
21490        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21491            // TODO Implement atomic delete if package is unused
21492            // It is currently possible that the package will be deleted even if it is installed
21493            // after this method returns.
21494            mHandler.post(new Runnable() {
21495                public void run() {
21496                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21497                }
21498            });
21499        }
21500    }
21501
21502    /**
21503     * Check and throw if the given before/after packages would be considered a
21504     * downgrade.
21505     */
21506    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21507            throws PackageManagerException {
21508        if (after.versionCode < before.mVersionCode) {
21509            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21510                    "Update version code " + after.versionCode + " is older than current "
21511                    + before.mVersionCode);
21512        } else if (after.versionCode == before.mVersionCode) {
21513            if (after.baseRevisionCode < before.baseRevisionCode) {
21514                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21515                        "Update base revision code " + after.baseRevisionCode
21516                        + " is older than current " + before.baseRevisionCode);
21517            }
21518
21519            if (!ArrayUtils.isEmpty(after.splitNames)) {
21520                for (int i = 0; i < after.splitNames.length; i++) {
21521                    final String splitName = after.splitNames[i];
21522                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21523                    if (j != -1) {
21524                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21525                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21526                                    "Update split " + splitName + " revision code "
21527                                    + after.splitRevisionCodes[i] + " is older than current "
21528                                    + before.splitRevisionCodes[j]);
21529                        }
21530                    }
21531                }
21532            }
21533        }
21534    }
21535
21536    private static class MoveCallbacks extends Handler {
21537        private static final int MSG_CREATED = 1;
21538        private static final int MSG_STATUS_CHANGED = 2;
21539
21540        private final RemoteCallbackList<IPackageMoveObserver>
21541                mCallbacks = new RemoteCallbackList<>();
21542
21543        private final SparseIntArray mLastStatus = new SparseIntArray();
21544
21545        public MoveCallbacks(Looper looper) {
21546            super(looper);
21547        }
21548
21549        public void register(IPackageMoveObserver callback) {
21550            mCallbacks.register(callback);
21551        }
21552
21553        public void unregister(IPackageMoveObserver callback) {
21554            mCallbacks.unregister(callback);
21555        }
21556
21557        @Override
21558        public void handleMessage(Message msg) {
21559            final SomeArgs args = (SomeArgs) msg.obj;
21560            final int n = mCallbacks.beginBroadcast();
21561            for (int i = 0; i < n; i++) {
21562                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21563                try {
21564                    invokeCallback(callback, msg.what, args);
21565                } catch (RemoteException ignored) {
21566                }
21567            }
21568            mCallbacks.finishBroadcast();
21569            args.recycle();
21570        }
21571
21572        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21573                throws RemoteException {
21574            switch (what) {
21575                case MSG_CREATED: {
21576                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21577                    break;
21578                }
21579                case MSG_STATUS_CHANGED: {
21580                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21581                    break;
21582                }
21583            }
21584        }
21585
21586        private void notifyCreated(int moveId, Bundle extras) {
21587            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21588
21589            final SomeArgs args = SomeArgs.obtain();
21590            args.argi1 = moveId;
21591            args.arg2 = extras;
21592            obtainMessage(MSG_CREATED, args).sendToTarget();
21593        }
21594
21595        private void notifyStatusChanged(int moveId, int status) {
21596            notifyStatusChanged(moveId, status, -1);
21597        }
21598
21599        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21600            Slog.v(TAG, "Move " + moveId + " status " + status);
21601
21602            final SomeArgs args = SomeArgs.obtain();
21603            args.argi1 = moveId;
21604            args.argi2 = status;
21605            args.arg3 = estMillis;
21606            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21607
21608            synchronized (mLastStatus) {
21609                mLastStatus.put(moveId, status);
21610            }
21611        }
21612    }
21613
21614    private final static class OnPermissionChangeListeners extends Handler {
21615        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21616
21617        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21618                new RemoteCallbackList<>();
21619
21620        public OnPermissionChangeListeners(Looper looper) {
21621            super(looper);
21622        }
21623
21624        @Override
21625        public void handleMessage(Message msg) {
21626            switch (msg.what) {
21627                case MSG_ON_PERMISSIONS_CHANGED: {
21628                    final int uid = msg.arg1;
21629                    handleOnPermissionsChanged(uid);
21630                } break;
21631            }
21632        }
21633
21634        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21635            mPermissionListeners.register(listener);
21636
21637        }
21638
21639        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21640            mPermissionListeners.unregister(listener);
21641        }
21642
21643        public void onPermissionsChanged(int uid) {
21644            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21645                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21646            }
21647        }
21648
21649        private void handleOnPermissionsChanged(int uid) {
21650            final int count = mPermissionListeners.beginBroadcast();
21651            try {
21652                for (int i = 0; i < count; i++) {
21653                    IOnPermissionsChangeListener callback = mPermissionListeners
21654                            .getBroadcastItem(i);
21655                    try {
21656                        callback.onPermissionsChanged(uid);
21657                    } catch (RemoteException e) {
21658                        Log.e(TAG, "Permission listener is dead", e);
21659                    }
21660                }
21661            } finally {
21662                mPermissionListeners.finishBroadcast();
21663            }
21664        }
21665    }
21666
21667    private class PackageManagerInternalImpl extends PackageManagerInternal {
21668        @Override
21669        public void setLocationPackagesProvider(PackagesProvider provider) {
21670            synchronized (mPackages) {
21671                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21672            }
21673        }
21674
21675        @Override
21676        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21677            synchronized (mPackages) {
21678                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21679            }
21680        }
21681
21682        @Override
21683        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21684            synchronized (mPackages) {
21685                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21686            }
21687        }
21688
21689        @Override
21690        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21691            synchronized (mPackages) {
21692                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21693            }
21694        }
21695
21696        @Override
21697        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21698            synchronized (mPackages) {
21699                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21700            }
21701        }
21702
21703        @Override
21704        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21705            synchronized (mPackages) {
21706                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21707            }
21708        }
21709
21710        @Override
21711        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21712            synchronized (mPackages) {
21713                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21714                        packageName, userId);
21715            }
21716        }
21717
21718        @Override
21719        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21720            synchronized (mPackages) {
21721                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21722                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21723                        packageName, userId);
21724            }
21725        }
21726
21727        @Override
21728        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21729            synchronized (mPackages) {
21730                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21731                        packageName, userId);
21732            }
21733        }
21734
21735        @Override
21736        public void setKeepUninstalledPackages(final List<String> packageList) {
21737            Preconditions.checkNotNull(packageList);
21738            List<String> removedFromList = null;
21739            synchronized (mPackages) {
21740                if (mKeepUninstalledPackages != null) {
21741                    final int packagesCount = mKeepUninstalledPackages.size();
21742                    for (int i = 0; i < packagesCount; i++) {
21743                        String oldPackage = mKeepUninstalledPackages.get(i);
21744                        if (packageList != null && packageList.contains(oldPackage)) {
21745                            continue;
21746                        }
21747                        if (removedFromList == null) {
21748                            removedFromList = new ArrayList<>();
21749                        }
21750                        removedFromList.add(oldPackage);
21751                    }
21752                }
21753                mKeepUninstalledPackages = new ArrayList<>(packageList);
21754                if (removedFromList != null) {
21755                    final int removedCount = removedFromList.size();
21756                    for (int i = 0; i < removedCount; i++) {
21757                        deletePackageIfUnusedLPr(removedFromList.get(i));
21758                    }
21759                }
21760            }
21761        }
21762
21763        @Override
21764        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21765            synchronized (mPackages) {
21766                // If we do not support permission review, done.
21767                if (!mPermissionReviewRequired) {
21768                    return false;
21769                }
21770
21771                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21772                if (packageSetting == null) {
21773                    return false;
21774                }
21775
21776                // Permission review applies only to apps not supporting the new permission model.
21777                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21778                    return false;
21779                }
21780
21781                // Legacy apps have the permission and get user consent on launch.
21782                PermissionsState permissionsState = packageSetting.getPermissionsState();
21783                return permissionsState.isPermissionReviewRequired(userId);
21784            }
21785        }
21786
21787        @Override
21788        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21789            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21790        }
21791
21792        @Override
21793        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21794                int userId) {
21795            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21796        }
21797
21798        @Override
21799        public void setDeviceAndProfileOwnerPackages(
21800                int deviceOwnerUserId, String deviceOwnerPackage,
21801                SparseArray<String> profileOwnerPackages) {
21802            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21803                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21804        }
21805
21806        @Override
21807        public boolean isPackageDataProtected(int userId, String packageName) {
21808            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21809        }
21810
21811        @Override
21812        public boolean isPackageEphemeral(int userId, String packageName) {
21813            synchronized (mPackages) {
21814                PackageParser.Package p = mPackages.get(packageName);
21815                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21816            }
21817        }
21818
21819        @Override
21820        public boolean wasPackageEverLaunched(String packageName, int userId) {
21821            synchronized (mPackages) {
21822                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21823            }
21824        }
21825
21826        @Override
21827        public void grantRuntimePermission(String packageName, String name, int userId,
21828                boolean overridePolicy) {
21829            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21830                    overridePolicy);
21831        }
21832
21833        @Override
21834        public void revokeRuntimePermission(String packageName, String name, int userId,
21835                boolean overridePolicy) {
21836            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21837                    overridePolicy);
21838        }
21839
21840        @Override
21841        public String getNameForUid(int uid) {
21842            return PackageManagerService.this.getNameForUid(uid);
21843        }
21844
21845        @Override
21846        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21847                Intent origIntent, String resolvedType, Intent launchIntent,
21848                String callingPackage, int userId) {
21849            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21850                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21851        }
21852
21853        public String getSetupWizardPackageName() {
21854            return mSetupWizardPackage;
21855        }
21856    }
21857
21858    @Override
21859    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21860        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21861        synchronized (mPackages) {
21862            final long identity = Binder.clearCallingIdentity();
21863            try {
21864                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21865                        packageNames, userId);
21866            } finally {
21867                Binder.restoreCallingIdentity(identity);
21868            }
21869        }
21870    }
21871
21872    private static void enforceSystemOrPhoneCaller(String tag) {
21873        int callingUid = Binder.getCallingUid();
21874        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21875            throw new SecurityException(
21876                    "Cannot call " + tag + " from UID " + callingUid);
21877        }
21878    }
21879
21880    boolean isHistoricalPackageUsageAvailable() {
21881        return mPackageUsage.isHistoricalPackageUsageAvailable();
21882    }
21883
21884    /**
21885     * Return a <b>copy</b> of the collection of packages known to the package manager.
21886     * @return A copy of the values of mPackages.
21887     */
21888    Collection<PackageParser.Package> getPackages() {
21889        synchronized (mPackages) {
21890            return new ArrayList<>(mPackages.values());
21891        }
21892    }
21893
21894    /**
21895     * Logs process start information (including base APK hash) to the security log.
21896     * @hide
21897     */
21898    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21899            String apkFile, int pid) {
21900        if (!SecurityLog.isLoggingEnabled()) {
21901            return;
21902        }
21903        Bundle data = new Bundle();
21904        data.putLong("startTimestamp", System.currentTimeMillis());
21905        data.putString("processName", processName);
21906        data.putInt("uid", uid);
21907        data.putString("seinfo", seinfo);
21908        data.putString("apkFile", apkFile);
21909        data.putInt("pid", pid);
21910        Message msg = mProcessLoggingHandler.obtainMessage(
21911                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21912        msg.setData(data);
21913        mProcessLoggingHandler.sendMessage(msg);
21914    }
21915
21916    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21917        return mCompilerStats.getPackageStats(pkgName);
21918    }
21919
21920    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21921        return getOrCreateCompilerPackageStats(pkg.packageName);
21922    }
21923
21924    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21925        return mCompilerStats.getOrCreatePackageStats(pkgName);
21926    }
21927
21928    public void deleteCompilerPackageStats(String pkgName) {
21929        mCompilerStats.deletePackageStats(pkgName);
21930    }
21931
21932    @Override
21933    public int getInstallReason(String packageName, int userId) {
21934        enforceCrossUserPermission(Binder.getCallingUid(), userId,
21935                true /* requireFullPermission */, false /* checkShell */,
21936                "get install reason");
21937        synchronized (mPackages) {
21938            final PackageSetting ps = mSettings.mPackages.get(packageName);
21939            if (ps != null) {
21940                return ps.getInstallReason(userId);
21941            }
21942        }
21943        return PackageManager.INSTALL_REASON_UNKNOWN;
21944    }
21945}
21946