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